diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 998b25427..8061997cf 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,12 +1,12 @@ (Click "Preview" to turn any http URL into a clickable link) -1. PLEASE CAREFULLY READ: [Contributing Guidelines](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md). By submitting a PR you are agreeing with the [CLA](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md#copyright--contributor-license-agreement). +1. PLEASE CAREFULLY READ: [Contributing Guidelines](https://github.com/ocornut/imgui/blob/master/docs/CONTRIBUTING.md) 2. **Make sure you're using a special branch just for this pull request**. (In git, 1 PR = 1 branch. If you update the branch the PR will be updated.) 3. Consider running the [imgui_test_suite](https://github.com/ocornut/imgui_test_engine) or adding new tests to test for expected behaviors. -4. PLEASE DO NOT SUBMIT AI-GENERATED PROSE. ONLY SUBMIT CODE THAT YOU REVIEWED AND UNDERSTAND. Submissions that are lacking proper human review/judgement before being passed to us are not welcome. +4. PLEASE DO NOT SUBMIT AI SLOP OR AUTOMATED AI REPORTS. Submissions that are lacking proper human review/judgement before being passed to us are not welcome. Do not let a LLM AI write most of the text for you. 5. Clear this template before submitting your PR. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5f0acd670..4e276e1de 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -77,7 +77,7 @@ jobs: run: | cd examples\example_null call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" - .\build_win.bat /W4 + .\build_win32.bat /W4 - name: Build example_null (single file build) shell: bash @@ -268,39 +268,6 @@ jobs: shell: cmd run: '"%MSBUILD_PATH%\MSBuild.exe" examples/example_win32_directx12/example_win32_directx12.vcxproj /p:Platform=x64 /p:Configuration=Release' - Build-Windows-ARM64: - runs-on: windows-11-arm - name: Build - Windows ARM64 - - defaults: - run: - working-directory: ${{ github.workspace }}/imgui - - env: - VS_PATH: C:\Program Files\Microsoft Visual Studio\18\Enterprise - steps: - - uses: actions/checkout@v6 - with: - path: ${{ github.workspace }}/imgui - - - name: Build example_null (extra warnings, msvc arm64) - shell: cmd - run: | - cd examples\example_null - call "%VS_PATH%\VC\Auxiliary\Build\vcvarsarm64.bat" - .\build_win.bat /W4 - - - name: Run example_null (msvc arm64) - shell: cmd - run: examples\example_null\Debug\example_null.exe - - - name: Build example_win32_directx11 (msvc arm64) - shell: cmd - run: | - cd examples\example_win32_directx11 - call "%VS_PATH%\VC\Auxiliary\Build\vcvarsarm64.bat" - .\build_win.bat - Build-Linux: runs-on: ubuntu-latest name: Build - Linux @@ -556,7 +523,7 @@ jobs: - name: Install Dependencies run: | - brew install glfw sdl2 sdl3 + brew install glfw3 sdl2 sdl3 - name: Build example_null (extra warnings, clang 64-bit) run: make -C examples/example_null WITH_EXTRA_WARNINGS=1 @@ -639,7 +606,7 @@ jobs: if: github.event_name == 'workflow_run' Build-iOS: - runs-on: macos-26 + runs-on: macos-14 name: Build - iOS steps: diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index d092fd714..231d3a972 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -23,16 +23,9 @@ jobs: run: | if [[ "$PVS_STUDIO_LICENSE" != "" ]]; then - wget -qO pvs-key.asc https://files.pvs-studio.com/etc/pubkey.txt - gpg --dearmor -o pvs-key.gpg pvs-key.asc - sudo install -D -m 644 pvs-key.gpg /etc/apt/keyrings/pvs-studio.gpg - wget -qO viva64.list https://files.pvs-studio.com/etc/viva64.list - sed -E \ - -e 's|^deb \[|deb [signed-by=/etc/apt/keyrings/pvs-studio.gpg |; t' \ - -e 's|^deb |deb [signed-by=/etc/apt/keyrings/pvs-studio.gpg] |' \ - viva64.list > viva64-scoped.list - sudo install -m 644 viva64-scoped.list /etc/apt/sources.list.d/viva64.list - + wget -q https://files.pvs-studio.com/etc/pubkey.txt + sudo apt-key add pubkey.txt + sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.pvs-studio.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 diff --git a/.gitignore b/.gitignore index 730857c1b..009e61ede 100644 --- a/.gitignore +++ b/.gitignore @@ -66,7 +66,6 @@ cmake-build-* ## Unix executables from our example Makefiles examples/example_apple_metal/example_apple_metal -examples/example_apple_metal4/example_apple_metal4 examples/example_apple_opengl2/example_apple_opengl2 examples/example_apple_opengl3/example_apple_opengl3 examples/example_glfw_metal/example_glfw_metal diff --git a/backends/imgui_impl_dx10.cpp b/backends/imgui_impl_dx10.cpp index a81d81305..cb767d6ac 100644 --- a/backends/imgui_impl_dx10.cpp +++ b/backends/imgui_impl_dx10.cpp @@ -101,11 +101,6 @@ static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplDX10_RenderState* ImGui_ImplDX10_GetRenderState() -{ - return (ImGui_ImplDX10_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - // Functions static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device) { diff --git a/backends/imgui_impl_dx10.h b/backends/imgui_impl_dx10.h index 3ab1669a9..6f75693f0 100644 --- a/backends/imgui_impl_dx10.h +++ b/backends/imgui_impl_dx10.h @@ -46,6 +46,7 @@ struct ImGui_ImplDX10_RenderState //ID3D10SamplerState* SamplerLinear; // Use ImDrawList::AddCallback(ImGui::GetPlatform().DrawCallback_SetSamplerLinear) //ID3D10SamplerState* SamplerNearest; // Use ImDrawList::AddCallback(ImGui::GetPlatform().DrawCallback_SetSamplerNearest) }; -IMGUI_IMPL_API ImGui_ImplDX10_RenderState* ImGui_ImplDX10_GetRenderState(); + +static inline ImGui_ImplDX10_RenderState* ImGui_ImplDX10_GetRenderState() { return (ImGui_ImplDX10_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_dx11.cpp b/backends/imgui_impl_dx11.cpp index a7d2cdf73..ff0a607c4 100644 --- a/backends/imgui_impl_dx11.cpp +++ b/backends/imgui_impl_dx11.cpp @@ -103,11 +103,6 @@ static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplDX11_RenderState* ImGui_ImplDX11_GetRenderState() -{ - return (ImGui_ImplDX11_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - // Functions static void ImGui_ImplDX11_SetupRenderState(const ImDrawData* draw_data, ID3D11DeviceContext* device_ctx) { diff --git a/backends/imgui_impl_dx11.h b/backends/imgui_impl_dx11.h index 5fd8ddca9..2fe392dfa 100644 --- a/backends/imgui_impl_dx11.h +++ b/backends/imgui_impl_dx11.h @@ -48,6 +48,7 @@ struct ImGui_ImplDX11_RenderState //ID3D11SamplerState* SamplerLinear; // Use ImDrawList::AddCallback(ImGui::GetPlatform().DrawCallback_SetSamplerLinear) //ID3D11SamplerState* SamplerNearest; // Use ImDrawList::AddCallback(ImGui::GetPlatform().DrawCallback_SetSamplerNearest) }; -IMGUI_IMPL_API ImGui_ImplDX11_RenderState* ImGui_ImplDX11_GetRenderState(); + +static inline ImGui_ImplDX11_RenderState* ImGui_ImplDX11_GetRenderState() { return (ImGui_ImplDX11_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_dx12.cpp b/backends/imgui_impl_dx12.cpp index 22a9bdc97..e5b314eb1 100644 --- a/backends/imgui_impl_dx12.cpp +++ b/backends/imgui_impl_dx12.cpp @@ -133,11 +133,6 @@ static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplDX12_RenderState* ImGui_ImplDX12_GetRenderState() -{ - return (ImGui_ImplDX12_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - // Buffers used during the rendering of a frame struct ImGui_ImplDX12_RenderBuffers { diff --git a/backends/imgui_impl_dx12.h b/backends/imgui_impl_dx12.h index 106b4b4d2..a8f3a6cf6 100644 --- a/backends/imgui_impl_dx12.h +++ b/backends/imgui_impl_dx12.h @@ -74,7 +74,8 @@ struct ImGui_ImplDX12_RenderState ID3D12Device* Device; ID3D12GraphicsCommandList* CommandList; }; -IMGUI_IMPL_API ImGui_ImplDX12_RenderState* ImGui_ImplDX12_GetRenderState(); + +static inline ImGui_ImplDX12_RenderState* ImGui_ImplDX12_GetRenderState() { return (ImGui_ImplDX12_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy initialization API Obsoleted in 1.91.5 diff --git a/backends/imgui_impl_dx9.cpp b/backends/imgui_impl_dx9.cpp index 10d0dc21e..360398f04 100644 --- a/backends/imgui_impl_dx9.cpp +++ b/backends/imgui_impl_dx9.cpp @@ -17,7 +17,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-13: DirectX9: Pre-transforming vertices and using `D3DFVF_XYZRHW` vertex format, largely increasing performances when in `D3DCREATE_SOFTWARE_VERTEXPROCESSING` mode. (#9628) // 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. (#9378) // 2026-03-19: Fixed issue in ImGui_ImplDX9_UpdateTexture() if ImTextureID_Invalid is defined to be != 0, which became the default since 2026-03-12. (#9295, #9310) // 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. @@ -72,11 +71,10 @@ struct ImGui_ImplDX9_Data struct CUSTOMVERTEX { float pos[3]; - float rhw; D3DCOLOR col; float uv[2]; }; -#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE|D3DFVF_TEX1) +#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) #ifdef IMGUI_USE_BGRA_PACKED_COLOR #define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL) @@ -143,7 +141,7 @@ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data) device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); - // Setup orthographic projection matrix for custom draw callbacks. Our pretransformed vertices bypass these transforms. + // Setup orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. // Being agnostic of whether or can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() { @@ -234,19 +232,18 @@ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) return; } - // Copy and pre-transform all vertices into a single contiguous buffer, convert colors to DX9 default format. - // XYZRHW bypasses vertex processing, avoiding repeated software transforms for each draw command. Apply DX9's half-pixel offset here. - // Define IMGUI_USE_BGRA_PACKED_COLOR in imconfig.h to avoid repacking colors. - const ImVec2 pos_offset(draw_data->DisplayPos.x + 0.5f, draw_data->DisplayPos.y + 0.5f); + // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. + // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and + // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR + // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; } for (const ImDrawList* draw_list : draw_data->CmdLists) { const ImDrawVert* vtx_src = draw_list->VtxBuffer.Data; for (int i = 0; i < draw_list->VtxBuffer.Size; i++) { - vtx_dst->pos[0] = vtx_src->pos.x - pos_offset.x; - vtx_dst->pos[1] = vtx_src->pos.y - pos_offset.y; - vtx_dst->pos[2] = 0.5f; - vtx_dst->rhw = 1.0f; + vtx_dst->pos[0] = vtx_src->pos.x; + vtx_dst->pos[1] = vtx_src->pos.y; + vtx_dst->pos[2] = 0.0f; vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col); vtx_dst->uv[0] = vtx_src->uv.x; vtx_dst->uv[1] = vtx_src->uv.y; diff --git a/backends/imgui_impl_glfw.cpp b/backends/imgui_impl_glfw.cpp index 9cbffafb6..678129a07 100644 --- a/backends/imgui_impl_glfw.cpp +++ b/backends/imgui_impl_glfw.cpp @@ -663,7 +663,7 @@ void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows) #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817 void ImGui_ImplGlfw_EmscriptenOpenURL(const char* url) { if (url) emscripten::glfw3::OpenURL(url); } #else -EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank', 'noopener'); }); +EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); #endif #endif @@ -748,13 +748,11 @@ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, Glfw // Windows: register a WndProc hook so we can intercept some messages. #ifdef _WIN32 - if (HWND hwnd = (HWND)main_viewport->PlatformHandleRaw) - { - ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", bd); - bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC); - IM_ASSERT(bd->PrevWndProc != nullptr); - ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); - } + HWND hwnd = (HWND)main_viewport->PlatformHandleRaw; + ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", bd); + bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC); + IM_ASSERT(bd->PrevWndProc != nullptr); + ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc); #endif // Emscripten: the same application can run on various platforms, so we detect the Apple platform at runtime @@ -814,12 +812,9 @@ void ImGui_ImplGlfw_Shutdown() // Windows: restore our WndProc hook #ifdef _WIN32 ImGuiViewport* main_viewport = ImGui::GetMainViewport(); - if (HWND hwnd = (HWND)main_viewport->PlatformHandleRaw) - { - ::SetPropA(hwnd, "IMGUI_BACKEND_DATA", nullptr); - ::SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); - bd->PrevWndProc = nullptr; - } + ::SetPropA((HWND)main_viewport->PlatformHandleRaw, "IMGUI_BACKEND_DATA", nullptr); + ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc); + bd->PrevWndProc = nullptr; #endif io.BackendPlatformName = nullptr; diff --git a/backends/imgui_impl_metal.mm b/backends/imgui_impl_metal.mm index 43019b54f..55b33de14 100644 --- a/backends/imgui_impl_metal.mm +++ b/backends/imgui_impl_metal.mm @@ -16,7 +16,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-10-06: Added support for render passes with multiple color attachments: we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-04-28: Added support for standard draw callbacks (in platform_io): DrawCallback_SetSamplerLinear and DrawCallback_SetSamplerNearest. (#9378, #9381) // 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState (others are not yet supported). (#9378) @@ -59,16 +58,14 @@ - (instancetype)initWithBuffer:(id)buffer; @end -#define IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS 8 // Metal's limit (see Metal Feature Set Tables). Not configurable. - // 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) MTLPixelFormat colorPixelFormat; @property (nonatomic, assign) MTLPixelFormat depthPixelFormat; @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat; - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor; -- (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index; @end @interface MetalTexture : NSObject @@ -480,33 +477,23 @@ void ImGui_ImplMetal_Shutdown() #pragma mark - FramebufferDescriptor implementation @implementation FramebufferDescriptor -{ - MTLPixelFormat _colorPixelFormats[IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS]; -} - - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor { if ((self = [super init])) { _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount; - for (NSUInteger n = 0; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) - _colorPixelFormats[n] = renderPassDescriptor.colorAttachments[n].texture.pixelFormat; + _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat; _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat; _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat; } return self; } -- (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index -{ - return _colorPixelFormats[index]; -} - - (nonnull id)copyWithZone:(nullable NSZone*)zone { FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init]; copy.sampleCount = self.sampleCount; - memcpy(copy->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)); + copy.colorPixelFormat = self.colorPixelFormat; copy.depthPixelFormat = self.depthPixelFormat; copy.stencilPixelFormat = self.stencilPixelFormat; return copy; @@ -515,12 +502,10 @@ void ImGui_ImplMetal_Shutdown() - (NSUInteger)hash { NSUInteger sc = _sampleCount & 0x3; - NSUInteger cf = _colorPixelFormats[0] & 0x3FF; + NSUInteger cf = _colorPixelFormat & 0x3FF; NSUInteger df = _depthPixelFormat & 0x3FF; NSUInteger sf = _stencilPixelFormat & 0x3FF; NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc; - for (NSUInteger n = 1; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) - hash = hash * 31 + _colorPixelFormats[n]; return hash; } @@ -530,7 +515,7 @@ void ImGui_ImplMetal_Shutdown() if (![other isKindOfClass:[FramebufferDescriptor class]]) return NO; return other.sampleCount == self.sampleCount && - memcmp(other->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)) == 0 && + other.colorPixelFormat == self.colorPixelFormat && other.depthPixelFormat == self.depthPixelFormat && other.stencilPixelFormat == self.stencilPixelFormat; } @@ -676,7 +661,7 @@ void ImGui_ImplMetal_Shutdown() pipelineDescriptor.fragmentFunction = fragmentFunction; pipelineDescriptor.vertexDescriptor = vertexDescriptor; pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount; - pipelineDescriptor.colorAttachments[0].pixelFormat = [self.framebufferDescriptor colorPixelFormatAtIndex:0]; + pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat; pipelineDescriptor.colorAttachments[0].blendingEnabled = YES; pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd; pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha; @@ -684,11 +669,6 @@ void ImGui_ImplMetal_Shutdown() pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd; pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne; pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha; - for (NSUInteger n = 1; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) // Don't write to other color attachments, if any. - { - pipelineDescriptor.colorAttachments[n].pixelFormat = [self.framebufferDescriptor colorPixelFormatAtIndex:n]; - pipelineDescriptor.colorAttachments[n].writeMask = MTLColorWriteMaskNone; - } pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat; pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat; diff --git a/backends/imgui_impl_metal4.h b/backends/imgui_impl_metal4.h index 9ef6e06ef..b5b54cad0 100644 --- a/backends/imgui_impl_metal4.h +++ b/backends/imgui_impl_metal4.h @@ -38,7 +38,6 @@ IMGUI_IMPL_API bool ImGui_ImplMetal4_Init(id device, id commandBuffer, diff --git a/backends/imgui_impl_metal4.mm b/backends/imgui_impl_metal4.mm index e5d3e3472..73f8c5905 100644 --- a/backends/imgui_impl_metal4.mm +++ b/backends/imgui_impl_metal4.mm @@ -19,8 +19,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-16: Worked around rendering artifacts by aligning 16-bit index buffer addresses to 4 bytes. / Fixed vertex/index buffers being reused by a later draw in the same frame. (#9622, #9625) / Remove the residency set from the command queue on shutdown so the queue can be reused. -// 2026-10-06: Added support for render passes with multiple color attachments: we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-07: Metal 4: Added metal-cpp support. (#9461) // 2026-07-02: Metal 4: Added new Metal 4 backend implementation. (#9458) @@ -37,32 +35,28 @@ #pragma mark - Support classes and structs -#define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) - struct ImGui_Metal4_ConstantData { float ModelViewProjectionMatrix[4][4]; }; -@interface Metal4Buffer : NSObject +@interface MetalBuffer : NSObject @property (nonatomic, strong) id buffer; @property (nonatomic, assign) double lastReuseTime; - (instancetype)initWithBuffer:(id)buffer; @end -#define IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS 8 // Metal's limit (see Metal Feature Set Tables). Not configurable. - // An object that encapsulates the data necessary to uniquely identify a // render pipeline state. These are used as cache keys. -@interface Metal4FramebufferDescriptor : NSObject +@interface FramebufferDescriptor : NSObject @property (nonatomic, assign) unsigned long sampleCount; +@property (nonatomic, assign) MTLPixelFormat colorPixelFormat; @property (nonatomic, assign) MTLPixelFormat depthPixelFormat; @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat; - (instancetype)initWithRenderPassDescriptor:(MTL4RenderPassDescriptor*)renderPassDescriptor; -- (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index; @end -@interface Metal4Texture : NSObject +@interface MetalTexture : NSObject @property (nonatomic, strong) id metalTexture; - (instancetype)initWithTexture:(id)metalTexture; @end @@ -70,7 +64,7 @@ struct ImGui_Metal4_ConstantData // 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 Metal4Context : NSObject +@interface MetalContext : NSObject @property (nonatomic, strong) id device; @property (nonatomic, strong) id commandQueue; @property (nonatomic, strong) id depthStencilState; @@ -78,25 +72,24 @@ struct ImGui_Metal4_ConstantData @property (nonatomic, strong) id samplerStateLinear; @property (nonatomic, strong) id samplerStateNearest; @property (nonatomic, strong) id residencySet; -@property (nonatomic, strong) Metal4FramebufferDescriptor* framebufferDescriptor; +@property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; @property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; @property (nonatomic, assign) NSUInteger framesInFlight; @property (nonatomic, assign) NSUInteger currentFrameSlot; @property (nonatomic, strong) NSArray>* constantBuffers; @property (nonatomic, assign) ImGui_Metal4_ConstantData** constantBufferContentsArray; -@property (nonatomic, strong) NSMutableArray*>* bufferCaches; -@property (nonatomic, strong) NSMutableArray*>* buffersInFlight; // per frame slot: buffers used since its last NewFrame(), may still be read by the GPU +@property (nonatomic, strong) NSMutableArray*>* bufferCaches; @property (nonatomic, strong) NSObject* bufferCacheLock; @property (nonatomic, assign) double lastBufferCachePurge; - (id)currentConstantBuffer; - (ImGui_Metal4_ConstantData*)currentConstantBufferContents; -- (Metal4Buffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; -- (id)renderPipelineStateForFramebufferDescriptor:(Metal4FramebufferDescriptor*)descriptor device:(id)device; +- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; +- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device; @end struct ImGui_ImplMetal4_Data { - Metal4Context* SharedMetalContext; + MetalContext* SharedMetalContext; id RenderCommandEncoder; ImGui_ImplMetal4_Data() { memset((void*)this, 0, sizeof(*this)); } @@ -130,7 +123,7 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, (__bridge id)(commandEncoder)); } -bool ImGui_ImplMetal4_CreateDeviceObjects(MTL::Device* device) +bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device) { return ImGui_ImplMetal4_CreateDeviceObjects((__bridge id)(device)); } @@ -143,27 +136,20 @@ void ImGui_ImplMetal4_NewFrame(MTL4RenderPassDescriptor* renderPassDescriptor, i { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal4_Init()?"); - IM_ASSERT(frameInFlightIndex < (int)bd->SharedMetalContext.framesInFlight && "frameInFlightIndex out of range! See framesInFlight passed to ImGui_ImplMetal4_Init()."); + IM_ASSERT(frameInFlightIndex < bd->SharedMetalContext.framesInFlight && "frameInFlightIndex out of range! See framesInFlight passed to ImGui_ImplMetal4_Init()."); #ifdef IMGUI_IMPL_METAL_CPP - bd->SharedMetalContext.framebufferDescriptor = [[[Metal4FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; + bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; #else - bd->SharedMetalContext.framebufferDescriptor = [[Metal4FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; + bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; #endif bd->SharedMetalContext.currentFrameSlot = (NSUInteger)frameInFlightIndex; if (bd->SharedMetalContext.depthStencilState == nil) ImGui_ImplMetal4_CreateDeviceObjects(bd->SharedMetalContext.device); - - // The application has finished GPU work for this slot before reusing it. - @synchronized(bd->SharedMetalContext.bufferCacheLock) - { - [bd->SharedMetalContext.bufferCaches[frameInFlightIndex] addObjectsFromArray:bd->SharedMetalContext.buffersInFlight[frameInFlightIndex]]; - [bd->SharedMetalContext.buffersInFlight[frameInFlightIndex] removeAllObjects]; - } } static void ImGui_ImplMetal4_SetupRenderState(ImDrawData* draw_data, id commandBuffer, id commandEncoder, id renderPipelineState, - Metal4Buffer* vertexBuffer, size_t vertexBufferOffset) + MetalBuffer* vertexBuffer, size_t vertexBufferOffset) { IM_UNUSED(commandBuffer); ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); @@ -215,7 +201,7 @@ static void ImGui_ImplMetal4_DrawCallback_SetSamplerNearest(const ImDrawList*, c void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, id commandBuffer, id commandEncoder) { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); - Metal4Context* ctx = bd->SharedMetalContext; + MetalContext* ctx = bd->SharedMetalContext; // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x + 0.5f); @@ -244,18 +230,8 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idTotalVtxCount * sizeof(ImDrawVert); size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx); - // Work around Metal 4 corrupting draws whose 16-bit index buffer address is only 2-byte aligned. - // Pack each draw at a 4-byte boundary, with at most one padding index per draw. - if (sizeof(ImDrawIdx) == 2) - { - indexBufferLength = 0; - for (const ImDrawList* draw_list : draw_data->CmdLists) - for (const ImDrawCmd& cmd : draw_list->CmdBuffer) - if (cmd.UserCallback == nullptr) - indexBufferLength += MEMALIGN((size_t)cmd.ElemCount * sizeof(ImDrawIdx), 4); - } - Metal4Buffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; - Metal4Buffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; + MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; + MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; bd->RenderCommandEncoder = commandEncoder; ImGui_ImplMetal4_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0); @@ -270,8 +246,7 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idCmdLists) { memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); - if (sizeof(ImDrawIdx) == 4) - memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) { @@ -322,31 +297,22 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idSharedMetalContext.argumentTable setAddress:(vertexBuffer.buffer.gpuAddress + vertexBufferOffset + (pcmd->VtxOffset * sizeof(ImDrawVert))) attributeStride:sizeof(ImDrawVert) atIndex:0]; size_t indexBufferCmdOffset = indexBufferOffset + (pcmd->IdxOffset * sizeof(ImDrawIdx)); - size_t indexBufferCmdLength = (size_t)pcmd->ElemCount * sizeof(ImDrawIdx); - if (sizeof(ImDrawIdx) == 2) - { - indexBufferCmdOffset = indexBufferOffset; - memcpy((char*)indexBuffer.buffer.contents + indexBufferCmdOffset, draw_list->IdxBuffer.Data + pcmd->IdxOffset, indexBufferCmdLength); - indexBufferOffset += MEMALIGN(indexBufferCmdLength, 4); - } [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle indexCount:pcmd->ElemCount indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32 indexBuffer:indexBuffer.buffer.gpuAddress + indexBufferCmdOffset - indexBufferLength:indexBufferCmdLength]; + indexBufferLength:indexBuffer.buffer.length - indexBufferCmdOffset]; } } vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert); - if (sizeof(ImDrawIdx) == 4) - indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); + indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); } - Metal4Context* sharedMetalContext = bd->SharedMetalContext; + MetalContext* sharedMetalContext = bd->SharedMetalContext; @synchronized(sharedMetalContext.bufferCacheLock) { - // Keep these buffers alive and out of the cache until the next NewFrame() for this slot. - NSMutableArray* slotCache = sharedMetalContext.buffersInFlight[sharedMetalContext.currentFrameSlot]; + NSMutableArray* slotCache = sharedMetalContext.bufferCaches[sharedMetalContext.currentFrameSlot]; [slotCache addObject:vertexBuffer]; [slotCache addObject:indexBuffer]; } @@ -358,7 +324,7 @@ void ImGui_ImplMetal4_RenderDrawData(ImDrawData* draw_data, idBackendUserData)) + if (MetalTexture* backend_tex = (__bridge_transfer MetalTexture*)(tex->BackendUserData)) { IM_ASSERT(backend_tex.metalTexture == (__bridge id)(void*)(intptr_t)tex->TexID); backend_tex.metalTexture = nil; @@ -394,7 +360,7 @@ void ImGui_ImplMetal4_UpdateTexture(ImTextureData* tex) id texture = [bd->SharedMetalContext.device newTextureWithDescriptor:textureDescriptor]; [bd->SharedMetalContext.residencySet addAllocation:texture]; [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)tex->Width, (NSUInteger)tex->Height) mipmapLevel:0 withBytes:tex->Pixels bytesPerRow:(NSUInteger)tex->Width * 4]; - Metal4Texture* backend_tex = [[Metal4Texture alloc] initWithTexture:texture]; + MetalTexture* backend_tex = [[MetalTexture alloc] initWithTexture:texture]; // Store identifiers tex->SetTexID((ImTextureID)(intptr_t)texture); @@ -405,7 +371,7 @@ void ImGui_ImplMetal4_UpdateTexture(ImTextureData* tex) { // Update selected blocks. We only ever write to textures regions which have never been used before! // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region. - Metal4Texture* backend_tex = (__bridge Metal4Texture*)(tex->BackendUserData); + MetalTexture* backend_tex = (__bridge MetalTexture*)(tex->BackendUserData); for (ImTextureRect& r : tex->Updates) { [backend_tex.metalTexture replaceRegion:MTLRegionMake2D((NSUInteger)r.x, (NSUInteger)r.y, (NSUInteger)r.w, (NSUInteger)r.h) @@ -425,15 +391,14 @@ bool ImGui_ImplMetal4_CreateDeviceObjects(id device) { ImGui_ImplMetal4_Data* bd = ImGui_ImplMetal4_GetBackendData(); + MTLResidencySetDescriptor* residencySetDescriptor = [[MTLResidencySetDescriptor alloc] init]; + residencySetDescriptor.initialCapacity = 1000; + NSError* error = nil; - if (bd->SharedMetalContext.residencySet == nil) - { - MTLResidencySetDescriptor* residencySetDescriptor = [[MTLResidencySetDescriptor alloc] init]; - residencySetDescriptor.initialCapacity = 1000; - bd->SharedMetalContext.residencySet = [device newResidencySetWithDescriptor:residencySetDescriptor error:&error]; - IM_ASSERT(bd->SharedMetalContext.residencySet != nil && error == nil); - [bd->SharedMetalContext.commandQueue addResidencySet:bd->SharedMetalContext.residencySet]; - } + bd->SharedMetalContext.residencySet = [device newResidencySetWithDescriptor:residencySetDescriptor error:&error]; + IM_ASSERT(bd->SharedMetalContext.residencySet != nil && error == nil); + + [bd->SharedMetalContext.commandQueue addResidencySet:bd->SharedMetalContext.residencySet]; MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init]; depthStencilDescriptor.depthWriteEnabled = NO; @@ -506,19 +471,14 @@ bool ImGui_ImplMetal4_Init(id device, id commandQue platform_io.DrawCallback_SetSamplerLinear = ImGui_ImplMetal4_DrawCallback_SetSamplerLinear; platform_io.DrawCallback_SetSamplerNearest = ImGui_ImplMetal4_DrawCallback_SetSamplerNearest; - bd->SharedMetalContext = [[Metal4Context alloc] init]; + bd->SharedMetalContext = [[MetalContext alloc] init]; bd->SharedMetalContext.device = device; bd->SharedMetalContext.commandQueue = commandQueue; bd->SharedMetalContext.framesInFlight = (NSUInteger)framesInFlight; - NSMutableArray*>* bufferCaches = [NSMutableArray array]; - NSMutableArray*>* buffersInFlight = [NSMutableArray array]; - for (NSUInteger i = 0; i < (NSUInteger)framesInFlight; i++) - { + NSMutableArray*>* bufferCaches = [NSMutableArray array]; + for (NSUInteger i = 0; i < framesInFlight; i++) [bufferCaches addObject:[NSMutableArray array]]; - [buffersInFlight addObject:[NSMutableArray array]]; - } bd->SharedMetalContext.bufferCaches = bufferCaches; - bd->SharedMetalContext.buffersInFlight = buffersInFlight; return true; } @@ -531,8 +491,6 @@ void ImGui_ImplMetal4_Shutdown() ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); ImGui_ImplMetal4_DestroyDeviceObjects(); - if (bd->SharedMetalContext.residencySet != nil) - [bd->SharedMetalContext.commandQueue removeResidencySet:bd->SharedMetalContext.residencySet]; ImGui_ImplMetal4_DestroyBackendData(); io.BackendRendererName = nullptr; @@ -541,7 +499,7 @@ void ImGui_ImplMetal4_Shutdown() platform_io.ClearRendererHandlers(); } -@implementation Metal4Buffer +@implementation MetalBuffer - (instancetype)initWithBuffer:(id)buffer { if ((self = [super init])) @@ -553,36 +511,26 @@ void ImGui_ImplMetal4_Shutdown() } @end -#pragma mark - Metal4FramebufferDescriptor implementation - -@implementation Metal4FramebufferDescriptor -{ - MTLPixelFormat _colorPixelFormats[IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS]; -} +#pragma mark - FramebufferDescriptor implementation +@implementation FramebufferDescriptor - (instancetype)initWithRenderPassDescriptor:(MTL4RenderPassDescriptor*)renderPassDescriptor { if ((self = [super init])) { _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount; - for (NSUInteger n = 0; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) - _colorPixelFormats[n] = renderPassDescriptor.colorAttachments[n].texture.pixelFormat; + _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat; _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat; _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat; } return self; } -- (MTLPixelFormat)colorPixelFormatAtIndex:(NSUInteger)index -{ - return _colorPixelFormats[index]; -} - - (nonnull id)copyWithZone:(nullable NSZone*)zone { - Metal4FramebufferDescriptor* copy = [[Metal4FramebufferDescriptor allocWithZone:zone] init]; + FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init]; copy.sampleCount = self.sampleCount; - memcpy(copy->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)); + copy.colorPixelFormat = self.colorPixelFormat; copy.depthPixelFormat = self.depthPixelFormat; copy.stencilPixelFormat = self.stencilPixelFormat; return copy; @@ -591,31 +539,29 @@ void ImGui_ImplMetal4_Shutdown() - (NSUInteger)hash { NSUInteger sc = _sampleCount & 0x3; - NSUInteger cf = _colorPixelFormats[0] & 0x3FF; + NSUInteger cf = _colorPixelFormat & 0x3FF; NSUInteger df = _depthPixelFormat & 0x3FF; NSUInteger sf = _stencilPixelFormat & 0x3FF; NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc; - for (NSUInteger n = 1; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) - hash = hash * 31 + _colorPixelFormats[n]; return hash; } - (BOOL)isEqual:(id)object { - Metal4FramebufferDescriptor* other = object; - if (![other isKindOfClass:[Metal4FramebufferDescriptor class]]) + FramebufferDescriptor* other = object; + if (![other isKindOfClass:[FramebufferDescriptor class]]) return NO; return other.sampleCount == self.sampleCount && - memcmp(other->_colorPixelFormats, _colorPixelFormats, sizeof(_colorPixelFormats)) == 0 && + other.colorPixelFormat == self.colorPixelFormat && other.depthPixelFormat == self.depthPixelFormat && other.stencilPixelFormat == self.stencilPixelFormat; } @end -#pragma mark - Metal4Texture implementation +#pragma mark - MetalTexture implementation -@implementation Metal4Texture +@implementation MetalTexture - (instancetype)initWithTexture:(id)metalTexture { if ((self = [super init])) @@ -625,9 +571,9 @@ void ImGui_ImplMetal4_Shutdown() @end -#pragma mark - Metal4Context implementation +#pragma mark - MetalContext implementation -@implementation Metal4Context +@implementation MetalContext - (instancetype)init { if ((self = [super init])) @@ -654,20 +600,20 @@ void ImGui_ImplMetal4_Shutdown() return self.constantBufferContentsArray[self.currentFrameSlot]; } -- (Metal4Buffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device +- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device { double now = GetMachAbsoluteTimeInSeconds(); - NSMutableArray* slotCache = self.bufferCaches[self.currentFrameSlot]; + NSMutableArray* slotCache = self.bufferCaches[self.currentFrameSlot]; @synchronized(self.bufferCacheLock) { // Purge old buffers that haven't been useful for a while if (now - self.lastBufferCachePurge > 1.0) { - for (NSMutableArray* cache in self.bufferCaches) + for (NSMutableArray* cache in self.bufferCaches) { NSMutableArray* survivors = [NSMutableArray array]; - for (Metal4Buffer* candidate in cache) + for (MetalBuffer* candidate in cache) if (candidate.lastReuseTime > self.lastBufferCachePurge) [survivors addObject:candidate]; [cache setArray:survivors]; @@ -676,8 +622,8 @@ void ImGui_ImplMetal4_Shutdown() } // See if we have a buffer we can reuse, from this frame-in-flight slot's own cache - Metal4Buffer* bestCandidate = nil; - for (Metal4Buffer* candidate in slotCache) + MetalBuffer* bestCandidate = nil; + for (MetalBuffer* candidate in slotCache) if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime)) bestCandidate = candidate; @@ -692,7 +638,7 @@ void ImGui_ImplMetal4_Shutdown() // No luck; make a new buffer id backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared]; [self.residencySet addAllocation:backing]; - return [[Metal4Buffer alloc] initWithBuffer:backing]; + return [[MetalBuffer alloc] initWithBuffer:backing]; } const char* shaderCode = R"( @@ -734,7 +680,7 @@ fragment half4 fragment_main(VertexOut in [[stage_in]], } )"; -- (id)renderPipelineStateForFramebufferDescriptor:(Metal4FramebufferDescriptor*)descriptor device:(id)device +- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device { NSError* error = nil; @@ -773,7 +719,7 @@ fragment half4 fragment_main(VertexOut in [[stage_in]], pipelineDescriptor.fragmentFunction = fragmentFunction; pipelineDescriptor.vertexDescriptor = vertexDescriptor; pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount; - pipelineDescriptor.colorAttachments[0].pixelFormat = [self.framebufferDescriptor colorPixelFormatAtIndex:0]; + pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat; pipelineDescriptor.colorAttachments[0].blendingEnabled = YES; pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd; pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha; @@ -781,11 +727,6 @@ fragment half4 fragment_main(VertexOut in [[stage_in]], pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd; pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne; pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha; - for (NSUInteger n = 1; n < IMGUI_IMPL_METAL_MAX_COLOR_ATTACHMENTS; n++) // Don't write to other color attachments, if any. - { - pipelineDescriptor.colorAttachments[n].pixelFormat = [self.framebufferDescriptor colorPixelFormatAtIndex:n]; - pipelineDescriptor.colorAttachments[n].writeMask = MTLColorWriteMaskNone; - } pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat; pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat; diff --git a/backends/imgui_impl_opengl3.cpp b/backends/imgui_impl_opengl3.cpp index d9cf487c5..1d340f637 100644 --- a/backends/imgui_impl_opengl3.cpp +++ b/backends/imgui_impl_opengl3.cpp @@ -24,9 +24,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-10-01: OpenGL: Added ImGui_ImplOpenGL3_SetClipOrigin() to specify clip origins (GL_LOWER_LEFT/GL_UPPER_LEFT, or use 0 to autodetect). (#2186, #3998, #3146, #3143, #8640) -// (Breaking): we now default to GL_LOWER_LEFT instead of 0=autodetect. Because 1) detection is not reliable and 2) is slow. -// 2026-10-01: OpenGL: Avoid querying glGetIntegerv(GL_CLIP_ORIGIN) multiple times when using DrawCallback_ResetRenderState. (#2186, #3998, #3146, #3143, #8640) // 2026-09-17: OpenGL: Added support for platform_io.DrawCallback_SetSamplerFromTex. (#9378) // 2026-09-07: OpenGL: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-07-15: OpenGL: Backup and restore GL_UNPACK_ROW_LENGTH and GL_UNPACK_ALIGNMENT in UpdateTexture() to avoid corrupting caller GL state. (#8802, #9473) @@ -192,10 +189,6 @@ #define IMGUI_IMPL_OPENGL_LOADER_IMGL3W #include "imgui_impl_opengl3_loader.h" #endif -#ifndef GL_LOWER_LEFT -#define GL_LOWER_LEFT 0x8CA1 -#define GL_UPPER_LEFT 0x8CA2 -#endif // Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension #ifndef IMGUI_IMPL_OPENGL_ES2 @@ -266,8 +259,6 @@ struct ImGui_ImplOpenGL3_Data bool HasPolygonMode; bool HasBindSampler; bool HasClipOrigin; - GLenum ClipOriginRequest; // Default = GL_LOWER_LEFT. Change using ImGui_ImplOpenGL3_SetClipOrigin(). - GLenum ClipOriginCurrent; bool UseBufferSubData; #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER GLuint TexSamplers[2]; // Used if HasBindSimpler. (0=linear, 1=nearest) @@ -285,11 +276,6 @@ static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplOpenGL3_RenderState* ImGui_ImplOpenGL3_GetRenderState() -{ - return (ImGui_ImplOpenGL3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - // OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only) #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY struct ImGui_ImplOpenGL3_VtxAttribState @@ -370,6 +356,17 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, ImGui_Impl glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); #endif + // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) +#if defined(GL_CLIP_ORIGIN) + bool clip_origin_lower_left = true; + if (bd->HasClipOrigin) + { + GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)¤t_clip_origin); + if (current_clip_origin == GL_UPPER_LEFT) + clip_origin_lower_left = false; + } +#endif + // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height)); @@ -377,7 +374,9 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, ImGui_Impl float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; float T = draw_data->DisplayPos.y; float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; - if (bd->ClipOriginCurrent == GL_UPPER_LEFT) { float tmp = T; T = B; B = tmp; } // Swap top and bottom +#if defined(GL_CLIP_ORIGIN) + if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left +#endif const float ortho_projection[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, @@ -459,14 +458,6 @@ static void ImGui_ImplOpenGL3_DrawCallback_SetSamplerFromTex(const ImDrawList*, render_state->UseTexParameterFilter = false; } -// Default is GL_LOWER_LEFT since 2026/10/01. Used to be auto. -void ImGui_ImplOpenGL3_SetClipOrigin(unsigned int clip_origin) -{ - IM_ASSERT(clip_origin == 0 || clip_origin == GL_UPPER_LEFT || clip_origin == GL_LOWER_LEFT); - ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData(); - bd->ClipOriginRequest = clip_origin; -} - // OpenGL3 Render function. // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly. // This is in order to be able to run within an OpenGL engine that doesn't do so. @@ -528,17 +519,6 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLboolean last_enable_primitive_restart = (!bd->GlProfileIsES3 && bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE; #endif - // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT) - bd->ClipOriginCurrent = bd->ClipOriginRequest; - if (bd->ClipOriginCurrent == 0) - { - bd->ClipOriginCurrent = GL_LOWER_LEFT; -#ifdef GL_CLIP_ORIGIN - if (bd->HasClipOrigin) - glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&bd->ClipOriginCurrent); -#endif - } - // Setup desired GL state // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound. @@ -1165,7 +1145,6 @@ bool ImGui_ImplOpenGL3_Init(const char* glsl_version) bd->HasClipOrigin = true; } #endif - bd->ClipOriginCurrent = bd->ClipOriginRequest = GL_LOWER_LEFT; return true; } diff --git a/backends/imgui_impl_opengl3.h b/backends/imgui_impl_opengl3.h index 17a49cd51..b5bcc7400 100644 --- a/backends/imgui_impl_opengl3.h +++ b/backends/imgui_impl_opengl3.h @@ -44,9 +44,6 @@ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects(); // (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. IMGUI_IMPL_API void ImGui_ImplOpenGL3_UpdateTexture(ImTextureData* tex); -// (Advanced) Specify clip origin, same value as glClipControl() or 0 for auto-detection. -IMGUI_IMPL_API void ImGui_ImplOpenGL3_SetClipOrigin(unsigned int gl_clip_origin); - // Configuration flags to add in your imconfig file: //#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten) //#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android) @@ -79,6 +76,7 @@ struct ImGui_ImplOpenGL3_RenderState unsigned int CurrentSampler; // (GLuint) Used if UseBindSampler == true (and are available), otherwise always 0 unsigned int CurrentTexParameterFilter; // (GLuint) Used if UseTexParameterFilter == true }; -IMGUI_IMPL_API ImGui_ImplOpenGL3_RenderState* ImGui_ImplOpenGL3_GetRenderState(); + +static inline ImGui_ImplOpenGL3_RenderState* ImGui_ImplOpenGL3_GetRenderState() { return (ImGui_ImplOpenGL3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_opengl3_loader.h b/backends/imgui_impl_opengl3_loader.h index 47f9fb364..2c485841a 100644 --- a/backends/imgui_impl_opengl3_loader.h +++ b/backends/imgui_impl_opengl3_loader.h @@ -114,7 +114,7 @@ extern "C" { #define GLAPI extern #endif /* glcorearb.h is for use with OpenGL core profile implementations. -** It should be placed in the same directory as gl.h and +** It should should be placed in the same directory as gl.h and ** included as . ** ** glcorearb.h includes only APIs in the latest OpenGL core profile @@ -303,7 +303,6 @@ typedef khronos_uint16_t GLushort; #define GL_LINK_STATUS 0x8B82 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_CURRENT_PROGRAM 0x8B8D -#define GL_LOWER_LEFT 0x8CA1 #define GL_UPPER_LEFT 0x8CA2 typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); diff --git a/backends/imgui_impl_sdl2.cpp b/backends/imgui_impl_sdl2.cpp index 8281fa4ed..a93bcc29e 100644 --- a/backends/imgui_impl_sdl2.cpp +++ b/backends/imgui_impl_sdl2.cpp @@ -21,9 +21,8 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-09: Inputs: iOS: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support. (#7636, #9474, #9617) // 2026-08-06: Fixed querying framebuffer scale when using Metal. (#5592) -// 2026-07-15: Inputs: Android: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support. (#7636, #9474) +// 2026-07-15: Inputs: restore SDL_StartTextInput()/SDL_StopTextInput() in IME handler for on-screen keyboard support on Android/mobile. (#7636, #9474) // 2026-04-16: Made ImGui_ImplSDL2_GetContentScaleForWindow(), ImGui_ImplSDL2_GetContentScaleForDisplay() helpers return a minimum of 1.0f, as some Linux setup seems to report <1.0f value and this breaks scaling border size. (#9369) // 2026-02-13: Inputs: systems other than X11 are back to starting mouse capture on mouse down (reverts 2025-02-26 change). Only X11 requires waiting for a drag by default (not ideal, but a better default for X11 users). Added ImGui_ImplSDL2_SetMouseCaptureMode() for X11 debugger users. (#3650, #6410, #9235) // 2026-01-15: Changed GetClipboardText() handler to return nullptr on error aka clipboard contents is not text. Consistent with other backends. (#9168) @@ -217,15 +216,15 @@ static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport*, ImG r.h = (int)data->InputLineHeight; SDL_SetTextInputRect(&r); -#if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) - // SDL_StartTextInput() is needed on Android and iOS to show the on-screen keyboard. (#7636, #9474, #6306) +#ifdef __ANDROID__ + // SDL_StartTextInput() is needed on Android (and some other platforms) to show the on-screen keyboard. (#7636, #9474, #6306) // It was removed in a7703fe6 due to concerns about its relation to desktop IME, but is required on mobile. SDL_StartTextInput(); #endif } else { -#if defined(__ANDROID__) || (defined(__APPLE__) && TARGET_OS_IOS) +#ifdef __ANDROID__ SDL_StopTextInput(); #endif } @@ -508,7 +507,7 @@ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event) } #ifdef __EMSCRIPTEN__ -EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank', 'noopener'); }); +EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); }); #endif static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context) diff --git a/backends/imgui_impl_sdlgpu3.cpp b/backends/imgui_impl_sdlgpu3.cpp index 2f6b25015..53b47d434 100644 --- a/backends/imgui_impl_sdlgpu3.cpp +++ b/backends/imgui_impl_sdlgpu3.cpp @@ -94,11 +94,6 @@ static ImGui_ImplSDLGPU3_Data* ImGui_ImplSDLGPU3_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplSDLGPU3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplSDLGPU3_RenderState* ImGui_ImplSDLGPU3_GetRenderState() -{ - return (ImGui_ImplSDLGPU3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - static void ImGui_ImplSDLGPU3_SetupRenderState(ImDrawData* draw_data, SDL_GPUGraphicsPipeline* pipeline, SDL_GPUCommandBuffer* command_buffer, SDL_GPURenderPass* render_pass, ImGui_ImplSDLGPU3_FrameData* fd, uint32_t fb_width, uint32_t fb_height) { ImGui_ImplSDLGPU3_Data* bd = ImGui_ImplSDLGPU3_GetBackendData(); diff --git a/backends/imgui_impl_sdlgpu3.h b/backends/imgui_impl_sdlgpu3.h index a517c43b1..ce216fef0 100644 --- a/backends/imgui_impl_sdlgpu3.h +++ b/backends/imgui_impl_sdlgpu3.h @@ -59,6 +59,7 @@ struct ImGui_ImplSDLGPU3_RenderState { SDL_GPUDevice* Device; }; -IMGUI_IMPL_API ImGui_ImplSDLGPU3_RenderState* ImGui_ImplSDLGPU3_GetRenderState(); + +static inline ImGui_ImplSDLGPU3_RenderState* ImGui_ImplSDLGPU3_GetRenderState() { return (ImGui_ImplSDLGPU3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlrenderer2.cpp b/backends/imgui_impl_sdlrenderer2.cpp index d8dcfb154..e66150e57 100644 --- a/backends/imgui_impl_sdlrenderer2.cpp +++ b/backends/imgui_impl_sdlrenderer2.cpp @@ -76,11 +76,6 @@ static ImGui_ImplSDLRenderer2_Data* ImGui_ImplSDLRenderer2_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplSDLRenderer2_RenderState* ImGui_ImplSDLRenderer2_GetRenderState() -{ - return (ImGui_ImplSDLRenderer2_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - // Functions static void ImGui_ImplSDLRenderer2_SetupRenderState(SDL_Renderer* renderer) { diff --git a/backends/imgui_impl_sdlrenderer2.h b/backends/imgui_impl_sdlrenderer2.h index e16b8cae9..0c14912db 100644 --- a/backends/imgui_impl_sdlrenderer2.h +++ b/backends/imgui_impl_sdlrenderer2.h @@ -51,6 +51,7 @@ struct ImGui_ImplSDLRenderer2_RenderState { SDL_Renderer* Renderer; }; -IMGUI_IMPL_API ImGui_ImplSDLRenderer2_RenderState* ImGui_ImplSDLRenderer2_GetRenderState(); + +static inline ImGui_ImplSDLRenderer2_RenderState* ImGui_ImplSDLRenderer2_GetRenderState() { return (ImGui_ImplSDLRenderer2_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_sdlrenderer3.cpp b/backends/imgui_impl_sdlrenderer3.cpp index 6dd4c14fe..121ce59c8 100644 --- a/backends/imgui_impl_sdlrenderer3.cpp +++ b/backends/imgui_impl_sdlrenderer3.cpp @@ -81,11 +81,6 @@ static ImGui_ImplSDLRenderer3_Data* ImGui_ImplSDLRenderer3_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplSDLRenderer3_RenderState* ImGui_ImplSDLRenderer3_GetRenderState() -{ - return (ImGui_ImplSDLRenderer3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - // Functions static void ImGui_ImplSDLRenderer3_SetupRenderState(SDL_Renderer* renderer) { diff --git a/backends/imgui_impl_sdlrenderer3.h b/backends/imgui_impl_sdlrenderer3.h index ee701be38..019def26a 100644 --- a/backends/imgui_impl_sdlrenderer3.h +++ b/backends/imgui_impl_sdlrenderer3.h @@ -51,6 +51,7 @@ struct ImGui_ImplSDLRenderer3_RenderState SDL_Renderer* Renderer; SDL_ScaleMode CurrentScaleMode; // Current scale mode during render. Set to SDL_SCALEMODE_INVALID to use "SetSamplerFromTex" mode. }; -IMGUI_IMPL_API ImGui_ImplSDLRenderer3_RenderState* ImGui_ImplSDLRenderer3_GetRenderState(); + +static inline ImGui_ImplSDLRenderer3_RenderState* ImGui_ImplSDLRenderer3_GetRenderState() { return (ImGui_ImplSDLRenderer3_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } #endif // #ifndef IMGUI_DISABLE diff --git a/backends/imgui_impl_vulkan.cpp b/backends/imgui_impl_vulkan.cpp index cf4d53537..9eca9a767 100644 --- a/backends/imgui_impl_vulkan.cpp +++ b/backends/imgui_impl_vulkan.cpp @@ -27,8 +27,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026-11-10: Don't transition swapchain images from VK_IMAGE_LAYOUT_UNDEFINED to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` on window creation, prevent validation errors in examples and multi-viewport support. (#9553, #9496) -// 2026-10-06: Added support for dynamic rendering with multiple color attachments (PipelineRenderingCreateInfo.colorAttachmentCount > 1): we render to the first one and leave the others untouched. (#9574) // 2026-09-07: Round framebuffer dimensions to the nearest integer instead of truncating them. (#9538, 9515, #8628) // 2026-09-03: Added for support for multiple Vulkan contexts with custom loaders. (#6616) // 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState, DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest. (#9378) @@ -461,11 +459,6 @@ static ImGui_ImplVulkan_Data* ImGui_ImplVulkan_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplVulkan_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplVulkan_RenderState* ImGui_ImplVulkan_GetRenderState() -{ - return (ImGui_ImplVulkan_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - #ifdef IMGUI_IMPL_VULKAN_USE_LOADER // Get the Vulkan function pointers used by the current backend. // If no backend is available, return the currently loaded global function pointers (ImGuiImplVulkanFuncs). @@ -1064,14 +1057,7 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; ms_info.rasterizationSamples = (info->MSAASamples != 0) ? info->MSAASamples : VK_SAMPLE_COUNT_1_BIT; - // Blend into the first color attachment. With dynamic rendering, other color attachments of the rendering are left untouched (requires independentBlend feature). - int color_attachment_count = 1; -#ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING - if (bd->VulkanInitInfo.UseDynamicRendering && info->PipelineRenderingCreateInfo.colorAttachmentCount > 1) - color_attachment_count = (int)info->PipelineRenderingCreateInfo.colorAttachmentCount; -#endif - ImVector color_attachment; - color_attachment.resize(color_attachment_count, VkPipelineColorBlendAttachmentState()); // colorWriteMask = 0 + VkPipelineColorBlendAttachmentState color_attachment[1] = {}; color_attachment[0].blendEnable = VK_TRUE; color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; @@ -1086,8 +1072,8 @@ static VkPipeline ImGui_ImplVulkan_CreatePipeline(VkDevice device, const VkAlloc VkPipelineColorBlendStateCreateInfo blend_info = {}; blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; - blend_info.attachmentCount = (uint32_t)color_attachment.Size; - blend_info.pAttachments = color_attachment.Data; + blend_info.attachmentCount = 1; + blend_info.pAttachments = color_attachment; ImVector dynamic_states = info->ExtraDynamicStates; dynamic_states.push_back(VK_DYNAMIC_STATE_VIEWPORT); @@ -1594,15 +1580,33 @@ VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physic avail_format.resize((int)avail_count); vkGetPhysicalDeviceSurfaceFormatsKHR(physical_device, surface, &avail_count, avail_format.Data); - // When requesting several formats, the first found will be used - if (avail_count > 1) + // First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available + if (avail_count == 1) + { + if (avail_format[0].format == VK_FORMAT_UNDEFINED) + { + VkSurfaceFormatKHR ret; + ret.format = request_formats[0]; + ret.colorSpace = request_color_space; + return ret; + } + else + { + // No point in searching another format + return avail_format[0]; + } + } + else + { + // Request several formats, the first found will be used for (int request_i = 0; request_i < request_formats_count; request_i++) for (uint32_t avail_i = 0; avail_i < avail_count; avail_i++) if (avail_format[avail_i].format == request_formats[request_i] && avail_format[avail_i].colorSpace == request_color_space) return avail_format[avail_i]; - // If none of the requested image formats could be found, use the first available - return avail_format[0]; + // If none of the requested image formats could be found, use the first available + return avail_format[0]; + } } VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count) @@ -1901,7 +1905,6 @@ void ImGui_ImplVulkanH_CreateWindowSwapChain(VkPhysicalDevice physical_device, V // Create or resize window // - 2025/09/26: v1.92.4 added a trailing 'VkImageUsageFlags image_usage' parameter which is usually VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT. -// - 2026/11/10: v1.93.1 removed a bunch of code transitioning swapchain image layout from `VK_IMAGE_LAYOUT_UNDEFINED` to `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR`. (#9496) void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int width, int height, uint32_t min_image_count, VkImageUsageFlags image_usage) { IM_ASSERT(g_FunctionsLoaded && "Need to call ImGui_ImplVulkan_LoadFunctions() if IMGUI_IMPL_VULKAN_NO_PROTOTYPES or VK_NO_PROTOTYPES are set!"); @@ -1910,6 +1913,81 @@ void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevic ImGui_ImplVulkanH_CreateWindowSwapChain(physical_device, device, wd, allocator, width, height, min_image_count, image_usage); ImGui_ImplVulkanH_CreateWindowCommandBuffers(physical_device, device, wd, queue_family, allocator); + + // FIXME: to submit the command buffer, we need a queue. In the examples folder, the ImGui_ImplVulkanH_CreateOrResizeWindow function is called + // before the ImGui_ImplVulkan_Init function, so we don't have access to the queue yet. Here we have the queue_family that we can use to grab + // a queue from the device and submit the command buffer. It would be better to have access to the queue as suggested in the FIXME below. + VkCommandPool command_pool; + VkCommandPoolCreateInfo pool_info = {}; + pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; + pool_info.queueFamilyIndex = queue_family; + VkResult err = vkCreateCommandPool(device, &pool_info, allocator, &command_pool); + check_vk_result(err); + + VkFenceCreateInfo fence_info = {}; + fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; + VkFence fence; + err = vkCreateFence(device, &fence_info, allocator, &fence); + check_vk_result(err); + + VkCommandBufferAllocateInfo alloc_info = {}; + alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; + alloc_info.commandPool = command_pool; + alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + alloc_info.commandBufferCount = 1; + VkCommandBuffer command_buffer; + err = vkAllocateCommandBuffers(device, &alloc_info, &command_buffer); + 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); + + // Transition the images to the correct layout for rendering + for (uint32_t i = 0; i < wd->ImageCount; i++) + { + VkImageMemoryBarrier barrier = {}; + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.image = wd->Frames[i].Backbuffer; + barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + barrier.subresourceRange.levelCount = 1; + barrier.subresourceRange.layerCount = 1; + vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); + } + + err = vkEndCommandBuffer(command_buffer); + check_vk_result(err); + VkSubmitInfo submit_info = {}; + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &command_buffer; + + VkQueue queue; + vkGetDeviceQueue(device, queue_family, 0, &queue); + err = vkQueueSubmit(queue, 1, &submit_info, fence); + check_vk_result(err); + err = vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX); + check_vk_result(err); + err = vkResetFences(device, 1, &fence); + check_vk_result(err); + + err = vkResetCommandPool(device, command_pool, 0); + check_vk_result(err); + + // Destroy command buffer and fence and command pool + vkFreeCommandBuffers(device, command_pool, 1, &command_buffer); + vkDestroyCommandPool(device, command_pool, allocator); + vkDestroyFence(device, fence, allocator); + command_pool = VK_NULL_HANDLE; + command_buffer = VK_NULL_HANDLE; + fence = VK_NULL_HANDLE; + queue = VK_NULL_HANDLE; } void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator) diff --git a/backends/imgui_impl_vulkan.h b/backends/imgui_impl_vulkan.h index 44c76c9a0..a48dae3ec 100644 --- a/backends/imgui_impl_vulkan.h +++ b/backends/imgui_impl_vulkan.h @@ -101,7 +101,6 @@ struct ImGui_ImplVulkan_PipelineInfo // - As an convenience, by setting DescriptorPoolSize > 0 the backend will create one for you. // - About dynamic rendering: // - When using dynamic rendering, set UseDynamicRendering=true + fill PipelineInfoMain.PipelineRenderingCreateInfo structure. -// - PipelineRenderingCreateInfo may describe multiple color attachments: we render to the first one and leave the others untouched. This requires the 'independentBlend' device feature. struct ImGui_ImplVulkan_InitInfo { uint32_t ApiVersion; // Fill with API version of Instance, e.g. VK_API_VERSION_1_3 or your value of VkApplicationInfo::apiVersion. May be lower than header version (VK_HEADER_VERSION_COMPLETE) @@ -176,7 +175,8 @@ struct ImGui_ImplVulkan_RenderState VkPipeline Pipeline; VkPipelineLayout PipelineLayout; }; -IMGUI_IMPL_API ImGui_ImplVulkan_RenderState* ImGui_ImplVulkan_GetRenderState(); + +static inline ImGui_ImplVulkan_RenderState* ImGui_ImplVulkan_GetRenderState() { return (ImGui_ImplVulkan_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } //------------------------------------------------------------------------- // Internal / Miscellaneous Vulkan Helpers diff --git a/backends/imgui_impl_wgpu.cpp b/backends/imgui_impl_wgpu.cpp index 002967b92..bdc4d434b 100644 --- a/backends/imgui_impl_wgpu.cpp +++ b/backends/imgui_impl_wgpu.cpp @@ -129,11 +129,6 @@ static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData() return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } -ImGui_ImplWGPU_RenderState* ImGui_ImplWGPU_GetRenderState() -{ - return (ImGui_ImplWGPU_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; -} - //----------------------------------------------------------------------------- // SHADERS //----------------------------------------------------------------------------- diff --git a/backends/imgui_impl_wgpu.h b/backends/imgui_impl_wgpu.h index 9f206db32..a5867c923 100644 --- a/backends/imgui_impl_wgpu.h +++ b/backends/imgui_impl_wgpu.h @@ -81,7 +81,8 @@ struct ImGui_ImplWGPU_RenderState WGPUDevice Device; WGPURenderPassEncoder RenderPassEncoder; }; -IMGUI_IMPL_API ImGui_ImplWGPU_RenderState* ImGui_ImplWGPU_GetRenderState(); + +static inline ImGui_ImplWGPU_RenderState* ImGui_ImplWGPU_GetRenderState() { return (ImGui_ImplWGPU_RenderState*)ImGui::GetPlatformIO().Renderer_RenderState; } //------------------------------------------------------------------------- // Internal Helpers diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt index 9788196ce..c83710ec0 100644 --- a/docs/CHANGELOG.txt +++ b/docs/CHANGELOG.txt @@ -36,410 +36,27 @@ HOW TO UPDATE? - Please report any issue! ----------------------------------------------------------------------- - VERSION 1.93.1 WIP (In Progress) + VERSION 1.93.0 WIP (In Progress) ----------------------------------------------------------------------- Breaking Changes: -Autumn cleanup of stuff marked obsolete more than two years ago: - -- Commented out legacy names/functions which were obsoleted in 1.90.7 (May 2024); - - `ImGuiMod_Shortcut` --> `ImGuiMod_Ctrl` (since 1.90.7 it maps to Cmd on macOS) -- Commented out legacy names/functions which were obsoleted in 1.90.9 (July 2024); - - `ImGuiCol_TabActive` --> `ImGuiCol_TabSelected` - - `ImGuiCol_TabUnfocused` --> `ImGuiCol_TabDimmed` - - `ImGuiCol_TabUnfocusedActive` --> `ImGuiCol_TabDimmedSelected` -- Commented out legacy names/functions which were obsoleted in 1.91.0 (July 2024); - - `ImGuiSelectableFlags_DontClosePopups` --> `ImGuiSelectableFlags_NoAutoClosePopups` - - `PushButtonRepeat(bool repeat)` --> `PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat)` - - `PopButtonRepeat()` --> `PopItemFlag()` - - `PushTabStop(bool tab_stop)` --> `PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);` - - `PopTabStop()` --> `PopItemFlag()` -- Commented out legacy names/functions which were obsoleted in 1.91.1 (Sept 2024); - - `io.GetClipboardTextFn` --> `platform_io.Platform_GetClipboardTextFn` - - `io.SetClipboardTextFn` --> `platform_io.Platform_SetClipboardTextFn` - - `io.ClipboardUserData` --> `platform_io.Platform_ClipboardUserData` -- Please also try to get rid of calls to `GetContentRegionMax()`, `GetWindowContentRegionMin()` - and `GetWindowContentRegionMax()` will may be removed soon-ish: you should not - ever need those functions. See #7838. - -Other Changes: - -- Style: - - `StyleColorsDark()`: tweaked WindowBg, PopupBg, ChildBg to be darker than in 1.93.0. - - Added `style.SymbolArrowSizeFactor`, `style.SymbolArrowThicknessFactor` to tweak the - shape and look of arrows. Made default arrow stroked. (#5233, #2431, #2235, #6730, #8243) - Legacy arrow: size: (0.60f,0.70f), thickness: 0.0f - New arrow: size: (0.72f,0.40f), thickness: 0.30f -- Windows: - - Using `SetNextWindowPos()` with a pivot while a window is hidden and measuring - size will still apply temporary position until size is figured out. (#9568) -- TreeNode: - - TreeNodeGetOpen(): added flags parameter to allow passing `ImGuiTreeNodeFlags_DefaultOpen` - or `ImGuiTreeNodeFlags_Leaf`. (#9569, #9592, #3823, #9251) [@adalisk-emikhaylov, @Yaki-Blake] -- Popups: - - Modals: fixed an assert displaying a modal in an environment where - `io.DisplayFramebufferScale` is not an integer (regression in 1.93.0). (#9598) -- Tables: - - Added "Reset->Reset Sizes" context-menu option. (#9523, #9605) - - Fixed various border overshooting issues, some mostly visible with transparent - borders and under specific conditions: (#4678) - - On non-scrolling tables, inner horizontal borders slightly overlapped - outer vertical ones with certain settings. - - On non-scrolling tables, clamping lower border coordinates to stay within - visible range (no visible change, but it makes ImDrawCmd AABB more sensible). - - Fixed vertical inner borders slightly overlapping bottom outer border. - - Fixed various issues using `ImGuiTableFlags_NoHostExtendX`/`_NoHostExtendY`: - - Fixed selectable highlight straying off the X2/Y2 clipping limit. - - Fixed parent window work rectangle affecting the Y2 clipping limit. - - Fixed the Y2 clipping limit overlapping bottom outer border. - - Fixed layout of items submitted while in horizontal layout mode (e.g. a menu bar). - `BeginTable()` resets layout mode to vertical. (#9589) [@themd] -- Multi-Select: - - Fixed `ImGuiSelectionBasicStorage::GetNextSelectedItem()` reading one past the - end of storage when trailing items are unselected (#9604) [@MilosLord] -- Drags: fixed handling of `ImGuiSliderFlags_WrapAround`: value could temporarily - escape the range when dragging fast. (#9612, #9611, #7749) [@swayie, @ocornut] -- Checkbox: indeterminate/mixed value inner rectangle never has rounding, - to reduce confusion with a radio button. (#5518, #5677, #6865, #2644) -- ColorEdit: - - ColorButton, ColorEdit, ColorPicker: fixed an issue rendering colors when - inside a `BeginDisabled(false)` block, caused by the alpha cancelling-out - code in 1.93.0. (#9511, #9613, #9614) [@tksuoran] -- Fonts: - - Detect if the parameters leading `AddFontDefault()` to implicitly select either - `AddFontDefaultBitmap()` or `AddFontDefaultVector()` have changed between init - time and first frame. (#9591) -- ImVec2: added a check for cases where a custom `IM_VEC2_CLASS_EXTRA` macro - adds an extra `operator=` to ImVec2. This isn't supported but should not - be needed as you should have a constructor to convert from your type to ImVec2. -- Misc: update stb_textedit 1.14->1.15. - - InputText: Up/PageUp on the first line now moves the cursor to the beginning - of the line, including when extending a selection. [@blackedout01] -- Misc: update stb_truetype 1.26->1.27. - - Fonts: fixed incorrect glyph mapping with certain character maps, loading fonts - with only a Microsoft Symbol character map, and rendering scaled composite glyphs. - - Fixed an out-of-bounds read with single-point off-curve contours. -- Misc: update stb_rect_pack 1.01->1.02. - - Fixed packing determinism by not depending on qsort() tiebreak. -- CI: added some ARM64 builds. (#9593) [@Harishmcw] -- Examples: renamed various helper batch files from build_win32.bat to build_win.bat - to reflect that they can also build X64 or ARM64, given the right environment. - Made the script detect the environment when needed (e.g. to specify library path). -- Examples: added support for ARM64 in selected build_win.bat helpers. (#9593) [@Harishmcw] -- Backends: - - DirectX9: pre-transforming vertices and using `D3DFVF_XYZRHW` vertex format, largely - increasing performances when in `D3DCREATE_SOFTWARE_VERTEXPROCESSING` mode. (#9628) - - GLFW: allow initialization with missing HWND. (#9619) [@djohansson] - - GLFW, SDL2: Emscripten implementation of `Platform_OpenInShellFn` calls - `window.open()` with `noopener`: prevents newly opened tab from keeping a - reference to opening page. (#9615, #7660, #7851) [@pthom] - - SDL2: on iOS, also restore calling `SDL_StartTextInput()/SDL_StopTextInput()` - in IME handler. Match Android change in 1.93.0. [@pthom] (#7636, #9474, #9617) - - Metal4: worked around rendering artifacts (e.g. flickering diagonal lines) with - 16-bit indices by aligning each draw command index buffer address to 4 bytes. - - Metal4: fixed vertex/index buffers being reused by a later draw in the same frame - before the GPU had processed them. (#9622, #9625) [@lailoken] - - Metal4: remove the residency set from the command queue on shutdown to avoid - hitting Metal's residency set limit when reinitializing on the same queue. - - Vulkan: don't transition swapchain images from `VK_IMAGE_LAYOUT_UNDEFINED` to - `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` on window creation, prevent validation errors in - examples and multi-viewport support. (#9553, #9496, #9152) [@sarpsenturk, @LewisJustin] - - - ------------------------------------------------------------------------ - VERSION 1.93.0 (Released 2026-10-14) ------------------------------------------------------------------------ - -Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v1.93.0 - -In 1.93.0, the `ImDrawList` rendering API has been improved to be more robust and -more consistent over the whole range of shapes. The rendering now matches much closer -to common vector drawing APIs, like html canvas. Improvements, like anti-aliased line -endings and stroke position were added. The coordinates passed to the API are now -consistently describing shape outlines. - -For code using custom rendering: some details are now rendered slightly differently -(even if generally more consistent). The difference in rendering is in the range of -half a pixel, but that can lead to issues like some lines now look blurrier or more -transparent. All Dear ImGui widgets should appear identical or better. - -The rendering of common shapes was optimized when the shapes fall on integer coordinates -(which is most of the UI). This includes skipping anti-aliasing when not needed, or -using textures instead of tessellated geometry to draw round corners. -The varying code-paths are designed to look indistinguishable from each others. - -New rendering code fixes some inconsistencies between graphics APIs -(e.g. DirectX vs OpenGL) which are using different diamond exits rules. -New code should work precisely the same regardless of which graphics API is used -(note that using _StrokeLegacy mode can lead to the same old inconsistencies). - -New rendering code also deals better with animating thickness and rounding -(integer values are recommended). - -While the current version doesn't make lots of visible use of the new features and -facilities, they are among the pillars that will make it easier to create prettier -contents, both for custom rendering and future versions of the library. - -Use `ImDrawFlags_StrokeLegacy` mode to emulate old rendering: -- Per-primitive: draw_list->AddLine(..., ..., ImDrawFlags_StrokeLegacy); -- For a given scope: draw_list->PushDrawFlag(ImDrawFlags_StrokeLegacy, true); draw_list->AddLine(...); draw_list->PopDrawFlag(); -- Globally: ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy); // Map to a checkbox -- Globally: io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on Shift - -Don't panic! -Many applications will not notice any difference! You will more likely see -differences if you used lots of direct `ImDrawList` calls for custom rendering. - -Credits for ImDrawList changes in 1.93.0: -- main work courtesy of @memononen. -- additional work/reviewing/guidance by @ocornut. -- with legacy bits from @thedmd, @potocpav. -Other credits marked below, or @ocornut when omitted. - -Refer to our guides: -- ImDrawList Vector Rendering Reference - https://github.com/ocornut/imgui/wiki/Draw-List - (includes a precise list of differences between 1.92.9 and 1.93.0). -- ImDrawList 1.92.9 vs 1.93.0 Interactive Testbed - https://www.dearimgui.com/docs/drawlist_v193 - (interactively compare differences between 1.92.9 and 1.93.0 + commentary) - (downloadable HTML file, may be used offline) -- Pixel Perfect Anti-aliased Rendering - https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering -- How Anti-aliased Polyline Rendering is Implemented - https://github.com/ocornut/imgui/wiki/Polyline-Rendering -- Discussion topic: - https://github.com/ocornut/imgui/issues/9504 - (if you have a problem to discuss, please open a new issue) - -Breaking Changes: - -- ImDrawList: - - AddLine(): removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates. (#9504) - - This fixes inconsistencies in the API and matches the PathXXX API. - - By default, stroke thickness extends on both side of the given segment. - e.g for a "pixel-perfect" looking line with thickness=1.0f, coords should be passed as center of each ends of the line. - - Use `ImDrawFlags_StrokeLegacy` to use old offset if required. Or you can apply the offset manually! - - Generally better, simple and faster to use `AddLineH()`, `AddLineV()` functions added in 1.92.8. - READ IF YOU ARE MINDFUL OF PIXEL-PERFECTNESS IN YOUR CUSTOM RENDERING/WIDGETS: - - TRANSITION GUIDE FOR AXIS-ALIGNED LINES: - - When switching from legacy `AddLine()` values to `AddLineV()`, `AddLineH()` you can keep same inputs coordinates as before: - - Old `AddLine({x, y1}, {x, y2}, col)` --> `AddLineV(x, y1, y2, col);` // Vertical line. - - Old `AddLine({x1, y}, {x2, y}, col)` --> `AddLineH(x1, x2, y, col);` // Horizontal line. - - This will be equivalent and faster for thickness=1.0f lines. - - Since `AddLine()` use default stroke pos Center and `AddLineV()`, `AddLineH()` use Inside, thickness>1.0f strokes will differ. - Using `ImDrawFlags_StrokeCenter` will match old result more closely (aka look centered), - but is more likely to look blurry as it already did before. - - Read table below about StrokePos and the "Pixel-Perfect Rendering" guide if you care about pixel-perfect lines. - - TRANSITION GUIDE FOR DIAGONAL LINES: - - Your lines will appear offset by -0.5f pixels on each axis. - Being anti-aliased diagonal lines, they won't look particularly better or worse, just slightly offset. - It'll likely only be noticeable if you carefully combined them with other primitives for a pixel-perfect result. - - Old `AddLine({x1, y1}, {x2, y2}, col)` --> `AddLine({x1 + 0.5f, y1 + 0.5f}, {x2+ 0.5f, y2 + 0.5f}, col);` // Same - or use `ImDrawFlags_StrokeLegacy` --> `AddLine({x1, y1}, {x2, y2}, col, thickness, ImDrawFlags_StrokeLegacy);` // Offset by +0.5f + disable AA ends. - This reapplies the old offset, and should get you exactly the same result you previously - got for thickness=1.0f lines. But said result were previously sometimes ambiguous and - renderer-dependent. (#3116, #3258, #2441) - - Old code did not support anti-aliased ends, which could create gaps when rendering shapes out - of multiple contiguous lines instead of using `AddPolyline()`. There is a possibility that you - legacy code added fudge offsets here and there; which may not be necessary anymore if you use - `_AALineEnds`, or if you combine rendering of contiguous lines using `AddPolyline()`. - - AddRect(), AddCircle(), AddNgon(), AddEllipse(), AddTriangle(), AddQuad(): defaulting to "inside" stroke. - - All closed shapes with thickness=1.0f will appear identical. - - The difference for thickness>1.0f shapes may be minimal since very large strokes - were not well supported for widgets, but stroke will default inside widgets. - - AddCircle(), AddNgon(): removed -0.5f offset added to radius. - - This fixes inconsistencies in the API. - - Use `ImDrawFlags_StrokeLegacy` to use old method if required. Or you can apply the offset manually! - - AddRectFilled(): non-integer coordinates will now display anti-aliased edges. - Previously, non-integer coordinates rendered with aliased edges snapped by the - rasterizer. (#6971) - - AddRect(), AddRectFilled(): rectangles with inverted coordinates won't be visible - unless using `ImDrawFlags_StrokeLegacy` mode. With inverted coordinates (min > max): - - Legacy `AddRect()` rounding off -> visible but incorrect outer size. - - Legacy `AddRect()` rounding on -> visible but very glitchy. - - Legacy `AddRectFilled()` rounding off -> visible and correct. - - Legacy `AddRectFilled()` rounding on -> visible but very glitchy. - - Use `ImDrawFlags_StrokeLegacy` to use old rendering for cases without rounding, or fix coordinates. - - Merged `ImDrawListFlags` into `ImDrawFlags`. `ImDrawListFlags` was rarely used directly - and generally setup by the ImGui context. - - `ImDrawListFlags_AntiAliasedLines` -> `ImDrawFlags_AALines` - - `ImDrawListFlags_AntiAliasedFill` -> `ImDrawFlags_AAFill` - - `ImDrawListFlags_AllowVtxOffset` -> `ImDrawFlags_UseVtxOffset` - - `ImDrawListFlags_TextNoPixelSnap` -> `ImDrawFlags_TextNoPixelSnap` - Unifying them allows easily using them for both per-primitives and scope alterations. - Kept redirection enums (will obsolete). - - Renamed all `ImDrawFlags_RoundCornersXXX` flags to `ImDrawFlags_RoundXXX`. - - `ImDrawFlags_RoundCornersAll` -> `ImDrawFlags_RoundAll` - - `ImDrawFlags_RoundCornersNone` -> `ImDrawFlags_RoundNone` - - `ImDrawFlags_RoundCornersTopLeft` -> `ImDrawFlags_RoundTopLeft` - - `ImDrawFlags_RoundCornersTopRight` -> `ImDrawFlags_RoundTopRight` - - `ImDrawFlags_RoundCornersBottomLeft` -> `ImDrawFlags_RoundBottomLeft` - - `ImDrawFlags_RoundCornersBottomRight` -> `ImDrawFlags_RoundBottomRight` - - `ImDrawFlags_RoundCornersTop` -> `ImDrawFlags_RoundTop` - - `ImDrawFlags_RoundCornersBottom` -> `ImDrawFlags_RoundBottom` - - `ImDrawFlags_RoundCornersLeft` -> `ImDrawFlags_RoundLeft` - - `ImDrawFlags_RoundCornersRight` -> `ImDrawFlags_RoundRight` - - `ImDrawFlags_RoundCornersMask_` -> `ImDrawFlags_RoundMask_` - Kept redirection enums (will obsolete). - - Marked `ImDrawListFlags_AntiAliasedLinesUseTex` and `style.AntiAliasedLinesUseTex` as - obsolete, as the new line rendering code always uses textures. - - Enabling `ImFontAtlasFlags_NoBakedLines` in the font atlas will now disable support for - anti-aliased lines by clearing `style.AntiAliasedLines`/`style.AntiAliasedLineEnds`. -- Style: obsoleted `style.CurveTessellationTol` (default 1.25) which was in Pixels² unit in - favor of `style.CurveTessellationMaxError` (default 1.12) which is in Pixels unit. It is +- Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in + favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. It is easier to tweak + this allows us to easily scale error threshold on high density screens. - - style.CurveTessellationMaxError == sqrtf(style.CurveTessellationTol). -- ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: - prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. -- Fonts: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). - (#609, #5748, #9559) + - style.CurveTessellationMaxError == sqrf(style.CurveTessellationTol). - Backends: - DirectX12: Removed support for legacy `ImGui_ImplDX12_Init()` signature, which was obsoleted in 1.91.6 (December 2014), because it needed to forcefully disable support for `ImGuiBackendFlags_RendererHasTextures`. Use the new signature! (#9487) - - OpenGL3: Does not attempt to read `GL_CLIP_ORIGIN` by default as the detection is - sub-optimal and not reliable on some setup. Use `ImGui_ImplOpenGL3_SetClipOrigin(0)` - to enable auto-detection, or e.g. `ImGui_ImplOpenGL3_SetClipOrigin(GL_UPPER_LEFT)`. Other Changes: -- Style: - - StyleColorsDark(): minor refresh of the default style to look more modern: - - Changed WindowBg to use a slightly greyer value and removed opacity. - - Changed FrameBg values to use a dark black to make frames stand out better. - - Tweak TextDisabled, TableHeaderBg, TableBorders to match altered WindowBg. - - StyleColorsLight(): inverted `ImGuiCol_TitleBgXXX` colors so that the selected - window title bar appears brighter. -- ImDrawList: - - Added flags to specify stroke position in all `ImDrawList` stroking functions: (#9504) [@memononen] - - `ImDrawFlags_StrokeInside` (default for Rect, Circle/Ellipse, Triangle, Quad, Ngon + AddLineH, AddLineV) - - `ImDrawFlags_StrokeCenter` (default for Line, Polyline, Beziers, Paths function) - - `ImDrawFlags_StrokeCenterBiased` (center w/ bias for pixel perfect alignment) - - `ImDrawFlags_StrokeOutside` - - `ImDrawFlags_StrokeLegacy` (match old behavior) - - Legacy mode may be set as default for a given scope using `PushDrawFlag(ImDrawFlags_StrokeLegacy, true)`. - - Legacy code was generally applying +0.50f offsets which meant that, - - with thickness=1.0f: the stroke would appear inside. - - with thickness>1.0f: the stroke would start expanding on both sides but starting from that small initial offset. - - with thickness>1.0f for even integer values, the stroke would look blurry. - - TL;DR; the logic didn't make much sense for thickness>1.0f. - - Defaulting to Inside for closed shapes ensure that rectangles and lines are - never blurry, regardless of thickness, as long as input coordinates/sizes - are integers. (#9359) Recap: - ------------------------------------------------------------------------ - Thickness Legacy Inside Outside Center CenterBiased - ------------------------------------------------------------------------ - 1.0f sharp sharp sharp blurry sharp - 2.0f blurry sharp sharp sharp sharp - 3.0f sharp sharp sharp blurry sharp - ------------------------------------------------------------------------ - - Read our Wiki guides for more details! - https://github.com/ocornut/imgui/wiki/Draw-List - - And interactive 1.92.9 vs 1.93.0 comparing testbed: - https://www.dearimgui.com/docs/drawlist_v193 - - AddPolyline(), PathStroke(), AddTriangle(): the algorithm to render lines got overhauled. - (#9504, #2183, #2964, #7972 + #9360, #6331, #4250, #4091) [@memononen] - - Generally fixed rendering of thick strokes/paths. - - The new stroke expansion now uses corner miter calculation, which keeps thickness along - the line segments consistent. If the corner becomes too sharp, it will be beveled to - avoid long spikes at corners. - - There are also some robustness measures for the case where the line thickness is larger - than the features being drawn. - - Rendering artifacts are still possible when the path features are smaller than line thickness, - but the artifacts should be more localized. The new implementation attempted to favor simple - implementation and robustness over the corner case accuracy. - - All functions: new rendering code fixes some inconsistencies between graphics APIs - (e.g. DirectX vs OpenGL) which are using different diamond exits rules. New code should - work precisely the same regardless of graphics API. (#3116, #3258, #2441) [@memononen] - - Debug: added `io.ConfigDebugDrawListDefaultsToStrokeLegacy` to facilitate comparing old/new - behaviors. This is equivalent to calling `PushDrawFlag(ImDrawFlags_StrokeLegacy, true)` - on every drawlists. - Suggested uses, e.g. - - `io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on holding Shift` - - `ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy);` - - Added `ImDrawFlags_AALineEnds` flag to enable anti-aliased line ends. - - Most noticeable for thick lines. - - Also helps fill minor gaps if combining multiple individual lines. For best looking - continuous lines you should use AddPolyline(), it creates joins between line segments - to avoid any gaps. - - Added `style.AntiAliasedLineEnds` in ImGui to set default state. - - This is disabled by default! Enabling AA Ends by default would be more "correct", - but since it is very slightly slower and increases vertex/index data we decided - to not enable it by default. - This keeps situations such as "throw tens of thousands of lines at ImDrawList" - optimal. You can opt-in for a given shape or in a scope using `PushDrawFlag()`. - - Added `ImDrawFlags_JoinMiter` flag to disable using beveled corner. - - Closer to legacy rendering and slightly faster, but corners sharper than - 90 degrees may expand far out. - - Automatically used by AddRect(), AddCircle(), AddNgon(), AddEllipse() functions - since we know that the input path does not contain sharper corners. - - Added `ImDrawFlags_CapSquare` flag to extend lines ends using square caps. (#9360) - - AddConvexPolyFilled()/PathFillConvex(): improved to handle input geometry more robustly. - The rendering of sharp corners was improved. Earlier there were issues with sharp corners - either creating long spikes, or messing up the adjacent edge's anti-aliasing. Now the - anti-aliasing fringe calculation is more consistent, and sharp corners get beveled to - avoid spikes. There might still be issues when the smallest extent of a long thin polygon - is less than a pixel. Also supports `ImDrawFlags_JoinMiter`, to facilitate matching - a stroke using the same flag. - - `AddRect()`, `AddRectFilled()`: various optimizations for rounded rectangles. (#1962, #9504) - - Integer-aligned coordinates and thicknesses will automatically use baked textures, - saving on both CPU and vertex/index data. - - Enabled by default. Use `ImFontAtlasFlags_NoBakedRoundCorners` to disable baking - round corners in font atlas. - - Added `ImDrawFlags_UseTexForRoundCorners` flag to enable in scope or per-shape. - Added for consistency and debugging, not really needed in practice. - - `AddCircle()`, `AddCircleFilled()`: fixed large circles being under-tessellated - (when above ~140 with default CircleTessellationMaxError). - - Improved debug-build performance in various locations. - - Improved minor mismatches when overlapping strokes and filled shapes. - For example, when using inside strokes, - - `AddRect()` and `AddRectFilled()` with rounding now overlap better. (#3656) - - `AddCircle()` and `AddCircleFilled()` now overlap better. - - Added `ImDrawList::PushDrawFlag()`/`PopDrawFlag()` to alter certain flags for a - scope and a given `ImDrawList`. (#9489) - - e.g. `PushDrawFlag(ImDrawFlags_StrokeLegacy, true);` enforce legacy tweaks. - - About `ImDrawFlags_StrokeLegacy`: - - This is designed to emulate old behavior: - - Most shapes use `ImDrawFlags_StrokeCenter`. - - AddLine() add +0.5f,+0.5f offset to position. - - AddRect() and AddRectFilled() allow inverted positions. - - AddRectFilled() has no AA when passed non-integer coordinates. - - AddCircle(), AddNgon() add a -0.5f offset to radius. - - Closed shapes use miter corners. - - Lines don't have anti-aliased ends. - - But there are known difference between legacy code and ImDrawFlags_StrokeLegacy: - - Thick shapes with acute angles will now preserve thickness better, - which may make them appear as protruding a little more. - - About disabling anti-aliasing: - - Disabling anti-aliasing is now emulated by applying different UV coordinates. - - It does not result in a performance increase or vertex/index data decrease any more - (however the tendency is that the new code behaves better than old code). - - But may be a useful stylistic choice in some circumstances. - - Many thick shapes had broken corners with old no-AA code, and the old no-AA code - was wildly different from the AA code. Not the case any more. (#288) - - Per-viewport FramebufferScale for Apple/Retina screen is applied to draw lists: - - AA Fringe is scaled accordingly. (#9577) - - Circle and Curves tessellation error are scaled accordingly. - - Reworked assert in `PushTexture()` to allow convenience grace period of using a - texture that was queue for destroy during the frame. Make it safe to stick to - an existing texture during the frame. (#9528, #8465) - - Added optional `platform_io.DrawCallback_SetSamplerFromTex` standard backend-agnostic - draw callback for requesting to use the sampler associated already associated to a texture. - Currently only supported by the OpenGL2/3 and SDLRenderer3 backend. (#9378) - - Fixed dangling `ImDrawList::_OwnerName` when using animated label. (#9552) [@ubi-dcastonguay] -- Mixed Values: - - Added `ImGuiItemFlags_MixedValue` flag for representing mixed/indeterminate values. - Supported by: Checkbox(), RadioButton(), DragXXX(), SliderXXX(), InputXXX(), ColorXXX() - and Combo() functions. - The scoped flag is designed for usage by advanced property editors. (#5518, #5677, #6865) - Drags, Sliders: - - Ongoing drags may be cancelled using Right-Click, Escape or Gamepad Triangle. - Cancelling reverts to the initial value. (#8564, #9534) - Fixed an overflow using `ImGuiSliderFlags_Logarithmic` with S32/S64 types which leads to clamped interactions. (#9526, #3361, #1823, #1316, #642) [@lailoken] + - Ongoing drags may be cancelled using Right-Click, Escape or Gamepad Triangle. + Cancelling reverts to the initial value. (#8564, #9534) - TreeNode: - Fixed issues/asserts with 32+ deep trees when using ImGuiTreeNodeFlags_DrawLinesXXX features or other features requiring stack storage. (#9509) [@lasrod] @@ -448,32 +65,13 @@ Other Changes: section width. - Using <> scrolling buttons while the selected Tab is at either end of the section mid-section but not fully visible always makes it fully visible - (before eventually selecting a Tab in the leading/trailing section). -- Tables: - - Fixed a bug restoring correct .ini columns order when table use is Sortable - but had no user changes. (regression from 1.92.9). (#9519, #9108) - - Fixed a bug tracking topology changes (insert new columns in the middle) - when the table is not _Reorderable: new columns would be ordered incorrectly. - (#9570, #9108, #9572) [@lailoken] -- InputText: - - Fixed a crash in some cases when using Home key in a WordWrap+ReadOnly field. (#9561) -- Selectable: - - Fixed `ImGuiSelectableFlags_SelectOnNav` triggering during NavInit. + (before eventually selecting a Tab in the leading/trailing section) - Fonts: - Reworked `AddFontDefault()` to use `io.DisplayFrameBufferScale` as part of the heuristic to select `AddFontDefaultVector()` by default, effectively using ProggyForever instead of ProggyClean on most Apple/Retina setups by default. - - Added `ImFont::AddRemapCodepointToGlyphIndex()` allowing to access glyphs that are not - mapped to codepoints. (#9559, #5647, #609, #5748, #8466) - - imgui_freetype: Fixed blurriness rendering `AddFontDefaultVector()`. Caused by a - non-pixel aligned offset caused by `ExtraSizeScale`. (#9348, #9233) [@redpartizan, @RDMCz] - - (Internal) ImFontLoader: reworked `FontSrcContainsGlyph`, `FontBakedLoadGlyph` signatures - to take raw glyph index instead of codepoint. Added `FontSrcGetGlyphIndexFromCodepoint`. - (#9559, #5647, #9540, #8466, #8465) - - Added `IMGUI_DISABLE_STB_TRUETYPE` to completely omit the stb_truetype loader - code + stb_truetype.h code. (#9573) - ColorEdit: - - ColorButton, ColorEdit, ColorPicker: cancel-out alpha caused by `BeginDisabled()` so + - ColorButton, ColorEdit, ColorPicker: cancel-out alpha caused by BeginDisabled() so disabled color buttons have the same color as non-disabled oness. (#9511) - ColorButton: fixed issues/inconsistencies with checkerboard rendering when combining color alpha and global style alpha. (#9511) [@enjmiah, @ocornut] @@ -481,58 +79,38 @@ Other Changes: - Amended context menu right-click opening code to check that the right-click hasn't been owned by another items. This is more correct and also necessary to avoid Drags/Sliders cancelling also triggering a cancel menu. (#8564, #9534) - - Reworked `GetMousePosOnOpeningCurrentPopup()` to be legal to call within the - BeginPopup/EndPopup scope of a popup which was just closed. (#9551) [@jkunstwald] -- ImGuiTextFilter: - - Added support for space as an "and" filter, which is the standard. (#2435, #30) - e.g. w/ filter 'hello world' (without quotes) both words needs to be in input data. - - Added support for double-quoted "xxx" blocks to e.g. match words sequences. (#2435) - e.g. w/ filter "hello world" the exact sequence needs to be in input data. - - Fixed filtering when mixing "include" and "-exclude" keyword so that an "-exclude" - match always filters out. (#2435) [@kudaba, @ocornut] - - Added `DrawWithHint()` function. (#6206, #6395, #6447) - - Added a "incl -excl" hint by default when the search field is empty. (#6206, #6395, #6447) -- Widgets: - - Checkbox, Menus: check marks use anti-aliased ends. - - Tweaked rendering in various locations to avoid blurriness: - - Windows: title-bar and menu-bar border (when thickness>1.0f). - - SeparatorText: border (when thickness>1.0f). - - Tree: hierarchy lines (when thickness>1.0f). - - InputText: input caret (when thickness>1.0f). - - TabBar: selected overline border (when thickness>1.0f). - Misc: + - Added `ImGuiItemFlags_MixedValue` flag for representing mixed/indeterminate values. + Supported by: Checkbox(), RadioButton(), DragXXX(), SliderXXX(), InputXXX(), ColorXXX() + and Combo() functions. + The scoped flag is designed for usage by advanced property editors. (#5518, #5677, #6865) - Fixed `GetBackgroundDrawList()`/`GetForegroundDrawList()` not being properly reset - every frame when accumulated session time is very large (e.g. a few days). [@lailoken] + every frame when cumulated session time is very large (e.g. a few days). [@lailoken] - Added `IM_NODEBUGSTEP` helper to tag functions with `__declspec(non_user_code)` (MSVC) or `[[gnu::artificial]]` (Clang/GCC) in order to provide a hint to debuggers to skip trivial functions when stepping into. - Tagged various trivial functions using `IM_NODEBUGSTEP`: `ImVec2()`, `ImVec4()` etc. and various operators. - - Fixed strict aliasing violation in `ImHashData()` affecting Clang 23 + SSE 4.2 + -flto. - Could manifest as `ImFontAtlasBakedGetId()` computation omitting font size from - the hashed data. (#9557, #9560) [@sthalik] - - IO: restore default clipboard/ime/shell platform handlers on `ClearPlatformHandlers()`, fixing + - IO: restore default clipboard/ime/shell platform handlers on ClearPlatformHandlers(), fixing issues switching backends mid-session to one relying on default. (#9537, #8945, #2769) [@lstalmir] +- DrawList: + - Per-viewport FramebufferScale for Apple/Retina screen is applied to draw lists: + - AA Fringe is scaled accordingly. + - Circle and Curves tessellation error are scaled accordingly. + - Reworked assert in PushTexture() to allow convenience grace period of using a + texture that was queue for destroy during the frame. Make it safe to stick to + an existing texture during the frame. (#9528, #8465) + - Added optional `platform_io.DrawCallback_SetSamplerFromTex` standard backend-agnostic + draw callback for requesting to use the sampler associated already associated to a texture. + Currently only supported by the OpenGL2/3 and SDLRenderer3 backend. (#9378) - Demo: - Added `Widgets->Mixed Values` section. (#5518, #5677, #6865) - - Custom Rendering section: exposed new flags; showcasing overlapping strokes - and filled shapes; added an option to animate thickness; added new shapes - to showcase new rendering features that previously hit limitations. - - Style Editor: fixed style/colors combo box applying style when opening Combo. - Backends: - QNX: added QNX Screen backend. (#9492) [@mgorchak-blackberry] - - Metal, Metal4: added support for rendering inside a render pass with multiple color - attachments (e.g. when merged with other passes): we render to the first color attachment - and leave the other ones untouched. (#9574) [@tqjxlm] - OpenGL2, OpenGL3: added support for `platform_io.DrawCallback_SetSamplerFromTex` draw callback to request using the sampler associated already associated to a texture. (#9378) - - OpenGL2, OpenGL3: fixed `DrawCallback_ResetRenderState` handler not resetting all states + - OpenGL2, OpenGL3: fixed `DrawCallback_ResetRenderState` handler not reseting all states in the glTexParameter() path. (#9378) - - OpenGL3: added `ImGui_ImplOpenGL3_SetClipOrigin()` to specify origin between - `GL_LOWER_LEFT` (new default), `GL_UPPER_LEFT` and `0` (autodetect, old default). - - OpenGL3: avoid querying `glGetIntegerv(GL_CLIP_ORIGIN)` multiple times when using - when using default and using `DrawCallback_ResetRenderState`, at it appear to stall - some drivers. (#2186, #3998, #3146, #3143, #8640) - SDL2: fixed querying framebuffer scale/density when using Metal without going through a SDL_Renderer. (#5592) [@lailoken] - SDLRenderer3: restore any temporarily modified texture scale modes at the of `RenderDrawData()`. (#9378) @@ -543,19 +121,12 @@ Other Changes: Note: this callback is only supported by selected rendering backends: most other graphics API don't have the equivalent of `SDL_SetTextureScaleMode()` and the callback won't work with them. - Vulkan: added for support for multiple Vulkan contexts with custom loaders. (#6616) [@lstalmir] - - Vulkan: added support for rendering inside a render pass with multiple color attachments - (e.g. when merged with other passes): we render to the first color attachment and leave the - other ones untouched. (#9574) [@tqjxlm] - WebGPU: fixed passing non-integer sizes to `wgpuRenderPassEncoderSetViewport()` - when `FramebufferScale` is >1.0f. (#9515, #8628) [@WayU] + when when `FramebufferScale` is >1.0f. (#9515, #8628) [@WayU] - WebGPU: update to build with wgpu-native 29.0+. (#9377, #9532, #9530) [@lucascompython, @ivan-enzhaev] - Examples: - - All: all examples now default to use a little bit of rounding (`FrameRounding` and `GrabRounding`). - MSVC: disabled /JMC in Visual Studio projects (unnecessary overhead). - GLFW/SDL2/SDL3+WebGPU: fixed running with wgpu-native missing `wgpuInstanceWaitAny()`. (#9377) - - GLFW/SDL2/SDL3+WebGPU: better select surface format. (#9576) [@ypujante] - - GLFW+Metal: fixed mistakenly calling `ImGui_ImplGlfw_InitForOpenGL()`, which - broke multi-viewport support. (#9564) [@ypujante] - SDL2+Metal: create Metal context without using a `SDL_Renderer`. - QNX+OpenGL3, QNX+Vulkan: added QNX Screen examples. (#9492) [@mgorchak-blackberry] - OSX+OpenGL3: added example_apple_opengl3/ (OSX/Cocoa + OpenGL 3.2 Core profile). @@ -2161,7 +1732,7 @@ Non-breaking Fonts/Textures related changes: - Fonts: ImFontAtlas::AddFontXXX() can fail more gracefully if error handling is configured to not assert (this will be better exposed via future font flags). - Fonts: added style.FontScaleBase scaling factor (previously called io.FontGlobalScale). -- Fonts: added style.FontScaleDpi scaling factor. This is designed to be changed on +- Fonts: added style.FontScaleDpi scaling factor. This is designed to be be changed on per-monitor/per-viewport basis, which `io.ConfigDpiScaleFonts` does automatically. (which is why it is separate from FontScaleBase). - Fonts: added optional font_size parameter to ImGui::PushFont() function. @@ -3316,7 +2887,7 @@ Other changes: - Backends: Vulkan: Remove Volk/ from volk.h #include directives. (#7722, #6582, #4854) [@martin-ejdestig] - Examples: SDL3: Remove use of SDL_HINT_IME_NATIVE_UI since new SDL_HINT_IME_IMPLEMENTED_UI - values has a more suitable default for our case. + values has a more suitable default for our case case. - Examples: GLFW+Vulkan, SDL+Vulkan: handle swap chain resize even without Vulkan returning VK_SUBOPTIMAL_KHR, which doesn't seem to happen on Wayland. (#7671) [@AndreiNego, @ocornut] @@ -5269,7 +4840,7 @@ Other Changes: - ColorPicker4: Fixed picker being unable to select exact 1.0f color when dragging toward the edges of the SV square (previously picked 0.999989986f). (#3517) [@rokups] - Menus: Fixed vertical alignments of MenuItem() calls within a menu bar (broken in 1.84). (#4538) -- Menus: Improve closing logic when moving diagonally in empty space between parent and child menus to +- Menus: Improve closing logic when moving diagonally in empty between between parent and child menus to accommodate for varying font size and dpi. - Menus: Fixed crash when navigating left inside a child window inside a sub-menu. (#4510). - Menus: Fixed an assertion happening in some situations when closing nested menus (broken in 1.83). (#4640) diff --git a/docs/README.md b/docs/README.md index 1dea58176..91bc92cde 100644 --- a/docs/README.md +++ b/docs/README.md @@ -113,7 +113,7 @@ Calling the `ImGui::ShowDemoWindow()` function will create a demo window showcas - [imgui_explorer](https://pthom.github.io/imgui_explorer): Web version of the demo w/ source code browser, courtesy of [@pthom](https://github.com/pthom). 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-20261015-win32.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20261015-win32.zip) (Win32, 1.93.0, built 2026/10/15, master) or [older binaries](https://www.dearimgui.com/binaries). +- [imgui-demo-binaries-20260225.zip](https://www.dearimgui.com/binaries/imgui-demo-binaries-20260225.zip) (Windows, 1.92.6, built 2026/02/25, master) or [older binaries](https://www.dearimgui.com/binaries). ### Gallery diff --git a/examples/example_allegro5/main.cpp b/examples/example_allegro5/main.cpp index 577f09911..ebb6d76b0 100644 --- a/examples/example_allegro5/main.cpp +++ b/examples/example_allegro5/main.cpp @@ -42,24 +42,21 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup Platform/Renderer backends ImGui_ImplAllegro5_Init(display); // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_android_opengl3/main.cpp b/examples/example_android_opengl3/main.cpp index edd654feb..382006fa0 100644 --- a/examples/example_android_opengl3/main.cpp +++ b/examples/example_android_opengl3/main.cpp @@ -144,12 +144,8 @@ void Init(struct android_app* app) io.IniFilename = g_IniFilename.c_str();; // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup Platform/Renderer backends ImGui_ImplAndroid_Init(g_App->window); @@ -157,18 +153,20 @@ void Init(struct android_app* app) // Setup scaling float main_scale = 2.0f; + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! // - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); diff --git a/examples/example_apple_metal/main.mm b/examples/example_apple_metal/main.mm index cb27f3330..b8edbd2d1 100644 --- a/examples/example_apple_metal/main.mm +++ b/examples/example_apple_metal/main.mm @@ -62,24 +62,21 @@ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup Renderer backend ImGui_ImplMetal_Init(_device); // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); @@ -111,6 +108,7 @@ #if TARGET_OS_OSX ImGui_ImplOSX_Init(self.view); + [NSApp activateIgnoringOtherApps:YES]; #endif } @@ -272,22 +270,6 @@ @implementation AppDelegate --(void)applicationDidFinishLaunching:(NSNotification *)notification -{ - NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+Metal Example"]; - NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [quitMenuItem setTarget:NSApp]; - [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; - - NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; - [appMenuItem setSubmenu:appMenu]; - [mainMenuBar addItem:appMenuItem]; - [NSApp setMainMenu:mainMenuBar]; - - [NSApp activateIgnoringOtherApps:YES]; -} - -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { return YES; @@ -302,7 +284,6 @@ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable backing:NSBackingStoreBuffered defer:NO]; - self.window.title = @"Dear ImGui OSX+Metal Example"; self.window.contentViewController = rootViewController; [self.window center]; [self.window makeKeyAndOrderFront:self]; @@ -350,6 +331,7 @@ int main(int, const char**) AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window [NSApp setDelegate:appDelegate]; + [NSApp activateIgnoringOtherApps:YES]; [NSApp run]; } return 0; diff --git a/examples/example_apple_metal4/main.mm b/examples/example_apple_metal4/main.mm index 40fbbe764..1102e41f8 100644 --- a/examples/example_apple_metal4/main.mm +++ b/examples/example_apple_metal4/main.mm @@ -66,12 +66,8 @@ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones. @@ -80,12 +76,13 @@ // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); @@ -117,6 +114,7 @@ #if TARGET_OS_OSX ImGui_ImplOSX_Init(self.view); + [NSApp activateIgnoringOtherApps:YES]; #endif } @@ -288,22 +286,6 @@ @implementation AppDelegate --(void)applicationDidFinishLaunching:(NSNotification *)notification -{ - NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+Metal4 Example"]; - NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [quitMenuItem setTarget:NSApp]; - [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; - - NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; - [appMenuItem setSubmenu:appMenu]; - [mainMenuBar addItem:appMenuItem]; - [NSApp setMainMenu:mainMenuBar]; - - [NSApp activateIgnoringOtherApps:YES]; -} - -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { return YES; @@ -318,7 +300,6 @@ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable backing:NSBackingStoreBuffered defer:NO]; - self.window.title = @"Dear ImGui OSX+Metal4 Example"; self.window.contentViewController = rootViewController; [self.window center]; [self.window makeKeyAndOrderFront:self]; @@ -366,6 +347,7 @@ int main(int, const char**) AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window [NSApp setDelegate:appDelegate]; + [NSApp activateIgnoringOtherApps:YES]; [NSApp run]; } return 0; diff --git a/examples/example_apple_opengl2/main.mm b/examples/example_apple_opengl2/main.mm index 94e03c6d4..7cdc38f20 100644 --- a/examples/example_apple_opengl2/main.mm +++ b/examples/example_apple_opengl2/main.mm @@ -50,12 +50,8 @@ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup Platform/Renderer backends ImGui_ImplOSX_Init(self); @@ -63,12 +59,13 @@ // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); @@ -191,14 +188,19 @@ -(void)setupMenu { NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"]; - NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [quitMenuItem setTarget:NSApp]; - [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + NSMenu* appMenu; + NSMenuItem* menuItem; - NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; - [appMenuItem setSubmenu:appMenu]; - [mainMenuBar addItem:appMenuItem]; + appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"]; + menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL2 Example" action:@selector(terminate:) keyEquivalent:@"q"]; + [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + + menuItem = [[NSMenuItem alloc] init]; + [menuItem setSubmenu:appMenu]; + + [mainMenuBar addItem:menuItem]; + + appMenu = nil; [NSApp setMainMenu:mainMenuBar]; } @@ -209,6 +211,10 @@ -(void)applicationDidFinishLaunching:(NSNotification *)aNotification { + // Make the application a foreground application (else it won't receive keyboard events) + ProcessSerialNumber psn = {0, kCurrentProcess}; + TransformProcessType(&psn, kProcessTransformToForegroundApplication); + // Menu [self setupMenu]; @@ -232,8 +238,6 @@ NSLog(@"No OpenGL Context!"); [view initialize]; - - [NSApp activateIgnoringOtherApps:YES]; } @end @@ -242,17 +246,14 @@ // Application main() function //----------------------------------------------------------------------------------- -int main(int, const char**) +int main(int argc, const char* argv[]) { @autoreleasepool { - [NSApplication sharedApplication]; - [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - - AppDelegate* appDelegate = [[AppDelegate alloc] init]; - [NSApp setDelegate:appDelegate]; - + NSApp = [NSApplication sharedApplication]; + AppDelegate* delegate = [[AppDelegate alloc] init]; + [[NSApplication sharedApplication] setDelegate:delegate]; [NSApp run]; } - return 0; + return NSApplicationMain(argc, argv); } diff --git a/examples/example_apple_opengl3/main.mm b/examples/example_apple_opengl3/main.mm index 77c95a90e..241aa1332 100644 --- a/examples/example_apple_opengl3/main.mm +++ b/examples/example_apple_opengl3/main.mm @@ -49,12 +49,8 @@ io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup Platform/Renderer backends [[self openGLContext] makeCurrentContext]; // ImGui_ImplOpenGL3_Init() requires a current GL context. @@ -63,12 +59,13 @@ // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); @@ -191,14 +188,19 @@ -(void)setupMenu { NSMenu* mainMenuBar = [[NSMenu alloc] init]; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL3 Example"]; - NSMenuItem* quitMenuItem = [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"]; - [quitMenuItem setTarget:NSApp]; - [quitMenuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + NSMenu* appMenu; + NSMenuItem* menuItem; - NSMenuItem* appMenuItem = [[NSMenuItem alloc] init]; - [appMenuItem setSubmenu:appMenu]; - [mainMenuBar addItem:appMenuItem]; + appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL3 Example"]; + menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL3 Example" action:@selector(terminate:) keyEquivalent:@"q"]; + [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; + + menuItem = [[NSMenuItem alloc] init]; + [menuItem setSubmenu:appMenu]; + + [mainMenuBar addItem:menuItem]; + + appMenu = nil; [NSApp setMainMenu:mainMenuBar]; } @@ -209,6 +211,10 @@ -(void)applicationDidFinishLaunching:(NSNotification *)aNotification { + // Make the application a foreground application (else it won't receive keyboard events) + ProcessSerialNumber psn = {0, kCurrentProcess}; + TransformProcessType(&psn, kProcessTransformToForegroundApplication); + // Menu [self setupMenu]; @@ -233,8 +239,6 @@ NSLog(@"No OpenGL Context!"); [view initialize]; - - [NSApp activateIgnoringOtherApps:YES]; } @end @@ -243,17 +247,14 @@ // Application main() function //----------------------------------------------------------------------------------- -int main(int, const char**) +int main(int argc, const char* argv[]) { @autoreleasepool { - [NSApplication sharedApplication]; - [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - - AppDelegate* appDelegate = [[AppDelegate alloc] init]; - [NSApp setDelegate:appDelegate]; - + NSApp = [NSApplication sharedApplication]; + AppDelegate* delegate = [[AppDelegate alloc] init]; + [[NSApplication sharedApplication] setDelegate:delegate]; [NSApp run]; } - return 0; + return NSApplicationMain(argc, argv); } diff --git a/examples/example_glfw_metal/main.mm b/examples/example_glfw_metal/main.mm index d398adc6b..0ded0a3bd 100644 --- a/examples/example_glfw_metal/main.mm +++ b/examples/example_glfw_metal/main.mm @@ -46,14 +46,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -61,17 +58,18 @@ int main(int, char**) id commandQueue = [device newCommandQueue]; // Setup Platform/Renderer backends - ImGui_ImplGlfw_InitForOther(window, true); + ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplMetal_Init(device); // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_opengl2/build_win.bat b/examples/example_glfw_opengl2/build_win.bat deleted file mode 100644 index cca29d76f..000000000 --- a/examples/example_glfw_opengl2/build_win.bat +++ /dev/null @@ -1,21 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_glfw_opengl2 -@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp -@set LIBS=glfw3.lib opengl32.lib gdi32.lib shell32.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-32 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-64 - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_opengl2/build_win32.bat b/examples/example_glfw_opengl2/build_win32.bat new file mode 100644 index 000000000..24c0e08fd --- /dev/null +++ b/examples/example_glfw_opengl2/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_glfw_opengl2 +@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include +@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 /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_opengl2/main.cpp b/examples/example_glfw_opengl2/main.cpp index 454849c5e..48584eaf8 100644 --- a/examples/example_glfw_opengl2/main.cpp +++ b/examples/example_glfw_opengl2/main.cpp @@ -55,14 +55,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -72,12 +69,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_opengl3/build_win.bat b/examples/example_glfw_opengl3/build_win.bat deleted file mode 100644 index a39236cdd..000000000 --- a/examples/example_glfw_opengl3/build_win.bat +++ /dev/null @@ -1,21 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_glfw_opengl3 -@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp -@set LIBS=glfw3.lib opengl32.lib gdi32.lib shell32.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-32 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-64 - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_opengl3/build_win32.bat b/examples/example_glfw_opengl3/build_win32.bat new file mode 100644 index 000000000..b5979ad49 --- /dev/null +++ b/examples/example_glfw_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_glfw_opengl3 +@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include +@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 /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_opengl3/main.cpp b/examples/example_glfw_opengl3/main.cpp index 5abf4654d..fbcc3e595 100644 --- a/examples/example_glfw_opengl3/main.cpp +++ b/examples/example_glfw_opengl3/main.cpp @@ -83,14 +83,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -103,13 +100,14 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - 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. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_vulkan/build_win.bat b/examples/example_glfw_vulkan/build_win.bat deleted file mode 100644 index 0366b1b5d..000000000 --- a/examples/example_glfw_vulkan/build_win.bat +++ /dev/null @@ -1,25 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_glfw_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp -@set LIBS=glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% - -@set OUT_DIR=Release -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_vulkan/build_win32.bat b/examples/example_glfw_vulkan/build_win32.bat new file mode 100644 index 000000000..bb54a4210 --- /dev/null +++ b/examples/example_glfw_vulkan/build_win32.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. + +@set OUT_EXE=example_glfw_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-32 /libpath:%VULKAN_SDK%\lib32 glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% + +@set OUT_DIR=Release +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_vulkan/build_win64.bat b/examples/example_glfw_vulkan/build_win64.bat new file mode 100644 index 000000000..ca9b788d8 --- /dev/null +++ b/examples/example_glfw_vulkan/build_win64.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup 64-bit command-line compiler. + +@set OUT_EXE=example_glfw_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-64 /libpath:%VULKAN_SDK%\lib glfw3.lib opengl32.lib gdi32.lib shell32.lib vulkan-1.lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% + +@set OUT_DIR=Release +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_glfw_vulkan/main.cpp b/examples/example_glfw_vulkan/main.cpp index e5f4d7560..f2139cef7 100644 --- a/examples/example_glfw_vulkan/main.cpp +++ b/examples/example_glfw_vulkan/main.cpp @@ -392,14 +392,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -425,12 +422,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_glfw_wgpu/main.cpp b/examples/example_glfw_wgpu/main.cpp index 441da4a4a..fe8b3de49 100644 --- a/examples/example_glfw_wgpu/main.cpp +++ b/examples/example_glfw_wgpu/main.cpp @@ -89,14 +89,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -114,13 +111,14 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - 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. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS @@ -292,16 +290,6 @@ int main(int, char**) return 0; } -static WGPUTextureFormat SelectSurfaceFormat(const WGPUSurfaceCapabilities& capabilities) -{ - const WGPUTextureFormat preferredFormats[] = { WGPUTextureFormat_BGRA8Unorm, WGPUTextureFormat_RGBA8Unorm, WGPUTextureFormat_BGRA8UnormSrgb, WGPUTextureFormat_RGBA8UnormSrgb }; - for (WGPUTextureFormat preferredFormat : preferredFormats) - for (size_t n = 0; n < capabilities.formatCount; n++) - if (capabilities.formats[n] == preferredFormat) - return preferredFormat; - return capabilities.formatCount > 0 ? capabilities.formats[0] : WGPUTextureFormat_Undefined; -} - #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -452,7 +440,8 @@ static bool InitWGPU(GLFWwindow* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); - preferred_fmt = SelectSurfaceFormat(surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK) @@ -481,7 +470,8 @@ static bool InitWGPU(GLFWwindow* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); - preferred_fmt = SelectSurfaceFormat(surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; #endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; diff --git a/examples/example_glut_opengl2/main.cpp b/examples/example_glut_opengl2/main.cpp index 227dad48a..ca8017f5b 100644 --- a/examples/example_glut_opengl2/main.cpp +++ b/examples/example_glut_opengl2/main.cpp @@ -63,12 +63,8 @@ int main(int argc, char** argv) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // 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(). @@ -84,12 +80,13 @@ int main(int argc, char** argv) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_null/build_win.bat b/examples/example_null/build_win32.bat similarity index 74% rename from examples/example_null/build_win.bat rename to examples/example_null/build_win32.bat index 6c4d4e036..be81d8093 100644 --- a/examples/example_null/build_win.bat +++ b/examples/example_null/build_win32.bat @@ -1,3 +1,3 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat, or vcvarsall.bat to setup command-line compiler. +@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 /utf-8 /I ..\.. %* *.cpp ..\..\*.cpp /FeDebug/example_null.exe /FoDebug/ /link gdi32.lib shell32.lib imm32.lib diff --git a/examples/example_null/example_null.vcxproj b/examples/example_null/example_null.vcxproj index 1353fc0b3..61e388f96 100644 --- a/examples/example_null/example_null.vcxproj +++ b/examples/example_null/example_null.vcxproj @@ -92,9 +92,8 @@ true - - - %(AdditionalLibraryDirectories) + d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) Console @@ -108,9 +107,8 @@ true - - - %(AdditionalLibraryDirectories) + d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) Console @@ -128,9 +126,8 @@ true true true - - - %(AdditionalLibraryDirectories) + d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) Console @@ -148,9 +145,8 @@ true true true - - - %(AdditionalLibraryDirectories) + d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) Console diff --git a/examples/example_null/main.cpp b/examples/example_null/main.cpp index ee6319fdc..eba675670 100644 --- a/examples/example_null/main.cpp +++ b/examples/example_null/main.cpp @@ -16,14 +16,6 @@ int main(int, char**) ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); - // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); - ImGui::StyleColorsDark(); - //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; - ImGui_ImplNullPlatform_Init(); ImGui_ImplNullRender_Init(); diff --git a/examples/example_qnx_opengl3/main.cpp b/examples/example_qnx_opengl3/main.cpp index f7f3f4ac7..d78bee90c 100644 --- a/examples/example_qnx_opengl3/main.cpp +++ b/examples/example_qnx_opengl3/main.cpp @@ -63,14 +63,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -80,12 +77,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_qnx_vulkan/main.cpp b/examples/example_qnx_vulkan/main.cpp index 1d596d72e..ae309ad15 100644 --- a/examples/example_qnx_vulkan/main.cpp +++ b/examples/example_qnx_vulkan/main.cpp @@ -471,14 +471,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -504,12 +501,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_directx11/build_win.bat b/examples/example_sdl2_directx11/build_win.bat deleted file mode 100644 index 6b279b937..000000000 --- a/examples/example_sdl2_directx11/build_win.bat +++ /dev/null @@ -1,21 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_sdl2_directx11 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp -@set LIBS=SDL2.lib SDL2main.lib d3d11.lib d3dcompiler.lib shell32.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 - -@set OUT_DIR=Debug -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/examples/example_sdl2_directx11/build_win32.bat b/examples/example_sdl2_directx11/build_win32.bat new file mode 100644 index 000000000..f0b485ca6 --- /dev/null +++ b/examples/example_sdl2_directx11/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_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_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 /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj b/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj index 4ba9ac321..afa9d5de4 100644 --- a/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj +++ b/examples/example_sdl2_directx11/example_sdl2_directx11.vcxproj @@ -97,7 +97,7 @@ true - %SDL2_DIR%\lib\x86;%(AdditionalLibraryDirectories) + %SDL2_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -113,7 +113,7 @@ true - %SDL2_DIR%\lib\x64;%(AdditionalLibraryDirectories) + %SDL2_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -133,7 +133,7 @@ true true true - %SDL2_DIR%\lib\x86;%(AdditionalLibraryDirectories) + %SDL2_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console @@ -154,7 +154,7 @@ true true true - %SDL2_DIR%\lib\x64;%(AdditionalLibraryDirectories) + %SDL2_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) SDL2.lib;SDL2main.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console @@ -186,4 +186,4 @@ - + \ No newline at end of file diff --git a/examples/example_sdl2_directx11/main.cpp b/examples/example_sdl2_directx11/main.cpp index c5bbc3baf..cf3971646 100644 --- a/examples/example_sdl2_directx11/main.cpp +++ b/examples/example_sdl2_directx11/main.cpp @@ -77,14 +77,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -94,12 +91,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_metal/main.mm b/examples/example_sdl2_metal/main.mm index 344310a3d..edd436aca 100644 --- a/examples/example_sdl2_metal/main.mm +++ b/examples/example_sdl2_metal/main.mm @@ -68,14 +68,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -85,12 +82,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_opengl2/build_win.bat b/examples/example_sdl2_opengl2/build_win.bat deleted file mode 100644 index 945464c00..000000000 --- a/examples/example_sdl2_opengl2/build_win.bat +++ /dev/null @@ -1,21 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_sdl2_opengl2 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\imgui*.cpp -@set LIBS=SDL2.lib SDL2main.lib opengl32.lib shell32.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 - -@set OUT_DIR=Debug -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/examples/example_sdl2_opengl2/build_win32.bat b/examples/example_sdl2_opengl2/build_win32.bat new file mode 100644 index 000000000..7543edafc --- /dev/null +++ b/examples/example_sdl2_opengl2/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_opengl2 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include +@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 /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_opengl2/main.cpp b/examples/example_sdl2_opengl2/main.cpp index 081874aaa..3b3412b14 100644 --- a/examples/example_sdl2_opengl2/main.cpp +++ b/examples/example_sdl2_opengl2/main.cpp @@ -66,14 +66,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -83,12 +80,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_opengl3/README.md b/examples/example_sdl2_opengl3/README.md index e62dec255..81fd9fe7b 100644 --- a/examples/example_sdl2_opengl3/README.md +++ b/examples/example_sdl2_opengl3/README.md @@ -7,7 +7,7 @@ Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) i ## Windows with Visual Studio's CLI -Use build_win.bat or directly: +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 diff --git a/examples/example_sdl2_opengl3/build_win.bat b/examples/example_sdl2_opengl3/build_win.bat deleted file mode 100644 index 7d8dd115c..000000000 --- a/examples/example_sdl2_opengl3/build_win.bat +++ /dev/null @@ -1,21 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_sdl2_opengl3 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl2.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp -@set LIBS=SDL2.lib SDL2main.lib opengl32.lib shell32.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 - -@set OUT_DIR=Debug -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/examples/example_sdl2_opengl3/build_win32.bat b/examples/example_sdl2_opengl3/build_win32.bat new file mode 100644 index 000000000..7b2fac922 --- /dev/null +++ b/examples/example_sdl2_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_sdl2_opengl3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL2_DIR%\include +@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 /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_opengl3/main.cpp b/examples/example_sdl2_opengl3/main.cpp index c1bc268fa..e7b101087 100644 --- a/examples/example_sdl2_opengl3/main.cpp +++ b/examples/example_sdl2_opengl3/main.cpp @@ -103,14 +103,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -120,13 +117,14 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - 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. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_sdlrenderer2/build_win.bat b/examples/example_sdl2_sdlrenderer2/build_win.bat deleted file mode 100644 index 82bc8613b..000000000 --- a/examples/example_sdl2_sdlrenderer2/build_win.bat +++ /dev/null @@ -1,21 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@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=SDL2.lib SDL2main.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 - -@set OUT_DIR=Debug -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/examples/example_sdl2_sdlrenderer2/build_win32.bat b/examples/example_sdl2_sdlrenderer2/build_win32.bat new file mode 100644 index 000000000..e311bfcd0 --- /dev/null +++ b/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/examples/example_sdl2_sdlrenderer2/main.cpp b/examples/example_sdl2_sdlrenderer2/main.cpp index 9916dd85d..b69867354 100644 --- a/examples/example_sdl2_sdlrenderer2/main.cpp +++ b/examples/example_sdl2_sdlrenderer2/main.cpp @@ -68,14 +68,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -85,12 +82,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_vulkan/build_win.bat b/examples/example_sdl2_vulkan/build_win.bat deleted file mode 100644 index 2b2fedcaa..000000000 --- a/examples/example_sdl2_vulkan/build_win.bat +++ /dev/null @@ -1,25 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@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_sdl2.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp -@set LIBS=SDL2.lib SDL2main.lib shell32.lib vulkan-1.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL2_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_vulkan/build_win32.bat b/examples/example_sdl2_vulkan/build_win32.bat new file mode 100644 index 000000000..f634aba00 --- /dev/null +++ b/examples/example_sdl2_vulkan/build_win32.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. + +@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_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 /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_vulkan/build_win64.bat b/examples/example_sdl2_vulkan/build_win64.bat new file mode 100644 index 000000000..5d315cca2 --- /dev/null +++ b/examples/example_sdl2_vulkan/build_win64.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. + +@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_sdl2.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL2_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib SDL2.lib SDL2main.lib shell32.lib vulkan-1.lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl2_vulkan/main.cpp b/examples/example_sdl2_vulkan/main.cpp index 7c9af9eef..45a5a6de5 100644 --- a/examples/example_sdl2_vulkan/main.cpp +++ b/examples/example_sdl2_vulkan/main.cpp @@ -398,14 +398,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -431,12 +428,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl2_wgpu/main.cpp b/examples/example_sdl2_wgpu/main.cpp index abc7be29c..b0fa54179 100644 --- a/examples/example_sdl2_wgpu/main.cpp +++ b/examples/example_sdl2_wgpu/main.cpp @@ -74,14 +74,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -96,13 +93,14 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - 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. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS @@ -278,16 +276,6 @@ int main(int, char**) return 0; } -static WGPUTextureFormat SelectSurfaceFormat(const WGPUSurfaceCapabilities& capabilities) -{ - const WGPUTextureFormat preferredFormats[] = { WGPUTextureFormat_BGRA8Unorm, WGPUTextureFormat_RGBA8Unorm, WGPUTextureFormat_BGRA8UnormSrgb, WGPUTextureFormat_RGBA8UnormSrgb }; - for (WGPUTextureFormat preferredFormat : preferredFormats) - for (size_t n = 0; n < capabilities.formatCount; n++) - if (capabilities.formats[n] == preferredFormat) - return preferredFormat; - return capabilities.formatCount > 0 ? capabilities.formats[0] : WGPUTextureFormat_Undefined; -} - #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -439,7 +427,8 @@ static bool InitWGPU(SDL_Window* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); - preferred_fmt = SelectSurfaceFormat(surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK) @@ -468,7 +457,8 @@ static bool InitWGPU(SDL_Window* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); - preferred_fmt = SelectSurfaceFormat(surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; #endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; diff --git a/examples/example_sdl3_directx11/build_win.bat b/examples/example_sdl3_directx11/build_win.bat deleted file mode 100644 index 3eccbb2ed..000000000 --- a/examples/example_sdl3_directx11/build_win.bat +++ /dev/null @@ -1,23 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@if /I "%TARGET_ARCH%"=="arm64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_sdl3_directx11 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp -@set LIBS=SDL3.lib d3d11.lib d3dcompiler.lib shell32.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 -@if /I "%TARGET_ARCH%"=="arm64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\arm64 - -@set OUT_DIR=Debug -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/examples/example_sdl3_directx11/build_win32.bat b/examples/example_sdl3_directx11/build_win32.bat new file mode 100644 index 000000000..b84b01f1a --- /dev/null +++ b/examples/example_sdl3_directx11/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_directx11 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 SDL3.lib /LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.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/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj b/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj index 8729480a5..057874196 100644 --- a/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj +++ b/examples/example_sdl3_directx11/example_sdl3_directx11.vcxproj @@ -97,7 +97,7 @@ true - %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) + %SDL3_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -113,7 +113,7 @@ true - %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) + %SDL3_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console msvcrt.lib @@ -133,7 +133,7 @@ true true true - %SDL3_DIR%\lib\x86;%(AdditionalLibraryDirectories) + %SDL3_DIR%\lib\x86;$(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console @@ -154,7 +154,7 @@ true true true - %SDL3_DIR%\lib\x64;%(AdditionalLibraryDirectories) + %SDL3_DIR%\lib\x64;$(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) SDL3.lib;d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) Console @@ -186,4 +186,4 @@ - + \ No newline at end of file diff --git a/examples/example_sdl3_directx11/main.cpp b/examples/example_sdl3_directx11/main.cpp index 8b28d1302..4337d4e2d 100644 --- a/examples/example_sdl3_directx11/main.cpp +++ b/examples/example_sdl3_directx11/main.cpp @@ -68,14 +68,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -85,12 +82,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_metal/main.mm b/examples/example_sdl3_metal/main.mm index 8edd50c09..e6e306624 100644 --- a/examples/example_sdl3_metal/main.mm +++ b/examples/example_sdl3_metal/main.mm @@ -64,14 +64,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -81,12 +78,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_metal4/main.mm b/examples/example_sdl3_metal4/main.mm index b2807935f..6debb5133 100644 --- a/examples/example_sdl3_metal4/main.mm +++ b/examples/example_sdl3_metal4/main.mm @@ -80,14 +80,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -97,12 +94,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_opengl3/README.md b/examples/example_sdl3_opengl3/README.md index bc748afac..a032f8752 100644 --- a/examples/example_sdl3_opengl3/README.md +++ b/examples/example_sdl3_opengl3/README.md @@ -7,7 +7,7 @@ Use the provided project file (.vcxproj). Add to solution (imgui_examples.sln) i ## Windows with Visual Studio's CLI -Use build_win.bat or directly: +Use build_win32.bat or directly: ``` set SDL3_DIR=path_to_your_sdl3_folder cl /Zi /MD /utf-8 /I.. /I..\.. /I%SDL3_DIR%\include main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_opengl3.cpp ..\..\imgui*.cpp /FeDebug/example_sdl3_opengl3.exe /FoDebug/ /link /libpath:%SDL3_DIR%\lib\x86 SDL3.lib opengl32.lib /subsystem:console diff --git a/examples/example_sdl3_opengl3/build_win.bat b/examples/example_sdl3_opengl3/build_win.bat deleted file mode 100644 index 6ea3e3941..000000000 --- a/examples/example_sdl3_opengl3/build_win.bat +++ /dev/null @@ -1,27 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@if /I "%TARGET_ARCH%"=="arm64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@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=SDL3.lib opengl32.lib shell32.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 -@if /I "%TARGET_ARCH%"=="arm64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\arm64 - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_opengl3/build_win32.bat b/examples/example_sdl3_opengl3/build_win32.bat new file mode 100644 index 000000000..5bed40ac1 --- /dev/null +++ b/examples/example_sdl3_opengl3/build_win32.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. + +@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 + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_opengl3/build_win64.bat b/examples/example_sdl3_opengl3/build_win64.bat new file mode 100644 index 000000000..87c6bb8b5 --- /dev/null +++ b/examples/example_sdl3_opengl3/build_win64.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. + +@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\x64 SDL3.lib opengl32.lib shell32.lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_opengl3/main.cpp b/examples/example_sdl3_opengl3/main.cpp index 819d9bd1c..e7d22a40c 100644 --- a/examples/example_sdl3_opengl3/main.cpp +++ b/examples/example_sdl3_opengl3/main.cpp @@ -93,14 +93,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -110,13 +107,14 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - 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. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_sdlgpu3/build_win.bat b/examples/example_sdl3_sdlgpu3/build_win.bat deleted file mode 100644 index c71478b57..000000000 --- a/examples/example_sdl3_sdlgpu3/build_win.bat +++ /dev/null @@ -1,27 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@if /I "%TARGET_ARCH%"=="arm64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_sdl3_sdlgpu3 -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_sdlgpu3.cpp ..\..\imgui*.cpp -@set LIBS=SDL3.lib shell32.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 -@if /I "%TARGET_ARCH%"=="arm64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\arm64 - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_sdlgpu3/build_win64.bat b/examples/example_sdl3_sdlgpu3/build_win64.bat new file mode 100644 index 000000000..ad7a2d603 --- /dev/null +++ b/examples/example_sdl3_sdlgpu3/build_win64.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. + +@set OUT_EXE=example_sdl3_sdlgpu3 +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_sdlgpu3.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x64 SDL3.lib shell32.lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_sdlgpu3/main.cpp b/examples/example_sdl3_sdlgpu3/main.cpp index 6caa71c1a..8edbbbbad 100644 --- a/examples/example_sdl3_sdlgpu3/main.cpp +++ b/examples/example_sdl3_sdlgpu3/main.cpp @@ -70,14 +70,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -93,12 +90,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_sdlrenderer3/build_win.bat b/examples/example_sdl3_sdlrenderer3/build_win.bat deleted file mode 100644 index 9014d76c2..000000000 --- a/examples/example_sdl3_sdlrenderer3/build_win.bat +++ /dev/null @@ -1,23 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@if /I "%TARGET_ARCH%"=="arm64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@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=SDL3.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 -@if /I "%TARGET_ARCH%"=="arm64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\arm64 - -@set OUT_DIR=Debug -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/examples/example_sdl3_sdlrenderer3/build_win32.bat b/examples/example_sdl3_sdlrenderer3/build_win32.bat new file mode 100644 index 000000000..7bc131a6a --- /dev/null +++ b/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/examples/example_sdl3_sdlrenderer3/main.cpp b/examples/example_sdl3_sdlrenderer3/main.cpp index 8fbd6a972..88f9ac7fb 100644 --- a/examples/example_sdl3_sdlrenderer3/main.cpp +++ b/examples/example_sdl3_sdlrenderer3/main.cpp @@ -58,14 +58,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -75,12 +72,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_vulkan/build_win.bat b/examples/example_sdl3_vulkan/build_win.bat deleted file mode 100644 index e1ad37988..000000000 --- a/examples/example_sdl3_vulkan/build_win.bat +++ /dev/null @@ -1,25 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_sdl3_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp -@set LIBS=SDL3.lib shell32.lib vulkan-1.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:%SDL3_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib - -@set OUT_DIR=Debug -mkdir %OUT_DIR% -cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console - -@set OUT_DIR=Release -@REM mkdir %OUT_DIR% -@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_vulkan/build_win32.bat b/examples/example_sdl3_vulkan/build_win32.bat new file mode 100644 index 000000000..3e26d3088 --- /dev/null +++ b/examples/example_sdl3_vulkan/build_win32.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler. + +@set OUT_EXE=example_sdl3_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x86 /libpath:%VULKAN_SDK%\lib32 SDL3.lib shell32.lib vulkan-1.lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_vulkan/build_win64.bat b/examples/example_sdl3_vulkan/build_win64.bat new file mode 100644 index 000000000..5d038d1ee --- /dev/null +++ b/examples/example_sdl3_vulkan/build_win64.bat @@ -0,0 +1,14 @@ +@REM Build for Visual Studio compiler. Run your copy of vcvars64.bat or vcvarsall.bat to setup command-line compiler. + +@set OUT_EXE=example_sdl3_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I%SDL3_DIR%\include /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_sdl3.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\imgui*.cpp +@set LIBS=/LIBPATH:%SDL3_DIR%\lib\x64 /libpath:%VULKAN_SDK%\lib SDL3.lib shell32.lib vulkan-1.lib + +@set OUT_DIR=Debug +mkdir %OUT_DIR% +cl /nologo /Zi /MD /utf-8 %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console + +@set OUT_DIR=Release +@REM mkdir %OUT_DIR% +@REM cl /nologo /Zi /MD /utf-8 /Ox /Oi %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% /subsystem:console diff --git a/examples/example_sdl3_vulkan/main.cpp b/examples/example_sdl3_vulkan/main.cpp index b0474e635..0073b37c5 100644 --- a/examples/example_sdl3_vulkan/main.cpp +++ b/examples/example_sdl3_vulkan/main.cpp @@ -397,14 +397,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -430,12 +427,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_sdl3_wgpu/main.cpp b/examples/example_sdl3_wgpu/main.cpp index 42053f0fb..c66748f80 100644 --- a/examples/example_sdl3_wgpu/main.cpp +++ b/examples/example_sdl3_wgpu/main.cpp @@ -81,14 +81,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -104,13 +101,14 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - 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. + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); #ifndef IMGUI_DISABLE_FILE_FUNCTIONS @@ -289,16 +287,6 @@ int main(int, char**) return 0; } -static WGPUTextureFormat SelectSurfaceFormat(const WGPUSurfaceCapabilities& capabilities) -{ - const WGPUTextureFormat preferredFormats[] = { WGPUTextureFormat_BGRA8Unorm, WGPUTextureFormat_RGBA8Unorm, WGPUTextureFormat_BGRA8UnormSrgb, WGPUTextureFormat_RGBA8UnormSrgb }; - for (WGPUTextureFormat preferredFormat : preferredFormats) - for (size_t n = 0; n < capabilities.formatCount; n++) - if (capabilities.formats[n] == preferredFormat) - return preferredFormat; - return capabilities.formatCount > 0 ? capabilities.formats[0] : WGPUTextureFormat_Undefined; -} - #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) static WGPUAdapter RequestAdapter(wgpu::Instance& instance) { @@ -450,7 +438,8 @@ static bool InitWGPU(SDL_Window* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities); - preferred_fmt = SelectSurfaceFormat(surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; // WGPU backend: Adapter and Device acquisition, Surface creation #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK) @@ -479,7 +468,8 @@ static bool InitWGPU(SDL_Window* window) WGPUSurfaceCapabilities surface_capabilities = {}; wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities); - preferred_fmt = SelectSurfaceFormat(surface_capabilities); + + preferred_fmt = surface_capabilities.formats[0]; #endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo; diff --git a/examples/example_win32_directx10/build_win.bat b/examples/example_win32_directx10/build_win32.bat similarity index 70% rename from examples/example_win32_directx10/build_win.bat rename to examples/example_win32_directx10/build_win32.bat index d7d2f5a6a..78a6e374d 100644 --- a/examples/example_win32_directx10/build_win.bat +++ b/examples/example_win32_directx10/build_win32.bat @@ -1,8 +1,8 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat or vcvarsall.bat to setup command-line compiler. +@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_directx10 -@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" @set SOURCES=main.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\backends\imgui_impl_dx10.cpp ..\..\imgui*.cpp -@set LIBS=d3d10.lib d3dcompiler.lib +@set LIBS=/LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d10.lib d3dcompiler.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/examples/example_win32_directx10/example_win32_directx10.vcxproj b/examples/example_win32_directx10/example_win32_directx10.vcxproj index 89e9393ab..add37ed97 100644 --- a/examples/example_win32_directx10/example_win32_directx10.vcxproj +++ b/examples/example_win32_directx10/example_win32_directx10.vcxproj @@ -93,7 +93,7 @@ true d3d10.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - %(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) Console @@ -108,7 +108,7 @@ true d3d10.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - %(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) Console @@ -127,7 +127,7 @@ true true d3d10.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - %(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) Console @@ -146,7 +146,7 @@ true true d3d10.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - %(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) Console @@ -175,4 +175,4 @@ - + \ No newline at end of file diff --git a/examples/example_win32_directx10/main.cpp b/examples/example_win32_directx10/main.cpp index b68ba06fe..2c3420709 100644 --- a/examples/example_win32_directx10/main.cpp +++ b/examples/example_win32_directx10/main.cpp @@ -59,14 +59,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -76,12 +73,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_directx11/build_win.bat b/examples/example_win32_directx11/build_win32.bat similarity index 70% rename from examples/example_win32_directx11/build_win.bat rename to examples/example_win32_directx11/build_win32.bat index 78758193d..c9a717c60 100644 --- a/examples/example_win32_directx11/build_win.bat +++ b/examples/example_win32_directx11/build_win32.bat @@ -1,9 +1,9 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat, or vcvarsall.bat to setup command-line compiler. +@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_directx11 -@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I "%DXSDK_DIR%Include" @set SOURCES=main.cpp ..\..\backends\imgui_impl_dx11.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp -@set LIBS=d3d11.lib d3dcompiler.lib +@set LIBS=/LIBPATH:"%DXSDK_DIR%/Lib/x86" d3d11.lib d3dcompiler.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/examples/example_win32_directx11/example_win32_directx11.vcxproj b/examples/example_win32_directx11/example_win32_directx11.vcxproj index ace899cb5..ed0b509a8 100644 --- a/examples/example_win32_directx11/example_win32_directx11.vcxproj +++ b/examples/example_win32_directx11/example_win32_directx11.vcxproj @@ -93,7 +93,7 @@ true d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - %(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) Console @@ -108,7 +108,7 @@ true d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - %(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) Console @@ -127,7 +127,7 @@ true true d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - %(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x86;%(AdditionalLibraryDirectories) Console @@ -146,7 +146,7 @@ true true d3d11.lib;d3dcompiler.lib;dxgi.lib;%(AdditionalDependencies) - %(AdditionalLibraryDirectories) + $(DXSDK_DIR)/Lib/x64;%(AdditionalLibraryDirectories) Console @@ -175,4 +175,4 @@ - + \ No newline at end of file diff --git a/examples/example_win32_directx11/main.cpp b/examples/example_win32_directx11/main.cpp index 5f3af383f..524538ac1 100644 --- a/examples/example_win32_directx11/main.cpp +++ b/examples/example_win32_directx11/main.cpp @@ -59,14 +59,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -76,12 +73,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_directx12/build_win.bat b/examples/example_win32_directx12/build_win32.bat similarity index 88% rename from examples/example_win32_directx12/build_win.bat rename to examples/example_win32_directx12/build_win32.bat index d609c7203..cb5e8e273 100644 --- a/examples/example_win32_directx12/build_win.bat +++ b/examples/example_win32_directx12/build_win32.bat @@ -1,4 +1,4 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat, or vcvarsall.bat to setup command-line compiler. +@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_directx12 @set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" diff --git a/examples/example_win32_directx12/main.cpp b/examples/example_win32_directx12/main.cpp index 5fb0ed788..0d8bb20b1 100644 --- a/examples/example_win32_directx12/main.cpp +++ b/examples/example_win32_directx12/main.cpp @@ -139,14 +139,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -171,12 +168,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_directx9/build_win.bat b/examples/example_win32_directx9/build_win.bat deleted file mode 100644 index 4523769df..000000000 --- a/examples/example_win32_directx9/build_win.bat +++ /dev/null @@ -1,21 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_win32_directx9 -@set INCLUDES=/I..\.. /I..\..\backends /I "%DXSDK_DIR%/Include" -@set SOURCES=main.cpp ..\..\backends\imgui_impl_dx9.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp -@set LIBS=d3d9.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /LIBPATH:"%DXSDK_DIR%/Lib/x86" -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /LIBPATH:"%DXSDK_DIR%/Lib/x64" - -@set OUT_DIR=Debug -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/examples/example_win32_directx9/build_win32.bat b/examples/example_win32_directx9/build_win32.bat new file mode 100644 index 000000000..ece5ea1ba --- /dev/null +++ b/examples/example_win32_directx9/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_directx9 +@set INCLUDES=/I..\.. /I..\..\backends /I "%DXSDK_DIR%/Include" +@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 /utf-8 %INCLUDES% /D UNICODE /D _UNICODE %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS% diff --git a/examples/example_win32_directx9/main.cpp b/examples/example_win32_directx9/main.cpp index f0711698e..fbe4c3983 100644 --- a/examples/example_win32_directx9/main.cpp +++ b/examples/example_win32_directx9/main.cpp @@ -57,14 +57,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -74,12 +71,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_opengl3/build_win.bat b/examples/example_win32_opengl3/build_win32.bat similarity index 86% rename from examples/example_win32_opengl3/build_win.bat rename to examples/example_win32_opengl3/build_win32.bat index 0bedfc19f..48df08087 100644 --- a/examples/example_win32_opengl3/build_win.bat +++ b/examples/example_win32_opengl3/build_win32.bat @@ -1,4 +1,4 @@ -@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat, vcvars64.bat or vcvarsall.bat to setup command-line compiler. +@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 diff --git a/examples/example_win32_opengl3/main.cpp b/examples/example_win32_opengl3/main.cpp index 28c92a677..cba8301f8 100644 --- a/examples/example_win32_opengl3/main.cpp +++ b/examples/example_win32_opengl3/main.cpp @@ -68,14 +68,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); - //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; + //ImGui::StyleColorsClassic(); // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -85,12 +82,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/examples/example_win32_vulkan/build_win.bat b/examples/example_win32_vulkan/build_win.bat deleted file mode 100644 index 7e71881b3..000000000 --- a/examples/example_win32_vulkan/build_win.bat +++ /dev/null @@ -1,21 +0,0 @@ -@REM Build for Visual Studio compiler. First run vcvars32.bat (x86) or vcvars64.bat (x64). - -@REM Detect target architecture (VS 2015 uses Platform, unset for native x86; VS 2017+ uses VSCMD_ARG_TGT_ARCH). -@set TARGET_ARCH=%VSCMD_ARG_TGT_ARCH% -@if not defined TARGET_ARCH if "%VisualStudioVersion%"=="14.0" (set TARGET_ARCH=x86& if defined Platform set TARGET_ARCH=%Platform%) -@if /I "%TARGET_ARCH%"=="x86" goto arch_ok -@if /I "%TARGET_ARCH%"=="x64" goto arch_ok -@echo Unsupported or uninitialized compiler environment. First run vcvars32.bat (x86) or vcvars64.bat (x64). -@exit /b 1 - -:arch_ok -@set OUT_EXE=example_win32_vulkan -@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I %VULKAN_SDK%\include -@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp -@set LIBS=vulkan-1.lib -@if /I "%TARGET_ARCH%"=="x86" set LIBS=%LIBS% /libpath:%VULKAN_SDK%\lib32 -@if /I "%TARGET_ARCH%"=="x64" set LIBS=%LIBS% /libpath:%VULKAN_SDK%\lib - -@set OUT_DIR=Debug -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/examples/example_win32_vulkan/build_win32.bat b/examples/example_win32_vulkan/build_win32.bat new file mode 100644 index 000000000..4bfb7cafc --- /dev/null +++ b/examples/example_win32_vulkan/build_win32.bat @@ -0,0 +1,9 @@ +@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_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp +@set LIBS=/libpath:%VULKAN_SDK%\lib32 vulkan-1.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/examples/example_win32_vulkan/build_win64.bat b/examples/example_win32_vulkan/build_win64.bat new file mode 100644 index 000000000..f8c66f799 --- /dev/null +++ b/examples/example_win32_vulkan/build_win64.bat @@ -0,0 +1,9 @@ +@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_vulkan +@set INCLUDES=/I..\.. /I..\..\backends /I "%WindowsSdkDir%Include\um" /I "%WindowsSdkDir%Include\shared" /I %VULKAN_SDK%\include +@set SOURCES=main.cpp ..\..\backends\imgui_impl_vulkan.cpp ..\..\backends\imgui_impl_win32.cpp ..\..\imgui*.cpp +@set LIBS=/libpath:%VULKAN_SDK%\lib vulkan-1.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/examples/example_win32_vulkan/main.cpp b/examples/example_win32_vulkan/main.cpp index 4c66a5422..cbdbdb830 100644 --- a/examples/example_win32_vulkan/main.cpp +++ b/examples/example_win32_vulkan/main.cpp @@ -385,14 +385,11 @@ int main(int, char**) io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style - ImGuiStyle& style = ImGui::GetStyle(); ImGui::StyleColorsDark(); //ImGui::StyleColorsLight(); - //style.FontSizeBase = 16.0f; // Default to 13.0f when unspecified, which allows crisp legacy font for non-4K screens. - style.FrameRounding = 3.0f; - style.GrabRounding = 3.0f; // Setup scaling + ImGuiStyle& style = ImGui::GetStyle(); style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again) style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor) @@ -418,12 +415,13 @@ int main(int, char**) // Load Fonts // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap(). - // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a threshold. + // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit). // - Read 'docs/FONTS.md' for more instructions and details. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + //style.FontSizeBase = 20.0f; //io.Fonts->AddFontDefaultVector(); //io.Fonts->AddFontDefaultBitmap(); //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf"); diff --git a/imconfig.h b/imconfig.h index d9c05692f..a25fa89af 100644 --- a/imconfig.h +++ b/imconfig.h @@ -72,8 +72,7 @@ //---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) //#define IMGUI_USE_WCHAR32 -//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version. -// This is for if you already embed a copy of those library in your code and don't want duplicate code in your binary. +//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" @@ -103,7 +102,6 @@ //---- Use stb_truetype to build and rasterize the font atlas (default) // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. //#define IMGUI_ENABLE_STB_TRUETYPE -//#define IMGUI_DISABLE_STB_TRUETYPE //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. // This will be inlined as part of ImVec2 and ImVec4 class declarations. diff --git a/imgui.cpp b/imgui.cpp index 3e6549e30..64bbe4fb3 100644 --- a/imgui.cpp +++ b/imgui.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.1 WIP +// dear imgui, v1.93.0 WIP // (main code and documentation) // Help: @@ -230,7 +230,7 @@ CODE This is to increase compatibility, increase maintainability and facilitate use from other languages. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that. - We can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally. + We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (so don't use ImVector in your code or at our own risk!). - Building: We don't use nor mandate a build system for the main library. @@ -395,64 +395,8 @@ IMPLEMENTING SUPPORT for ImGuiBackendFlags_RendererHasTextures: When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2026/10/15 (1.93.1) - commented out legacy names/functions which were obsoleted from 1.90.7 (May 2024) to 1.91.1 (Sept 2024): - - `ImGuiMod_Shortcut` --> `ImGuiMod_Ctrl` (since 1.90.7 it maps to Cmd on macOS) - - `ImGuiCol_TabActive` --> `ImGuiCol_TabSelected` - - `ImGuiCol_TabUnfocused` --> `ImGuiCol_TabDimmed` - - `ImGuiCol_TabUnfocusedActive` --> `ImGuiCol_TabDimmedSelected` - - `ImGuiSelectableFlags_DontClosePopups`-> `ImGuiSelectableFlags_NoAutoClosePopups` - - `PushButtonRepeat(bool repeat)` --> `PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat)` - - `PopButtonRepeat()` --> `PopItemFlag()` - - `PushTabStop(bool tab_stop)` --> `PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);` - - `PopTabStop()` --> `PopItemFlag()` - - `io.GetClipboardTextFn` --> `platform_io.Platform_GetClipboardTextFn` - - `io.SetClipboardTextFn` --> `platform_io.Platform_SetClipboardTextFn` - - `io.ClipboardUserData` --> `platform_io.Platform_ClipboardUserData` - 2026/10/07 (1.93.0) - large cleanup/refactor of ImDrawList. many issues and inconsistencies fixed! (#9504) - BELOW IS A SIMPLIFIED/SHORTENED RECAP OF CHANGES. READ CHANGELOG AND LINKS ABOVE FOR MORE DETAILS! - useful links: - - ImDrawList 1.92.9 <> 1.93 Interactive Testbed: https://www.dearimgui.com/docs/drawlist_v193 (<-- you can download this locally) - - ImDrawList Wiki Reference: https://github.com/ocornut/imgui/wiki/Draw-List - - Discussion thread: https://github.com/ocornut/imgui/issues/9504 - - use ImDrawFlags_StrokeLegacy mode to emulate old rendering: - - Per-primitive: draw_list->AddLine(..., ..., ImDrawFlags_StrokeLegacy); - - For a given scope: draw_list->PushDrawFlag(ImDrawFlags_StrokeLegacy, true); draw_list->AddLine(...); draw_list->PopDrawFlag(); - - Globally: ImGui::Checkbox("DefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy); // Map to a checkbox - - Globally: io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map on Shift - - AddLine: removed the (+0.5f,+0.5f) offset that was sneakily added to input coordinates by this function, and led to lots of inconsistencies. - - This fixes inconsistencies in the API and matches the PathXXX API. - - By default, stroke thickness extends on both side of the given segment. e.g for a "pixel-perfect" looking line with thickness=1.0f, coords should be passed as center of each ends of the line. - - Use `ImDrawFlags_StrokeLegacy` to use old offset if required. Or you can apply the offset manually! - - Generally better, simpler and faster to use `AddLineH()`, `AddLineV()` functions added in 1.92.8. - - IF YOU ARE MINDFUL OF PIXEL-PERFECTNESS IN YOUR CUSTOM RENDERING/WIDGETS read Changelog and links above for details. - - AddRect(), AddCircle(), AddNgon(), AddEllipse(), AddTriangle(), AddQuad(): defaulting to "inside" stroke. All closed shapes with thickness=1.0f will appear identical. The difference for thickness>1.0f shapes may be minimal since very large strokes were not well supported for widgets, but stroke will default inside widgets. - - AddCircle(), AddNgon(): removed +0.5f offset added to radius. This fixes inconsistencies in the API. Use `ImDrawFlags_StrokeLegacy` to use old method if required. Or you can apply the offset manually! - - AddRectFilled(): non-integer coordinates will now display anti-aliased edges. Previously, non-integer coordinates rendered with aliased edges snapped by the rasterizer. - - AddRect(), AddRectFilled(): rectangles with inverted coordinates won't be visible unless using ImDrawFlags_StrokeLegacy mode. - With inverted coordinates: - - Legacy `AddRect()` rounding off -> visible but incorrect outer size. - - Legacy `AddRect()` rounding on -> visible but very glitchy. - - Legacy `AddRectFilled()` rounding off -> visible and correct. - - Legacy `AddRectFilled()` rounding on -> visible but very glitchy. - - merged ImDrawListFlags into ImDrawFlags. obsoleted ImDrawListFlags (which were rarely used directly): - - ImDrawListFlags_AntiAliasedLines -> ImDrawFlags_AALines, - - ImDrawListFlags_AntiAliasedFill -> ImDrawFlags_AAFill, - - ImDrawListFlags_AllowVtxOffset -> ImDrawFlags_UseVtxOffset, - - ImDrawListFlags_TextNoPixelSnap -> ImDrawFlags_TextNoPixelSnap, - unifying them allows easily using them for both per-primitives alterations and scope alterations. - - renamed ImDrawFlags_RoundCornersXXXX to ImDrawFlags_RoundXXXX. - - ImDrawFlags_RoundCornersAll -> ImDrawFlags_RoundAll, - - ImDrawFlags_RoundCornersNone -> ImDrawFlags_RoundNone, - - ImDrawFlags_RoundCornersTopLeft -> ImDrawFlags_RoundTopLeft, - - ImDrawFlags_RoundCornersTopRight -> ImDrawFlags_RoundTopRight, - - ImDrawFlags_RoundCornersTop -> ImDrawFlags_RoundTop, - - ImDrawFlags_RoundCornersBottom -> ImDrawFlags_RoundBottom, - etc. kept redirection enums (will obsolete). - - obsoleted style.AntiAliasedLinesUseTex and ImDrawListFlags_AntiAliasedLinesUseTex, as the new line rendering code always uses textures. - - 2026/09/30 (1.93.0) - ImFont: renamed `AddRemapChar()` to `AddRemapCodepoint()` (rarely used, marked internal). (#609, #5748) - - 2026/09/18 (1.93.0) - ImGuiTextFilter: removed `float width` parameter of `Draw(const char* filter, float width)`: prefer using `SetNextItemWidth(float)` which is standard. Kept inline redirection function. - - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol` (default 1.25) which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12) which is in Pixels unit. - - style.CurveTessellationMaxError == sqrtf(style.CurveTessellationTol). + - 2026/08/03 (1.93.0) - Style: obsoleted `style.CurveTessellationTol (default 1.25)` which was in Pixels² unit in favor of `style.CurveTessellationMaxError` (default 1.12)` which is in Pixels unit. + - style.CurveTessellationMaxError == sqrf(style.CurveTessellationTol). - 2026/07/20 (1.92.9) - DragXXX, SliderXXX, InputScalar: with `ImGuiItemFlags_LiveEditOnInputScalar` now defaulting to being disabled: inputting a value with the keyboard doesn't write intermediate values to backing variable. (#9476) - Before: DragFloat() with user typing "123" --> write back 1, then 12, then 123. @@ -1501,6 +1445,7 @@ static void UpdateTexturesNewFrame(); static void UpdateTexturesEndFrame(); static void UpdateSettings(); static int UpdateWindowManualResize(ImGuiWindow* window, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); +static void RenderWindowShadow(ImGuiWindow* window); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); @@ -1628,16 +1573,15 @@ ImGuiStyle::ImGuiStyle() DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. - // Symbols - SymbolArrowSizeFactor = ImVec2(0.72f,0.40f); // Width/height factor of arrows (0.0f..1.0f). Legacy arrows use (0.60f,0.70f) - SymbolArrowThicknessFactor = 0.30f; // Thickness factor of arrows (0.0f..0.5f). 0.0f=Fill. >0.0f=Stroke. Legacy arrows use 0.0f. - // Rendering & Tessellation - AntiAliasedLines = true; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. - AntiAliasedLineEnds = false; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. - AntiAliasedFill = true; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Used at the beginning of the frame to set ImDrawFlags_AAFill in all draw-lists. + AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. + AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). + AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationMaxError = 1.12f; // Maximum error (in pixels) when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + WindowShadowSize = 100.0f; // Size (in pixels) of window shadows. + WindowShadowOffsetDist = 0.0f; // Offset distance (in pixels) of window shadows from casting window. + WindowShadowOffsetAngle = IM_PI * 0.25f; // Offset angle of window shadows from casting window (0.0f = left, 0.5f*PI = bottom, 1.0f*PI = right, 1.5f*PI = top). // Behaviors HoverStationaryDelay = 0.15f; // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary. @@ -1651,7 +1595,6 @@ ImGuiStyle::ImGuiStyle() _NextFrameFontSizeBase = 0.0f; #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS CurveTessellationTol = 0.0f; // Old CurveTessellationTol = CurveTessellationMaxError*CurveTessellationMaxError. - AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures for legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). #endif // Default theme @@ -1920,7 +1863,7 @@ void ImGuiIO::ClearInputMouse() MouseWheel = MouseWheelH = 0.0f; } -ImGuiInputEvent* ImGui::FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg) +static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1) { ImGuiContext& g = *ctx; for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--) @@ -1965,7 +1908,7 @@ void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value) } // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed) - const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key); + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key); const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key); const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down; const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue; @@ -2023,7 +1966,7 @@ void ImGuiIO::AddMousePosEvent(float x, float y) ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y); // Filter duplicate - const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_MousePos); + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos); const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos; if (latest_pos.x == pos.x && latest_pos.y == pos.y) return; @@ -2056,7 +1999,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) } // Filter duplicate - const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button); + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button); const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button]; if (latest_button_down == down) return; @@ -2066,7 +2009,7 @@ void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down) // - At this point we want from !down to down, so this is handling the initial press. if (ConfigMacOSXBehaviors && mouse_button == 0 && down) { - const ImGuiInputEvent* latest_super_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super); + const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super); if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper) { IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n"); @@ -2121,7 +2064,7 @@ void ImGuiIO::AddFocusEvent(bool focused) ImGuiContext& g = *Ctx; // Filter duplicate - const ImGuiInputEvent* latest_event = ImGui::FindLatestInputEvent(&g, ImGuiInputEventType_Focus); + const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus); const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost; if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused)) return; @@ -2269,14 +2212,14 @@ ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, int ImStricmp(const char* str1, const char* str2) { int d; - while ((d = ImToUpper(*str1) - ImToUpper(*str2)) == 0 && *str1) { str1++; str2++; } + while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int ImStrnicmp(const char* str1, const char* str2, size_t count) { int d = 0; - while (count > 0 && (d = ImToUpper(*str1) - ImToUpper(*str2)) == 0 && *str1) { str1++; str2++; count--; } + while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } @@ -2553,13 +2496,7 @@ ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed) #else while (data + 4 <= data_end) { -#if defined(_DEBUG) || defined(_MSC_VER) crc = _mm_crc32_u32(crc, *(ImU32*)data); -#else - ImU32 v; - memcpy(&v, data, sizeof(ImU32)); // Avoid aliasing violation (#9557) - crc = _mm_crc32_u32(crc, v); -#endif data += 4; } while (data < data_end) @@ -3156,11 +3093,11 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE // [SECTION] ImGuiTextFilter //----------------------------------------------------------------------------- -// Helper: Parse and apply text filters e.g. 'aaa bbb -ccc'. +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 { InputBuf[0] = 0; - _CountExclude = 0; + CountGrep = 0; if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_COUNTOF(InputBuf)); @@ -3168,110 +3105,84 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077 } } -bool ImGuiTextFilter::Draw(const char* label) +bool ImGuiTextFilter::Draw(const char* label, float width) { - return DrawWithHint(label, "incl -excl"); -} - -// Use ImGui::SetNextItemWidth() manually if you want to use this. -bool ImGuiTextFilter::DrawWithHint(const char* label, const char* hint) -{ - bool value_changed = ImGui::InputTextWithHint(label, hint, InputBuf, IM_COUNTOF(InputBuf)); + if (width != 0.0f) + ImGui::SetNextItemWidth(width); + bool value_changed = ImGui::InputText(label, InputBuf, IM_COUNTOF(InputBuf)); if (value_changed) Build(); return value_changed; } -// Parse filter and split into a format optimal for PassFilter() +void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector* out) const +{ + out->resize(0); + const char* wb = b; + const char* we = wb; + while (we < e) + { + if (*we == separator) + { + out->push_back(ImGuiTextRange(wb, we)); + wb = we + 1; + } + we++; + } + if (wb != we) + out->push_back(ImGuiTextRange(wb, we)); +} + void ImGuiTextFilter::Build() { - _Items.resize(0); - _CountExclude = 0; + Filters.resize(0); + ImGuiTextRange input_range(InputBuf, InputBuf + ImStrlen(InputBuf)); + input_range.split(',', &Filters); - const char* buf_e = InputBuf + ImStrlen(InputBuf); - const char* word_e; - int seq_start_idx = -1; - for (const char* word_b = InputBuf; word_b < buf_e; word_b = word_e + 1) + CountGrep = 0; + for (ImGuiTextRange& f : Filters) { - // Trim blanks - while (word_b < buf_e && ImCharIsBlankA(word_b[0])) // FIXME: UTF-8 support - word_b++; - const bool is_excl = (word_b < buf_e && word_b[0] == '-'); - if (is_excl) - word_b++; - const bool is_quote = (word_b < buf_e && word_b[0] == '\"'); - if (is_quote) - { - // Parsing quotes. Omit storing leading/trailing quotes. - word_e = ImStrchrRange(++word_b, buf_e, '\"'); - if (word_e == NULL) - word_e = buf_e; - } - else - { - // Handle both ' ' and ',' separators. - for (word_e = word_b; word_e < buf_e; word_e++) - if (*word_e == ' ' || *word_e == ',') - break; - } - - // Min length - if (word_e - word_b > 0) - { - // Add to list. The '-' is not stored in items but implicitly inferred using (n < CountExclude). - // FIXME-OPT: as items are derived from user input buffer and we expect the insert() to behave sanely. - if (is_excl) - { - _Items.insert(_Items.Data + _CountExclude, ImGuiTextFilterItem(word_b, word_e)); - _CountExclude++; - if (seq_start_idx != -1) - seq_start_idx++; - } - else - { - if (seq_start_idx == -1) - seq_start_idx = _Items.Size; - _Items.insert(_Items.Data + _Items.Size, ImGuiTextFilterItem(word_b, word_e)); - _Items.Data[seq_start_idx].CountInclude++; - } - } - - // Next sequence - if (word_e[0] == ',') - seq_start_idx = -1; + while (f.b < f.e && ImCharIsBlankA(f.b[0])) + f.b++; + while (f.e > f.b && ImCharIsBlankA(f.e[-1])) + f.e--; + if (f.empty()) + continue; + if (f.b[0] != '-') + CountGrep += 1; } } -// FIXME: Could use a specialized ImStristr() + pre-convert our filter to uppercase. bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { - if (_Items.Size == 0) + if (Filters.Size == 0) return true; + if (text == NULL) text = text_end = ""; - // Filters are sorted so that '-' ones are always leading. - ImGuiTextFilterItem* seq = _Items.Data; - ImGuiTextFilterItem* seq_excl_end = _Items.Data + _CountExclude; - for (; seq < seq_excl_end; seq++) - if (ImStristr(text, text_end, seq->Begin, seq->Begin + seq->Len) != NULL) - return false; - - // Process includes - ImGuiTextFilterItem* seq_end = _Items.Data + _Items.Size; - if (seq == seq_end) // When no inclusion are specified (only exclusions) we implicitly pass - return true; - while (seq < seq_end) + for (const ImGuiTextRange& f : Filters) { - ImGuiTextFilterItem* seq_incl_end = seq + seq->CountInclude; - IM_ASSERT_PARANOID(seq->CountInclude > 0 && seq_incl_end <= seq_end); - for (; seq < seq_incl_end; seq++) - if (ImStristr(text, text_end, seq->Begin, seq->Begin + seq->Len) == NULL) - break; - if (seq == seq_incl_end) // All matched - return true; - seq = seq_incl_end; // Try next + if (f.b == f.e) + continue; + if (f.b[0] == '-') + { + // Subtract + if (ImStristr(text, text_end, f.b + 1, f.e) != NULL) + return false; + } + else + { + // Grep + if (ImStristr(text, text_end, f.b, f.e) != NULL) + return true; + } } + + // Implicit * grep + if (CountGrep == 0) + return true; + return false; } @@ -3965,6 +3876,7 @@ const char* ImGui::GetStyleColorName(ImGuiCol idx) case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg"; case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg"; + case ImGuiCol_WindowShadow: return "WindowShadow"; } IM_ASSERT(0); return "Unknown"; @@ -4007,12 +3919,13 @@ void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool text_end = text + ImStrlen(text); // FIXME-OPT (not reached by our internal calls) text_display_end = text_end; } - if (text == text_display_end) - return; - window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); - if (g.LogEnabled) - LogRenderedText(&pos, text, text_display_end); + if (text != text_display_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_display_end); + } } void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) @@ -4022,12 +3935,13 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end if (!text_end) text_end = text + ImStrlen(text); // FIXME-OPT (not reached by our internal calls) - if (text == text_end) - return; - window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); - if (g.LogEnabled) - LogRenderedText(&pos, text, text_end); + if (text != text_end) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); + if (g.LogEnabled) + LogRenderedText(&pos, text, text_end); + } } // Default clip_rect uses (pos_min,pos_max) @@ -4035,15 +3949,12 @@ void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end // FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especially for text above draw_list->DrawList. // Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take // better advantage of the render function taking size into account for coarse clipping. +void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) // DOES NOT CALL LogRenderedText(), unlike RenderTextClipped!!! -void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { - if (text == text_end) - return; - // Perform CPU side clipping for single clipped element to avoid using scissor state ImVec2 pos = pos_min; - const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end, false, 0.0f); + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; @@ -4052,20 +3963,18 @@ void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, co need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. - if (align.x > 0.0f) - pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); - if (align.y > 0.0f) - pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); // Render if (need_clipping) { ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); - draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_end, 0.0f, &fine_clip_rect); + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); } else { - draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_end, 0.0f, NULL); + draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); } } @@ -4308,12 +4217,11 @@ static const ImGuiLocEntry GLocalizationEntriesEnUS[] = { ImGuiLocKey_VersionStr, "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" }, { ImGuiLocKey_TableSizeOne, "Size column to fit###SizeOne" }, { ImGuiLocKey_TableSizeAllFit, "Size all columns to fit###SizeAll" }, - { ImGuiLocKey_TableSizeAllDefault, "Size all columns to auto###SizeAll" }, + { ImGuiLocKey_TableSizeAllDefault, "Size all columns to default###SizeAll" }, { ImGuiLocKey_TableReset, "Reset" }, //{ ImGuiLocKey_TableResetAll, "Reset to default###ResetAll" }, { ImGuiLocKey_TableResetOrder, "Reset order###ResetOrder" }, { ImGuiLocKey_TableResetVisibility, "Reset visibility###ResetVisibility" }, - { ImGuiLocKey_TableResetSizing, "Reset sizing###ResetSizing" }, { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)" }, { ImGuiLocKey_WindowingPopup, "(Popup)" }, { ImGuiLocKey_WindowingUntitled, "(Untitled)" }, @@ -4434,7 +4342,7 @@ ImGuiContext::ImGuiContext(ImFontAtlas* shared_font_atlas) NavJustMovedFromFocusScopeId = NavJustMovedToId = NavJustMovedToFocusScopeId = 0; NavJustMovedToKeyMods = ImGuiMod_None; - NavJustMovedToIsTabbing = NavJustMovedToIsInit = false; + NavJustMovedToIsTabbing = false; NavJustMovedToHasSelectionData = false; // All platforms use Ctrl+Tab but Ctrl<>Super are swapped on Mac... @@ -4748,13 +4656,12 @@ void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id) // Call context hooks (used by e.g. test engine) // We assume a small number of hooks so all stored in same array -// Iterate by index: a callback may add a hook, which reallocates the array. Hooks added here are called from the next call. void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type) { ImGuiContext& g = *ctx; - for (int n = 0, hooks_count = g.Hooks.Size; n < hooks_count; n++) - if (g.Hooks[n].Type == hook_type) - g.Hooks[n].Callback(&g, &g.Hooks[n]); + for (ImGuiContextHook& hook : g.Hooks) + if (hook.Type == hook_type) + hook.Callback(&g, &hook); } //----------------------------------------------------------------------------- @@ -5680,21 +5587,15 @@ static void SetupDrawListSharedData() g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4(); g.DrawListSharedData.CurveTessellationMaxError = g.Style.CurveTessellationMaxError; g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError); - g.DrawListSharedData.InitialDrawFlags = ImDrawFlags_None; - if (g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines) - g.Style.AntiAliasedLines = g.Style.AntiAliasedLineEnds = false; - if (g.Style.AntiAliasedFill) - g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AAFill; + g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) - g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALines; - if (g.Style.AntiAliasedLineEnds) - g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_AALineEnds; - if (g.IO.ConfigDebugDrawListDefaultsToStrokeLegacy) - g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_StrokeLegacy; - if (!(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedRoundCorners)) - g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_; + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; + if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines)) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; + if (g.Style.AntiAliasedFill) + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) - g.DrawListSharedData.InitialDrawFlags |= ImDrawFlags_UseVtxOffset; + g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; } void ImGui::NewFrame() @@ -6126,8 +6027,7 @@ static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 if (draw_list->CmdBuffer.Size == 0) draw_list->AddDrawCmd(); draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to strictly ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that) - draw_list->PrimReserve(6, 4); - draw_list->PrimRect(viewport_rect.Min, viewport_rect.Max, col); + draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col); ImDrawCmd cmd = draw_list->CmdBuffer.back(); IM_ASSERT(cmd.ElemCount == 6); draw_list->CmdBuffer.pop_back(); @@ -7376,7 +7276,7 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) { float y = window->Pos.y + window->TitleBarHeight - 1; - window->DrawList->AddLineH(window->Pos.x + border_size, window->Pos.x + window->Size.x - border_size, y, border_col, g.Style.FrameBorderSize, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(window->Pos.x + border_size * 0.5f, window->Pos.x + window->Size.x - border_size * 0.5f, y, border_col, g.Style.FrameBorderSize); } } @@ -7424,17 +7324,22 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar if (bg_col & IM_COL32_A_MASK) { ImRect bg_rect(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size); - ImDrawFlags bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawFlags_RoundAll : ImDrawFlags_RoundBottom; + ImDrawFlags bg_rounding_flags = (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersBottom; ImDrawList* bg_draw_list = window->DrawList; bg_draw_list->AddRectFilled(bg_rect.Min, bg_rect.Max, bg_col, window_rounding, bg_rounding_flags); } } + // Draw window shadow + if (style.WindowShadowSize > 0.0f && (!(flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_Popup))) + if (style.Colors[ImGuiCol_WindowShadow].w > 0.0f) + RenderWindowShadow(window); + // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); - window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundTop); + window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop); } // Menu bar @@ -7442,9 +7347,9 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar { ImRect menu_bar_rect = window->MenuBarRect(); menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. - window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundTop); + window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop); if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) - window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size, menu_bar_rect.Max.x - window_border_size, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5f, menu_bar_rect.Max.x - window_border_size * 0.5f, menu_bar_rect.Max.y, GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } // Scrollbars @@ -7478,6 +7383,16 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar window->DC.NavLayerCurrent = ImGuiNavLayer_Main; } +void ImGui::RenderWindowShadow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + ImGuiStyle& style = g.Style; + float shadow_size = style.WindowShadowSize; + ImU32 shadow_col = GetColorU32(ImGuiCol_WindowShadow); + ImVec2 shadow_offset = ImVec2(ImCos(style.WindowShadowOffsetAngle), ImSin(style.WindowShadowOffsetAngle)) * style.WindowShadowOffsetDist; + window->DrawList->AddShadowRect(window->Pos, window->Pos + window->Size, shadow_col, shadow_size, shadow_offset, ImDrawFlags_ShadowCutOutShapeBackground, window->WindowRounding); +} + // Render title text, collapse button, close button void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) { @@ -7833,7 +7748,6 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) size_t buf_len = (size_t)window->NameBufLen; window->Name = ImStrdupcpy(window->Name, &buf_len, name); window->NameBufLen = (int)buf_len; - window->DrawList->_OwnerName = window->Name; } // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS @@ -7998,13 +7912,9 @@ bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) window->Pos = parent_window->DC.CursorPos; } - if (window->SetWindowPosVal.x != FLT_MAX) - { - const ImVec2 backup_pos_val = window->SetWindowPosVal; + const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); + if (window_pos_with_pivot) SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) - if (window->HiddenFramesCannotSkipItems != 0) - window->SetWindowPosVal = backup_pos_val; // Restore set request while hidden, so an updated size will be accounted for. (#9568) - } else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) window->Pos = FindBestWindowPosForPopup(window); else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) @@ -9392,6 +9302,12 @@ void ImGui::UpdateCurrentFontSize(float restore_font_size_after_scaling) g.FontBaked = (g.Font != NULL && window != NULL) ? g.Font->GetFontBaked(final_size) : NULL; g.FontBakedScale = (g.FontBaked != NULL) ? (g.FontSize / g.FontBaked->Size) : 0.0f; g.DrawListSharedData.FontScale = g.FontBakedScale; + if (g.Font) + { + ImFontAtlas* atlas = g.Font->OwnerAtlas; + g.DrawListSharedData.ShadowRectIds = &atlas->ShadowRectIds[0]; + g.DrawListSharedData.ShadowRectUvs = &atlas->ShadowRectUvs[0]; + } } // Exposed in case user may want to override setting density. @@ -10352,11 +10268,12 @@ void ImGui::TeleportMousePos(const ImVec2& pos) //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y); } +// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.BeginPopupStack.Size > 0) - return g.BeginPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; + return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; return g.IO.MousePos; } @@ -11222,15 +11139,6 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct! if (true) IM_ASSERT(1); else IM_ASSERT(0); - // Check user IM_VEC2_CLASS_EXTRA macro - // (IF YOU GET A "ambiguous overload" COMPILE ERROR HERE: does your IM_VEC2_CLASS_EXTRA macro contains an operator=? - // e.g. ImVec2& operator=(const MyPoint & p) { x = p.x; y = p.y; return *this; } - // You should be able to remove it if you have the corresponding constructor: - // e.g. IM_NODEBUGSTEP constexpr inline ImVec2(const MyPoint& f) : x(f.x), y(f.y) {} - // Allowing you to add this extra operator to ImVec2 would prevent our whole codebase from using v = {x,y} assignment style. - // PLEASE GET IN TOUCH IF REMOVING THE operator= IS A PROBLEM TO YOU) - ImVec2 v; v = { 1.0f, 2.0f }; - // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644) // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it. #ifdef __EMSCRIPTEN__ @@ -11263,14 +11171,6 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() if (g.IO.ConfigErrorRecovery) IM_ASSERT(g.IO.ConfigErrorRecoveryEnableAssert || g.IO.ConfigErrorRecoveryEnableDebugLog || g.IO.ConfigErrorRecoveryEnableTooltip || g.ErrorCallback != NULL); - // Detect if the parameters leading AddFontDefault() to implicitly select either AddFontDefaultBitmap() or AddFontDefaultVector() have changed. - if (g.FrameCount == 2 && g.IO.Fonts->Builder->LoadedFontDefaultAsVector != -1) - { - const bool old_heuristic_result_for_using_vector_font = (bool)g.IO.Fonts->Builder->LoadedFontDefaultAsVector; - const bool new_heuristic_result_for_using_vector_font = ImFontAtlasHeuristicShouldUseDefaultVectorFont(g.IO.Fonts); - IM_ASSERT_USER_ERROR(old_heuristic_result_for_using_vector_font == new_heuristic_result_for_using_vector_font, "AddFontDefault() font selection heuristic parameters changed between load/init time and now. Verify which parameters have changed or load a default font explicitly!"); - } - #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (g.IO.FontGlobalScale > 1.0f) IM_ASSERT(g.Style.FontScaleMain == 1.0f && "Since 1.92: use style.FontScaleMain instead of g.IO.FontGlobalScale!"); @@ -11288,10 +11188,10 @@ static void ImGui::ErrorCheckNewFrameSanityChecks() } // Remap legacy clipboard handlers (OBSOLETED in 1.91.1, August 2024) - //if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl)) - // g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); }; - //if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl)) - // g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); }; + if (g.IO.GetClipboardTextFn != NULL && (g.PlatformIO.Platform_GetClipboardTextFn == NULL || g.PlatformIO.Platform_GetClipboardTextFn == Platform_GetClipboardTextFn_DefaultImpl)) + g.PlatformIO.Platform_GetClipboardTextFn = [](ImGuiContext* ctx) { return ctx->IO.GetClipboardTextFn(ctx->IO.ClipboardUserData); }; + if (g.IO.SetClipboardTextFn != NULL && (g.PlatformIO.Platform_SetClipboardTextFn == NULL || g.PlatformIO.Platform_SetClipboardTextFn == Platform_SetClipboardTextFn_DefaultImpl)) + g.PlatformIO.Platform_SetClipboardTextFn = [](ImGuiContext* ctx, const char* text) { return ctx->IO.SetClipboardTextFn(ctx->IO.ClipboardUserData, text); }; // Remap legacy CurveTessellationTol into CurveTessellationMaxError (OBSOLETED in 1.93.0, August 2026) if (g.Style.CurveTessellationTol != 0.0f) @@ -12179,7 +12079,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) } scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]); } - scroll[axis] = ImRoundPositive64(ImMax(scroll[axis], 0.0f)); + scroll[axis] = ImRound64(ImMax(scroll[axis], 0.0f)); if (!window->Collapsed && !window->SkipItems) scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]); } @@ -12958,7 +12858,7 @@ bool ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags // This is a helper to handle the simplest case of associating one named popup to one given widget. // - To create a popup associated to the last item, you generally want to pass a NULL value to str_id. // - To create a popup with a specific identifier, pass it in str_id. -// - This is useful when using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. +// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. // - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id. // - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // This is essentially the same as: @@ -14300,7 +14200,6 @@ void ImGui::NavInitRequestApplyResult() g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = 0; g.NavJustMovedToIsTabbing = false; - g.NavJustMovedToIsInit = true; g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0; } @@ -14568,7 +14467,6 @@ void ImGui::NavMoveRequestApplyResult() g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = g.NavMoveKeyMods; g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0; - g.NavJustMovedToIsInit = false; g.NavJustMovedToHasSelectionData = (result->ItemFlags & ImGuiItemFlags_HasSelectionUserData) != 0; //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId); } @@ -16781,7 +16679,7 @@ static const char* FormatTextureRefForDebugDisplay(char* buf, int buf_size, ImTe char* buf_end = buf + buf_size; if (tex_ref._TexData != NULL) buf_p += ImFormatString(buf_p, buf_end - buf_p, "#%03d: ", tex_ref._TexData->UniqueID); - ImFormatString(buf_p, buf_end - buf_p, "0x%" IM_PRIX64, ImGui::DebugTextureIDToU64(tex_ref.GetTexID())); + ImFormatString(buf_p, buf_end - buf_p, "0x%X", ImGui::DebugTextureIDToU64(tex_ref.GetTexID())); return buf; } @@ -16833,7 +16731,6 @@ void ImGui::ShowFontAtlas(ImFontAtlas* atlas) if (TreeNode("Loader", "Loader: \'%s\'", atlas->FontLoaderName ? atlas->FontLoaderName : "NULL")) { const ImFontLoader* loader_current = atlas->FontLoader; - IM_UNUSED(loader_current); BeginDisabled(!atlas->RendererHasTextures); #ifdef IMGUI_ENABLE_STB_TRUETYPE const ImFontLoader* loader_stbtruetype = ImFontAtlasGetFontLoaderForStbTruetype(); @@ -17756,9 +17653,10 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con Selectable(buf, false); if (fg_draw_list && IsItemHovered()) { - fg_draw_list->PushDrawFlag(ImDrawFlags_AALines, false); // Disable AA on triangle outlines is more readable for very large and thin triangles. + ImDrawListFlags backup_flags = fg_draw_list->Flags; + fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), 1.0f, ImDrawFlags_Closed); - fg_draw_list->PopDrawFlag(); + fg_draw_list->Flags = backup_flags; } } TreePop(); @@ -17774,7 +17672,8 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co // Draw wire-frame version of all triangles ImRect clip_rect = draw_cmd->ClipRect; ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); - out_draw_list->PushDrawFlag(ImDrawFlags_AALines, false); // Disable AA on triangle outlines is more readable for very large and thin triangles. + ImDrawListFlags backup_flags = out_draw_list->Flags; + out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; ) { ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list @@ -17792,7 +17691,7 @@ void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, co out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles } - out_draw_list->PopDrawFlag(); + out_draw_list->Flags = backup_flags; } // [DEBUG] Compute mask of inputs with the same codepoint. @@ -17802,8 +17701,7 @@ static int CalcFontGlyphSrcOverlapMask(ImFontAtlas* atlas, ImFont* font, unsigne for (int src_n = 0; src_n < font->Sources.Size; src_n++) { ImFontConfig* src = font->Sources[src_n]; - const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - if (loader->FontSrcGetGlyphIndexFromCodepoint(atlas, src, (ImWchar)codepoint) == 0) + if (!(src->FontLoader ? src->FontLoader : atlas->FontLoader)->FontSrcContainsGlyph(atlas, src, (ImWchar)codepoint)) continue; mask |= (1 << src_n); count++; @@ -18409,9 +18307,9 @@ void ImGui::DebugDrawLineExtents(ImU32 col) float curr_x = window->DC.CursorPos.x; float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y); float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y); - window->DrawList->AddLineH(curr_x - 4.0f, curr_x + 5.0f, line_y1, col, 1.0f); - window->DrawList->AddLineV(curr_x, line_y1, line_y2, col, 1.0f); - window->DrawList->AddLineH(curr_x - 4.0f, curr_x + 5.0f, line_y2, col, 1.0f); + window->DrawList->AddLineH(curr_x - 5.0f, curr_x + 5.0f, line_y1, col, 1.0f); + window->DrawList->AddLineV(curr_x - 0.5f, line_y1, line_y2, col, 1.0f); + window->DrawList->AddLineH(curr_x - 5.0f, curr_x + 5.0f, line_y2, col, 1.0f); } // Draw last item rect in ForegroundDrawList (so it is always visible) diff --git a/imgui.h b/imgui.h index 69e061c34..4dfd47e4c 100644 --- a/imgui.h +++ b/imgui.h @@ -1,4 +1,4 @@ -// dear imgui, v1.93.1 WIP +// dear imgui, v1.93.0 WIP // (headers) // Help: @@ -29,8 +29,8 @@ // Library Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals, e.g. '#if IMGUI_VERSION_NUM >= 12345') -#define IMGUI_VERSION "1.93.1 WIP" -#define IMGUI_VERSION_NUM 19303 +#define IMGUI_VERSION "1.93.0 WIP" +#define IMGUI_VERSION_NUM 19297 #define IMGUI_HAS_TABLE // Added BeginTable() - from IMGUI_VERSION_NUM >= 18000 #define IMGUI_HAS_TEXTURES // Added ImGuiBackendFlags_RendererHasTextures - from IMGUI_VERSION_NUM >= 19198 @@ -49,7 +49,7 @@ Index of this file: // [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) // [SECTION] Multi-Select API flags and structures (ImGuiMultiSelectFlags, ImGuiMultiSelectIO, ImGuiSelectionRequest, ImGuiSelectionBasicStorage, ImGuiSelectionExternalStorage) -// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) +// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) // [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport) @@ -130,7 +130,6 @@ Index of this file: // Alternative to using a .natstepfilter file or other scripts in misc/debuggers/ to skip debug-stepping selected trivial functions. // If you get a compiler error or warning related to use, please report it to us! -#ifndef IM_NODEBUGSTEP #if (defined(__clang__) && (__clang_major__ >= 7)) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) #define IM_NODEBUGSTEP [[gnu::artificial]] #elif defined(_MSC_VER) && (_MSC_VER >= 1915) @@ -138,7 +137,6 @@ Index of this file: #else #define IM_NODEBUGSTEP #endif -#endif // Warnings #ifdef _MSC_VER @@ -248,6 +246,7 @@ typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A // - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments. // - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments. typedef int ImDrawFlags; // -> enum ImDrawFlags_ // Flags: for ImDrawList functions +typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList instance typedef int ImDrawTextFlags; // -> enum ImDrawTextFlags_ // Internal, do not use! typedef int ImFontFlags; // -> enum ImFontFlags_ // Flags: for ImFont typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas @@ -769,7 +768,7 @@ namespace ImGui IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. IMGUI_API void SetNextItemStorageID(ImGuiID storage_id); // set id to use for open/close storage (default to same as item id). - IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags = 0); // retrieve tree node open/close state. + IMGUI_API bool TreeNodeGetOpen(ImGuiID storage_id); // retrieve tree node open/close state. // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. @@ -994,7 +993,7 @@ namespace ImGui IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. returns NULL when drag and drop is finished or inactive. use ImGuiPayload::IsDataType() to test for the payload type. - // Disabling + // Disabling [BETA API] // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors) // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) // - Tooltips windows are automatically opted out of disabling. Note that IsItemHovered() by default returns false on disabled items, unless using ImGuiHoveredFlags_AllowWhenDisabled. @@ -1409,7 +1408,7 @@ enum ImGuiSelectableFlags_ ImGuiSelectableFlags_SelectOnNav = 1 << 6, // Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - //ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 + ImGuiSelectableFlags_DontClosePopups = ImGuiSelectableFlags_NoAutoClosePopups, // Renamed in 1.91.0 //ImGuiSelectableFlags_AllowItemOverlap = ImGuiSelectableFlags_AllowOverlap, // Renamed in 1.89.7 #endif }; @@ -1712,7 +1711,7 @@ enum ImGuiKey : int #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS ImGuiKey_COUNT = ImGuiKey_NamedKey_END, // Obsoleted in 1.91.5 because it was misleading (since named keys don't start at 0 anymore) - //ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl (will auto map to Cmd on Mac) + ImGuiMod_Shortcut = ImGuiMod_Ctrl, // Removed in 1.90.7, you can now simply use ImGuiMod_Ctrl //ImGuiKey_ModCtrl = ImGuiMod_Ctrl, ImGuiKey_ModShift = ImGuiMod_Shift, ImGuiKey_ModAlt = ImGuiMod_Alt, ImGuiKey_ModSuper = ImGuiMod_Super, // Renamed in 1.89 //ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter, // Renamed in 1.87 #endif @@ -1838,13 +1837,14 @@ enum ImGuiCol_ ImGuiCol_NavWindowingHighlight, // Highlight window when using Ctrl+Tab ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the Ctrl+Tab window list, when active ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active + ImGuiCol_WindowShadow, // Window shadows ImGuiCol_COUNT, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiCol_NavHighlight = ImGuiCol_NavCursor, // [renamed in 1.91.4] - //ImGuiCol_TabActive = ImGuiCol_TabSelected, // [renamed in 1.90.9] - //ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed, // [renamed in 1.90.9] - //ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected, // [renamed in 1.90.9] + ImGuiCol_TabActive = ImGuiCol_TabSelected, // [renamed in 1.90.9] + ImGuiCol_TabUnfocused = ImGuiCol_TabDimmed, // [renamed in 1.90.9] + ImGuiCol_TabUnfocusedActive = ImGuiCol_TabDimmedSelected, // [renamed in 1.90.9] + ImGuiCol_NavHighlight = ImGuiCol_NavCursor, // [renamed in 1.91.4] #endif }; @@ -2396,17 +2396,17 @@ struct ImGuiStyle ImVec2 DisplaySafeAreaPadding; // Apply to every windows, menus, popups, tooltips: amount where we avoid displaying contents. Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured). float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). We apply per-monitor DPI scaling over this scale. May be removed later. - // Symbols - ImVec2 SymbolArrowSizeFactor; // Width/height factor of arrows (0.0f..1.0f). - float SymbolArrowThicknessFactor; // Thickness factor of arrows (0.0f..0.5f). 0.0f=Fill. >0.0f=Stroke. - // Rendering & Tessellation - bool AntiAliasedLines; // Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawFlags_AALines in all draw-lists. - bool AntiAliasedLineEnds; // Enable anti-aliased lines/borders ends. Nicer for thick lines but more expensive. Used at the beginning of the frame to set ImDrawFlags_AALineEnds in all draw-lists. - bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Used at the beginning of the frame to set ImDrawFlags_AAFill in all draw-lists. + bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). + bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationMaxError; // Maximum error (in pixels) when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. float CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. + float WindowShadowSize; // Size (in pixels) of window shadows. Set this to zero to disable shadows. + float WindowShadowOffsetDist; // Offset distance (in pixels) of window shadows from casting window. + float WindowShadowOffsetAngle; // Offset angle of window shadows from casting window (0.0f = left, 0.5f*PI = bottom, 1.0f*PI = right, 1.5f*PI = top). + // Colors ImVec4 Colors[ImGuiCol_COUNT]; @@ -2428,7 +2428,6 @@ struct ImGuiStyle // Obsolete names #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - bool AntiAliasedLinesUseTex; // [OBSOLETE] Enable anti-aliased lines/borders using textures for legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). Latched at the beginning of the frame (copied to ImDrawList). float CurveTessellationTol; // [OBSOLETE] Old CurveTessellationTol = New CurveTessellationMaxError*CurveTessellationMaxError. // Changed in 1.93.0 // TabMinWidthForCloseButton = TabCloseButtonMinWidthUnselected // Renamed in 1.91.9. #endif @@ -2565,12 +2564,6 @@ struct ImGuiIO // - Backends may have other side-effects on focus loss, so this will reduce side-effects but not necessary remove all of them. bool ConfigDebugIgnoreFocusLoss; // = false // Ignore io.AddFocusEvent(false), consequently not calling io.ClearInputKeys()/io.ClearInputMouse() in input processing. - // Option to compare < 1.93.0 rendering details vs 1.93.0 rendering details. (#9504) - // - Equivalent to calling PushDrawFlag(ImDrawFlags_StrokeLegacy,true) on every draw list instances. - // - Suggested use, e.g. io.ConfigDebugDrawListDefaultsToStrokeLegacy = io.KeyShift; // Map to SHIFT modifier - // - Also see our interactive testbed: https://www.dearimgui.com/docs/drawlist_v193 - bool ConfigDebugDrawListDefaultsToStrokeLegacy; // false // Default all ImDrawList to ImDrawFlags_StrokeLegacy mode, mimicking pre-1.93.0 rendering. - //------------------------------------------------------------------ // Platform Identifiers // (the imgui_impl_xxxx backend files are setting those up for you) @@ -2684,11 +2677,11 @@ struct ImGuiIO #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS float FontGlobalScale; // Moved io.FontGlobalScale to style.FontScaleMain in 1.92.0 (June 2025) - // [Moved in 1.91.1] Clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. + // Legacy: before 1.91.1, clipboard functions were stored in ImGuiIO instead of ImGuiPlatformIO. // As this is will affect all users of custom engines/backends, we are providing proper legacy redirection (will obsolete). - //const char* (*GetClipboardTextFn)(void* user_data); // --> `platform_io.Platform_GetClipboardTextFn` - //void (*SetClipboardTextFn)(void* user_data, const char* text); // --> `platform_io.Platform_SetClipboardTextFn` - //void* ClipboardUserData; // --> `platform_io.Platform_ClipboardUserData` + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; //void ClearInputCharacters() { InputQueueCharacters.resize(0); } // [Obsoleted in 1.89.8] Clear the current frame text input buffer. Now included within ClearInputKeys(). Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue. #endif @@ -2797,27 +2790,30 @@ struct ImGuiOnceUponAFrame operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; -// Helper: Parse and apply text filters e.g. 'aaa bbb' (all), 'aaa,bbb' (any), '-aaa' (exclude), '"Hello, world"' (exact sequence) -struct ImGuiTextFilterItem; +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" struct ImGuiTextFilter { IMGUI_API ImGuiTextFilter(const char* default_filter = ""); + IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; - IMGUI_API void Build(); // Update internal data when filter changes - inline void Clear() { InputBuf[0] = 0; Build(); } // Clear filter - inline bool IsActive() const { return _Items.Size != 0; } // Useful if you need e.g. an alternative code-path when there are no filters + IMGUI_API void Build(); + void Clear() { InputBuf[0] = 0; Build(); } + bool IsActive() const { return !Filters.empty(); } - // Helper to call InputText() + Build() when buffer is changed. - IMGUI_API bool Draw(const char* label = "Filter"); - IMGUI_API bool DrawWithHint(const char* label = "Filter", const char* hint = "incl -excl"); -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - inline bool Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); return Draw(label); } -#endif + // [Internal] + struct ImGuiTextRange + { + const char* b; + const char* e; - // Members - char InputBuf[256]; // User input buffer - int _CountExclude; // [Internal] >= 0 count of leading exclude - ImVector _Items; // [Internal] Pre-parsed, trimmed, reordered items + ImGuiTextRange() { b = e = NULL; } + ImGuiTextRange(const char* _b, const char* _e) { b = _b; e = _e; } + bool empty() const { return b == e; } + IMGUI_API void split(char separator, ImVector* out) const; + }; + char InputBuf[256]; + ImVectorFilters; + int CountGrep; }; // Helper: Growable text buffer for logging/accumulating text @@ -2897,20 +2893,6 @@ struct ImGuiStorage #endif }; -// [Internal] Used for small stacks. Do not use. -template -struct ImSmallStack_ -{ - T LocalData[Capacity]; // FIXME: should evolve into using heap, e.g union {} with T* HeapData + add SZ_T Capacity. - SZ_T Size = 0; - - inline void clear() { Size = 0; } - inline T& back() { IM_ASSERT(Size > 0); return LocalData[Size - 1]; } - inline void push_back(const T& v) { IM_ASSERT(Size < Capacity); memcpy(&LocalData[Size], &v, sizeof(v)); Size++; } - inline void pop_back() { IM_ASSERT(Size > 0); Size--; } - inline int capacity() const { return Capacity; } -}; - // Flags for ImGuiListClipper (currently not fully exposed in function calls: a future refactor will likely add this to ImGuiListClipper::Begin function equivalent) enum ImGuiListClipperFlags_ { @@ -3224,10 +3206,15 @@ struct ImGuiSelectionExternalStorage }; //----------------------------------------------------------------------------- -// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) +// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData) // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- +// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking. +#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX +#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) +#endif + // ImDrawIdx: vertex index. [Compile-time configurable type] // - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended). // - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file. @@ -3321,83 +3308,42 @@ struct ImDrawListSplitter // Flags for ImDrawList functions enum ImDrawFlags_ { - ImDrawFlags_None = 0, - //ImDrawFlags_Closed = 1, // -> FLAG MOVED BELOW. Prior to 1.92.8 (May 2026): ImDrawFlags_Closed was guaranteed to be == (1<<0) == 1, for legacy compatibility reason. Hardcoded use of 1 or true should be replaced with 'ImDrawFlags_Closed'. + ImDrawFlags_None = 0, - // About usage of flags: - // - "Prim" column: 'OK' = flag can be used to configure an individual AddXXX() call. - // - "Scope" column: 'OK' = initialized by ImGui based on Style options (e.g. whether anti-aliased is enabled) + may be modified using ImDrawList::PushDrawFlag(). - // OK(0)/OK(1) indicates whether this flag is set in the default ImGui Style settings. + // Rounding for AddRect(), AddRectFilled(), PathRect() + // - When not specified, we defaults to ImDrawFlags_RoundCornersAll! So you only need to use those flags if you want another configuration. + ImDrawFlags_RoundCornersTopLeft = 1 << 4, // Round top-left corner only (when rounding > 0.0f, we default to all corners). + ImDrawFlags_RoundCornersTopRight = 1 << 5, // Round top-right corner only (when rounding > 0.0f, we default to all corners). + ImDrawFlags_RoundCornersBottomLeft = 1 << 6, // Round bottom-left corner only (when rounding > 0.0f, we default to all corners). + ImDrawFlags_RoundCornersBottomRight = 1 << 7, // Round bottom-right corner only (when rounding > 0.0f, we default to all corners). + ImDrawFlags_RoundCornersNone = 1 << 8, // Disable rounding even if `float rounding > 0.0f`. This is NOT zero, NOT an implicit flag! + ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, // (Default!!) + ImDrawFlags_RoundCornersDefault_ = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified! + ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight, + ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft, + ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight, + ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone, - // - Rounding default to ImDrawFlags_RoundAll when 'rounding > 0'. - // - So you only need to use the ImDrawFlags_RoundXXX flags if you want a special configuration (e.g. a rectangle with one rounded corner). - // Rounding for AddRectXXX(), PathRect() ------ // Prim/Scope? - ImDrawFlags_RoundTopLeft = 1 << 4, // OK -- // Round top-left corner only (when 'rounding > 0.0f', we default to all corners). - ImDrawFlags_RoundTopRight = 1 << 5, // OK -- // Round top-right corner only (when 'rounding > 0.0f', we default to all corners). - ImDrawFlags_RoundBottomLeft = 1 << 6, // OK -- // Round bottom-left corner only (when 'rounding > 0.0f', we default to all corners). - ImDrawFlags_RoundBottomRight = 1 << 7, // OK -- // Round bottom-right corner only (when 'rounding > 0.0f', we default to all corners). - ImDrawFlags_RoundNone = 1 << 8, // OK -- // Disable rounding even when 'rounding > 0.0f'. This value is NOT zero, it is NOT an implicit flag! - ImDrawFlags_RoundAll = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundTopRight | ImDrawFlags_RoundBottomLeft | ImDrawFlags_RoundBottomRight, // (Default!!) - ImDrawFlags_RoundTop = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundTopRight, - ImDrawFlags_RoundBottom = ImDrawFlags_RoundBottomLeft | ImDrawFlags_RoundBottomRight, - ImDrawFlags_RoundLeft = ImDrawFlags_RoundBottomLeft | ImDrawFlags_RoundTopLeft, - ImDrawFlags_RoundRight = ImDrawFlags_RoundBottomRight | ImDrawFlags_RoundTopRight, + // Stroke options + ImDrawFlags_Closed = 1 << 9, // PathStroke(), AddPolyline(): specify that shape should be closed. + //ImDrawFlags_Closed = 1, // Prior to 1.92.8 (May 2026), ImDrawFlags_Closed was guaranteed to be == 1<<0 == 1 for legacy compatibility reason. Hardcoded use of 1 or true should be replaced. - // Stroke Options ----------------------------- // Prim/Scope? - ImDrawFlags_Closed = 1 << 9, // OK -- // PathStroke(), AddPolyline(): specify that shape should be closed. - ImDrawFlags_JoinMiter = 1 << 10, // OK -- // PathStroke(), AddPolyline(): use miter joins/corners only. This assumes that the input polyline does not have corners sharper than 90 degrees. Slightly faster. - ImDrawFlags_CapSquare = 1 << 11, // OK -- // PathStroke(), AddPolyline(): use square cap line ends. + ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // == 0x8000000F, - // About Stroke Ends: - // - Rendering is optimized for fast pixel-perfect UI, so line ends are not anti-aliased by default. It's cheaper (we can emit less vertices). - // - For more free-form drawings, light graphs and markers, or when using thick strokes: you can turn them on using the ImDrawFlags_AALineEnds flag. - // - See 'Demo->Examples->Custom Rendering' to interactively toy with those flags. - // - 'OK*' indicates using this at the AddXXX() call site is unlikely: it would only makes sense if (1) the option is disabled in style/scope and (2) you want to forcefully enable it for a single primitives. Possible but unlikely! Only supported for functions taking flags inputs. - // Stroke/Fill Anti-aliasing ------------------ // Prim/Scope? - ImDrawFlags_AAFill = 1 << 12, // OK* OK(1) // Enable anti-aliasing for Filled shapes. - ImDrawFlags_AALines = 1 << 13, // OK* OK(1) // Enable anti-aliasing for Strokes (lines, borders). - ImDrawFlags_AALineEnds = 1 << 14, // OK OK(0) // Enable anti-aliasing for Strokes Ends. Requires AALines to also be enabled. Useful on thick strokes or for precise continuity of multiple lines. A little more costly. - //ImDrawFlags_NoAA = 1 << 15, // OK -- // Disable anti-aliasing for a given primitive. - //ImDrawFlags_NoAALineEnds = 1 << 16, // OK -- // Disable anti-aliasing ends for a given primitive. + ImDrawFlags_ShadowCutOutShapeBackground = 1 << 20, // Do not render the shadow shape under the objects to be shadowed to save on fill-rate or facilitate blending. Slower on CPU. +}; - // About Stroke Position: - // - Read https://github.com/ocornut/imgui/wiki/Draw-List (this guide includes a precise list of differences between 1.92.9 and 1.93.0) - // - Read https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering - // Stroke Position relative to shape outline -- // Prim/Scope? - ImDrawFlags_StrokeInside = 1 << 17, // OK -- // Draw stroke inside of the shape outline (default for closed shapes and AddLineH, AddLineV functions) - ImDrawFlags_StrokeCenter = 2 << 17, // OK -- // Draw stroke at the center of the shape outline (default for paths, bezier, and AddLine functions) - ImDrawFlags_StrokeCenterBiased = 3 << 17, // OK -- // Draw stroke at the center of the shape outline, so that half thickness rounded down will be outside, and the rest inside the shape outline. Useful for axis-aligned shapes: AddLineH, AddLineV, AddRect. Does not animate well! - ImDrawFlags_StrokeOutside = 4 << 17, // OK -- // Draw stroke outside of the shape outline - ImDrawFlags_StrokeLegacy = 7 << 17, // OK OK(0) // Use legacy positioning + enable JoinMiter + disable AALineEnds. Must be all bits set. - - // Other Options ------------------------------ // Prim/Scope? - ImDrawFlags_TextNoPixelSnap = 1 << 20, // OK OK(0) // Disable automatically snapping AddText() calls to pixel boundaries. - ImDrawFlags_UseTexForRoundCorners = 1 << 21, // -- OK(1) // Enable using textures instead of strokes to draw rounded corners/circles where possible (faster). Used by default unless 'ImFontAtlasFlags_NoBakedRoundCorners' is enabled in the font atlas. - ImDrawFlags_UseVtxOffset = 1 << 22, // -- OK(1) // Can emit 'VtxOffset > 0' to allow large meshes with 16-bit ImDrawIdx. Used by default when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled by the backend. - ImDrawFlags_AllowTexForRoundCorners_= 1 << 23, // -- OK(1) // [Internal] - - // [Internal] - ImDrawFlags_RoundMask_ = ImDrawFlags_RoundAll | ImDrawFlags_RoundNone, // [Internal] - ImDrawFlags_AllowInPushScope_ = ImDrawFlags_AAFill | ImDrawFlags_AALines | ImDrawFlags_AALineEnds | ImDrawFlags_StrokeLegacy | ImDrawFlags_TextNoPixelSnap | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_UseVtxOffset | ImDrawFlags_RoundMask_, // [Internal] Values allowed in PushDrawFlag() scope. - ImDrawFlags_AllowInFrameScope_ = ImDrawFlags_AllowInPushScope_ | ImDrawFlags_AllowTexForRoundCorners_, - ImDrawFlags_StrokeMask_ = 0x07 << 17, // [Internal] - ImDrawFlags_InvalidMask_ = ~0x7FFFFFF0, // [Internal] == 0x8000000F. Reserved to detect misuses. - - // Obsolete names -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - // RENAMED in 1.93.0 (Oct 2026): ImDrawFlags_RoundCornersXXXX -> ImDrawFlags_RoundXXXX. - ImDrawFlags_RoundCornersTopLeft = ImDrawFlags_RoundTopLeft, - ImDrawFlags_RoundCornersTopRight = ImDrawFlags_RoundTopRight, - ImDrawFlags_RoundCornersBottomLeft = ImDrawFlags_RoundBottomLeft, - ImDrawFlags_RoundCornersBottomRight = ImDrawFlags_RoundBottomRight, - ImDrawFlags_RoundCornersNone = ImDrawFlags_RoundNone, - ImDrawFlags_RoundCornersAll = ImDrawFlags_RoundAll, - ImDrawFlags_RoundCornersTop = ImDrawFlags_RoundTop, - ImDrawFlags_RoundCornersBottom = ImDrawFlags_RoundBottom, - ImDrawFlags_RoundCornersLeft = ImDrawFlags_RoundLeft, - ImDrawFlags_RoundCornersRight = ImDrawFlags_RoundRight, - ImDrawFlags_RoundCornersMask_ = ImDrawFlags_RoundMask_, -#endif +// Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly. +// It is however possible to temporarily alter flags between calls to ImDrawList:: functions. +enum ImDrawListFlags_ +{ + ImDrawListFlags_None = 0, + ImDrawListFlags_AntiAliasedLines = 1 << 0, // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles) + ImDrawListFlags_AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering (NOT point/nearest filtering). + ImDrawListFlags_AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles). + ImDrawListFlags_AllowVtxOffset = 1 << 3, // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled. + ImDrawListFlags_TextNoPixelSnap = 1 << 4, // Disable automatically snapping AddText() calls to pixel boundaries. }; // Draw command list @@ -3415,7 +3361,7 @@ struct ImDrawList ImVector CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector VtxBuffer; // Vertex buffer. - ImDrawFlags Flags; // Current flags for drawing primitives. Alter with PushDrawFlag()/PopDrawFlags() to adjust defaults to a given scope. + ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. // [Internal, used while building lists] unsigned int _VtxCurrentIdx; // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. @@ -3428,10 +3374,8 @@ struct ImDrawList ImVector _ClipRectStack; // [Internal] ImVector _TextureStack; // [Internal] ImVector _CallbacksDataBuf; // [Internal] - ImSmallStack_ _DrawFlagsStack;// [Internal] - float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content + float _FringeScale; // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content. float _InvFringeScale; // [internal] 1.0 / _FringeScale // FIXME: Consider renaming to _PixelDensity. - bool _FringeScaleIsInteger; // [Internal] true if 1/_FringeScale is a whole number, used to select fast path for rendering const char* _OwnerName; // Pointer to owner window's name for debugging // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData(). @@ -3444,8 +3388,6 @@ struct ImDrawList IMGUI_API void PopClipRect(); IMGUI_API void PushTexture(ImTextureRef tex_ref); IMGUI_API void PopTexture(); - IMGUI_API void PushDrawFlag(ImDrawFlags flags, bool enabled); // [BETA] Please notify me if you are using this. - IMGUI_API void PopDrawFlag(); inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } @@ -3456,32 +3398,32 @@ struct ImDrawList // In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12. // In future versions we will use textures to provide cheaper and higher-quality circles. // Use AddNgon() and AddNgonFilled() functions if you need to guarantee a specific number of sides. - IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); - IMGUI_API void AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); - IMGUI_API void AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); + IMGUI_API void AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness = 1.0f); IMGUI_API void AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, float thickness = 1.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) IMGUI_API void AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0); // a: upper-left, b: lower-right (== upper-left + size) IMGUI_API void AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); - IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); + IMGUI_API void AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f); IMGUI_API void AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col); - IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0); + IMGUI_API void AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f, ImDrawFlags flags = 0); + IMGUI_API void AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f); IMGUI_API void AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0); - IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f, ImDrawFlags flags = 0); + IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f); IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments); - IMGUI_API void AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f, ImDrawFlags flags = 0); + IMGUI_API void AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0, float thickness = 1.0f); IMGUI_API void AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot = 0.0f, int num_segments = 0); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); - IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0, ImDrawFlags flags = 0); // Cubic Bezier (4 control points) - IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0, ImDrawFlags flags = 0); // Quadratic Bezier (3 control points) + IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points) + IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points) // General polygon // - Only simple polygons are supported by filling functions (no self-intersections, no holes). // - Concave polygon fill is more expensive than convex one: it has O(N^2) complexity. Provided as a convenience for the user but not used by the main library. - inline void AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0) { _AddPolyline(points, num_points, col, thickness, flags, FLT_MAX); } - IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags = 0); + IMGUI_API void AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags = 0); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); IMGUI_API void AddConcavePolyFilled(const ImVec2* points, int num_points, ImU32 col); // Image primitives @@ -3492,15 +3434,32 @@ struct ImDrawList IMGUI_API void AddImageQuad(ImTextureRef tex_ref, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE); IMGUI_API void AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0); + // Shadows primitives + // [BETA] API + // - Add shadow for a object, with min/max or center/radius describing the object extents, and offset shifting the shadow. + // - Rounding parameters refer to the object itself, not the shadow! + // - By default, the area under the object is filled, because this is simpler to process. + // Using the ImDrawFlags_ShadowCutOutShapeBackground flag makes the function not render this area and leave a hole under the object. + // - Shadows w/ fill under the object: a bit faster for CPU, more pixels rendered, visible/darkening if used behind a transparent shape. + // Typically used by: small, frequent objects, opaque objects, transparent objects if shadow darkening isn't an issue. + // - Shadows w/ hole under the object: a bit slower for CPU, less pixels rendered, no difference if used behind a transparent shape. + // Typically used by: large, infrequent objects, transparent objects if exact blending/color matter. + // - FIXME-SHADOWS: 'offset' + ImDrawFlags_ShadowCutOutShapeBackground are not currently supported together with AddShadowCircle(), AddShadowConvexPoly(), AddShadowNGon(). + #define IMGUI_HAS_SHADOWS 1 + IMGUI_API void AddShadowRect(const ImVec2& obj_min, const ImVec2& obj_max, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags = 0, float obj_rounding = 0.0f); + IMGUI_API void AddShadowCircle(const ImVec2& obj_center, float obj_radius, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags = 0, int obj_num_segments = 12); + IMGUI_API void AddShadowConvexPoly(const ImVec2* points, int points_count, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags = 0); + IMGUI_API void AddShadowNGon(const ImVec2& obj_center, float obj_radius, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags, int obj_num_segments); + // Stateful path API, add points then finish with PathFillConvex() or PathStroke() // - Important: filled shapes must always use clockwise winding order! The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. // so e.g. 'PathArcTo(center, radius, PI * -0.5f, PI)' is ok, whereas 'PathArcTo(center, radius, PI, PI * -0.5f)' won't have correct anti-aliasing when followed by PathFillConvex(). inline void PathClear() { _Path.Size = 0; } inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); } - inline void PathFillConvex(ImU32 col, ImDrawFlags flags = 0) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, flags); _Path.Size = 0; } + inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } inline void PathFillConcave(ImU32 col) { AddConcavePolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; } - inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0) { _AddPolyline(_Path.Data, _Path.Size, col, thickness, flags, FLT_MAX); _Path.Size = 0; } + inline void PathStroke(ImU32 col, float thickness = 1.0f, ImDrawFlags flags = 0) { AddPolyline(_Path.Data, _Path.Size, col, thickness, flags); _Path.Size = 0; } IMGUI_API void PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0); IMGUI_API void PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathEllipticalArcTo(const ImVec2& center, const ImVec2& radius, float rot, float a_min, float a_max, int num_segments = 0); // Ellipse @@ -3578,13 +3537,6 @@ struct ImDrawList IMGUI_API int _CalcCircleAutoSegmentCount(float radius) const; IMGUI_API void _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step); IMGUI_API void _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments); - IMGUI_API void _AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, const ImVec4& tex_uvs, ImDrawFlags flags); - IMGUI_API void _AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, const ImVec4& tex_uvs, ImDrawFlags flags); - IMGUI_API void _AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags); - IMGUI_API void _AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags); - IMGUI_API void _SelectLineTexture(float screen_thickness, ImVec2* out_uv0, ImVec2* out_uv1, float* out_fringe, ImDrawFlags flags); - IMGUI_API float _CalculateCenterBiasedOffset(float thickness); - IMGUI_API void _AddPolyline(const ImVec2* points, int num_points, ImU32 col, float thickness, ImDrawFlags flags, float max_inner_offset); }; // All draw data to render a Dear ImGui frame @@ -3604,7 +3556,7 @@ struct ImDrawData ImVector* Textures; // List of textures to update. Most of the times the list is shared by all ImDrawData, has only 1 texture and it doesn't need any update. This almost always points to ImGui::GetPlatformIO().Textures[]. May be overridden or set to NULL if you want to manually update textures. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - int CmdListsCount; // [OBSOLETED in 1.92.9] Use CmdLists.Size instead. Number of ImDrawList* to render. + int CmdListsCount; // Use CmdLists.Size instead. Number of ImDrawList* to render. #endif // Functions @@ -3704,6 +3656,24 @@ struct ImTextureData // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont) //----------------------------------------------------------------------------- +// [Internal] Shadow texture baking config +struct ImFontAtlasShadowTexConfig +{ + int TexCornerSize; // Size of the corner areas. + int TexEdgeSize; // Size of the edge areas (and by extension the center). Changing this is normally unnecessary. + float TexFalloffPower; // The power factor for the shadow falloff curve. + float TexDistanceFieldOffset; // How much to offset the distance field by (allows over/under-shadowing, potentially useful for accommodating rounded corners on the "casting" shape). + bool TexBlur; // Do we want to Gaussian blur the shadow texture? + + inline ImFontAtlasShadowTexConfig() { memset(this, 0, sizeof(*this)); } + IMGUI_API void SetupDefaults(); + int GetRectTexPadding() const { return 2; } // Number of pixels of padding to add to the rectangular texture to avoid sampling artifacts at the edges. + int CalcRectTexSize() const { return TexCornerSize + TexEdgeSize + GetRectTexPadding(); } // The size of the texture area required for the actual 2x2 rectangle shadow texture (after the redundant corners have been removed). Padding is required here to avoid sampling artifacts at the edge adjoining the removed corners. int CalcConvexTexWidth() const; // The width of the texture area required for the convex shape shadow texture. + int GetConvexTexPadding() const { return 8; } // Number of pixels of padding to add to the convex shape texture to avoid sampling artifacts at the edges. This also acts as padding for the expanded corner triangles. + int CalcConvexTexWidth() const; // The width of the texture area required for the convex shape shadow texture. + int CalcConvexTexHeight() const; // The height of the texture area required for the convex shape shadow texture. +}; + // A font input/source (we may rename this to ImFontSource in the future) struct ImFontConfig { @@ -3801,8 +3771,7 @@ enum ImFontAtlasFlags_ ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas (save a little texture memory) - ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build anti-aliased line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENTS ANTI-ALIASED LINES FROM WORKING AND WILL DISABLE THEM. - ImFontAtlasFlags_NoBakedRoundCorners= 1 << 3, // Don't build round corners into the atlas. + ImFontAtlasFlags_NoBakedLines = 1 << 2, // Don't build thick line textures into the atlas (save a little texture memory, allow support for point/nearest filtering). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU). }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: @@ -3919,7 +3888,7 @@ struct ImFontAtlas // Input ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) ImTextureFormat TexDesiredFormat; // Desired texture format (default to ImTextureFormat_RGBA32 but may be changed to ImTextureFormat_Alpha8). - int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method never relies on bilinear filtering you may set this to 0. + int TexGlyphPadding; // FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0 (will also need to set AntiAliasedLinesUseTex = false). int TexMinWidth; // Minimum desired texture width. Must be a power of two. Default to 512. int TexMinHeight; // Minimum desired texture height. Must be a power of two. Default to 128. int TexMaxWidth; // Maximum desired texture width. Must be a power of two. Default to 8192. @@ -3946,6 +3915,7 @@ struct ImFontAtlas ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel. May change as new texture gets created. ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector Sources; // Source/configuration data + ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1]; // UVs for baked anti-aliased lines int TexNextUniqueID; // Next value to be stored in TexData->UniqueID int FontNextUniqueID; // Next value to be stored in ImFont->FontID ImVector DrawListSharedDatas; // List of users for this atlas. Typically one per Dear ImGui context. @@ -3957,6 +3927,11 @@ struct ImFontAtlas int RefCount; // Number of contexts using this atlas ImGuiContext* OwnerContext; // Context which own the atlas will be in charge of updating and destroying it. + // [Internal] Shadow data + ImFontAtlasRectId ShadowRectIds[2]; // IDs of rect for shadow textures + ImVec4 ShadowRectUvs[10]; // UV coordinates for shadow textures, 9 for the rectangle shadows and the final entry for the convex shape shadows + ImFontAtlasShadowTexConfig ShadowTexConfig; // Shadow texture baking config + // [Obsolete] #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Legacy: You can request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. --> Prefer using a custom ImFontLoader. @@ -4042,7 +4017,7 @@ struct ImFont ImWchar FallbackChar; // 2-4 // out // Character used if a glyph isn't found (U+FFFD, '?') ImU8 Used8kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/8192/8]; // 1 bytes if ImWchar=ImWchar16, 17 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 8K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints. bool EllipsisAutoBake; // 1 // // Mark when the "..." glyph (== EllipsisChar) needs to be generated by combining multiple '.'. - ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapCodepointXXX(). + ImGuiStorage RemapPairs; // 16 // // Remapping pairs when using AddRemapChar(), otherwise empty. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS float Scale; // 4 // in // Legacy base font scale (~1.0f), multiplied by the per-window font scale which you can adjust with SetWindowFontScale() #endif @@ -4068,10 +4043,8 @@ struct ImFont // [Internal] Don't use! IMGUI_API void ClearOutputData(); - IMGUI_API void AddRemapCodepoint(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. - IMGUI_API void AddRemapCodepointToGlyphIndex(ImWchar from_codepoint, int font_src_idx, int glyph_idx); + IMGUI_API void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint); // Makes 'from_codepoint' character points to 'to_codepoint' glyph. IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last); - //inline void AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) { AddRemapCodepoint(from_codepoint, to_codepoint); } // Renamed in 1.93.0 (Sep 2026) }; // This is provided for consistency (but we don't actually use this) @@ -4236,17 +4209,16 @@ namespace ImGui // OBSOLETED in 1.91.9 (from February 2025) IMGUI_API void Image(ImTextureRef tex_ref, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col); // <-- 'border_col' was removed in favor of ImGuiCol_ImageBorder. If you use 'tint_col', use ImageWithBg() instead. // OBSOLETED in 1.91.0 (from July 2024) + inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } + inline void PopButtonRepeat() { PopItemFlag(); } + inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } + inline void PopTabStop() { PopItemFlag(); } // You do not need those functions! See #7838 on GitHub for more info. IMGUI_API ImVec2 GetContentRegionMax(); // Content boundaries max (e.g. window boundaries including scrolling, or current column boundaries). You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMin(); // Content boundaries min for the window (roughly (0,0)-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! IMGUI_API ImVec2 GetWindowContentRegionMax(); // Content boundaries max for the window (roughly (0,0)+Size-Scroll), in window-local coordinates. You should never need this. Always use GetCursorScreenPos() and GetContentRegionAvail()! // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) - // OBSOLETED in 1.91.0 (from July 2024) - //inline void PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } - //inline void PopButtonRepeat() { PopItemFlag(); } - //inline void PushTabStop(bool tab_stop) { PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop); } - //inline void PopTabStop() { PopItemFlag(); } // OBSOLETED in 1.90.0 (from September 2023) //IMGUI_API bool Combo(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int popup_max_height_in_items = -1); // Getter signature changed. See 2023/09/15 and 2026/02/27 commits. //IMGUI_API bool ListBox(const char* label, int* current_item, bool (*old_callback)(void* user_data, int idx, const char** out_text), void* user_data, int items_count, int height_in_items = -1); // Getter signature changed. See 2023/09/15 and 2026/02/27 commits. @@ -4324,18 +4296,6 @@ namespace ImGui #define ImDrawCallback_ResetRenderState (ImDrawCallback)(-8) // OBSOLETED in 1.92.8: Use ImGui::GetPlatformIO().DrawCallback_ResetRenderState -// -- RENAMED in 1.93.0: Merged ImDrawListFlags into ImDrawFlags. -typedef ImDrawFlags ImDrawListFlags; -enum ImDrawListFlags_ -{ - ImDrawListFlags_None = ImDrawFlags_None, - ImDrawListFlags_AntiAliasedFill = ImDrawFlags_AAFill, - ImDrawListFlags_AntiAliasedLines = ImDrawFlags_AALines, - ImDrawListFlags_AntiAliasedLinesUseTex = ImDrawFlags_AALines, // No effect, anti-aliased rendering always uses textures from 1.93+ - ImDrawListFlags_AllowVtxOffset = ImDrawFlags_UseVtxOffset, - ImDrawListFlags_TextNoPixelSnap = ImDrawFlags_TextNoPixelSnap, -}; - //-- OBSOLETED in 1.92.0: ImFontAtlasCustomRect becomes ImTextureRect // - ImFontAtlasCustomRect::X,Y --> ImTextureRect::x,y // - ImFontAtlasCustomRect::Width,Height --> ImTextureRect::w,h @@ -4359,16 +4319,16 @@ typedef ImFontAtlasRect ImFontAtlasCustomRect; //typedef ImDrawFlags ImDrawCornerFlags; //enum ImDrawCornerFlags_ //{ -// ImDrawCornerFlags_None = ImDrawFlags_RoundNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundNone which is != 0 and not implicit -// ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). -// ImDrawCornerFlags_TopRight = ImDrawFlags_RoundTopRight, // Was == 0x02 (1 << 1) prior to 1.82. -// ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. -// ImDrawCornerFlags_BotRight = ImDrawFlags_RoundBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. -// ImDrawCornerFlags_All = ImDrawFlags_RoundAll, // Was == 0x0F prior to 1.82 -// ImDrawCornerFlags_Top = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundTopRight, -// ImDrawCornerFlags_Bot = ImDrawFlags_RoundBottomLeft | ImDrawFlags_RoundBottomRight, -// ImDrawCornerFlags_Left = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundBottomLeft, -// ImDrawCornerFlags_Right = ImDrawFlags_RoundTopRight | ImDrawFlags_RoundBottomRight, +// ImDrawCornerFlags_None = ImDrawFlags_RoundCornersNone, // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit +// ImDrawCornerFlags_TopLeft = ImDrawFlags_RoundCornersTopLeft, // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally). +// ImDrawCornerFlags_TopRight = ImDrawFlags_RoundCornersTopRight, // Was == 0x02 (1 << 1) prior to 1.82. +// ImDrawCornerFlags_BotLeft = ImDrawFlags_RoundCornersBottomLeft, // Was == 0x04 (1 << 2) prior to 1.82. +// ImDrawCornerFlags_BotRight = ImDrawFlags_RoundCornersBottomRight, // Was == 0x08 (1 << 3) prior to 1.82. +// ImDrawCornerFlags_All = ImDrawFlags_RoundCornersAll, // Was == 0x0F prior to 1.82 +// ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, +// ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, +// ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, +// ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, //}; // RENAMED and MERGED both ImGuiKey_ModXXX and ImGuiModFlags_XXX into ImGuiMod_XXX (from September 2022) diff --git a/imgui_demo.cpp b/imgui_demo.cpp index 8d27c9f3f..7aeff1fbe 100644 --- a/imgui_demo.cpp +++ b/imgui_demo.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.1 WIP +// dear imgui, v1.93.0 WIP // (demo code) // Help: @@ -576,8 +576,6 @@ void ImGui::ShowDemoWindow(bool* p_open) ImGui::SameLine(); HelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running."); ImGui::Checkbox("io.ConfigDebugIgnoreFocusLoss", &io.ConfigDebugIgnoreFocusLoss); ImGui::SameLine(); HelpMarker("Option to deactivate io.AddFocusEvent(false) handling. May facilitate interactions with a debugger when focus loss leads to clearing inputs data."); - ImGui::Checkbox("io.ConfigDebugDrawListDefaultsToStrokeLegacy", &io.ConfigDebugDrawListDefaultsToStrokeLegacy); - ImGui::SameLine(); HelpMarker("Option to default all ImDrawList to ImDrawFlags_StrokeLegacy mode, mimicking pre-1.93.0 rendering."); ImGui::Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings); ImGui::SameLine(); HelpMarker("Option to save .ini data with extra comments (particularly helpful for Docking, but makes saving slower)."); @@ -965,9 +963,8 @@ static void DemoWindowWidgetsBasic() ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f)); - ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); ImGui::Button("Click"); - ImGui::PopStyleColor(4); + ImGui::PopStyleColor(3); ImGui::PopID(); } @@ -1262,7 +1259,6 @@ static void DemoWindowWidgetsColorAndPickers() ImGui::OpenPopup("mypicker"); backup_color = color; } - float ref_sz = ImGui::GetFrameHeight(); if (ImGui::BeginPopup("mypicker")) { ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!"); @@ -1270,12 +1266,11 @@ static void DemoWindowWidgetsColorAndPickers() ImGui::ColorPicker4("##picker", (float*)&color, base_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview); ImGui::SameLine(); - ImVec2 color_button_sz(ref_sz * 3.0f, ref_sz * 2.0f); ImGui::BeginGroup(); // Lock X position ImGui::Text("Current"); - ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, color_button_sz); + ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)); ImGui::Text("Previous"); - if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, color_button_sz)) + if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40))) color = backup_color; ImGui::Separator(); ImGui::Text("Palette"); @@ -1286,7 +1281,7 @@ static void DemoWindowWidgetsColorAndPickers() ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y); ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip; - if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags)) + if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20))) color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha! // Allow user to drop colors into each palette entry. Note that ColorButton() is already a @@ -1309,9 +1304,8 @@ static void DemoWindowWidgetsColorAndPickers() IMGUI_DEMO_MARKER("Widgets/Color/ColorButton (simple)"); ImGui::Text("Color button only:"); static bool no_border = false; - const ImVec2 color_button_sz(ref_sz * 2.0f, ref_sz * 2.0f); ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border); - ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, base_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), color_button_sz); + ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, base_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80)); IMGUI_DEMO_MARKER("Widgets/Color/ColorPicker"); ImGui::SeparatorText("Color picker"); @@ -1458,8 +1452,7 @@ static void DemoWindowWidgetsComboBoxes() filter.Clear(); } ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F); - ImGui::SetNextItemWidth(-FLT_MIN); - filter.DrawWithHint("##Filter", "Filter (incl -excl)"); + filter.Draw("##Filter", -FLT_MIN); for (int n = 0; n < IM_COUNTOF(items); n++) { @@ -1651,10 +1644,10 @@ static void DemoWindowWidgetsDragAndDrop() { if (ImGui::TreeNode("Drag and Drop")) { - IMGUI_DEMO_MARKER("Widgets/Drag and Drop"); + IMGUI_DEMO_MARKER("Widgets/Drag and drop"); if (ImGui::TreeNode("Drag and drop in standard widgets")) { - IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Standard widgets"); + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Standard widgets"); // ColorEdit widgets automatically act as drag source and drag target. // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F // to allow your own widgets to use colors in their drag and drop interaction. @@ -1669,7 +1662,7 @@ static void DemoWindowWidgetsDragAndDrop() if (ImGui::TreeNode("Drag and drop to copy/swap items")) { - IMGUI_DEMO_MARKER("Widgets/Drag and Drop/Copy-swap items"); + IMGUI_DEMO_MARKER("Widgets/Drag and drop/Copy-swap items"); enum Mode { Mode_Copy, @@ -1686,13 +1679,12 @@ static void DemoWindowWidgetsDragAndDrop() "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }; - float sz = ImGui::GetFrameHeight() * 3.0f; for (int n = 0; n < IM_COUNTOF(names); n++) { ImGui::PushID(n); if ((n % 3) != 0) ImGui::SameLine(); - ImGui::Button(names[n], ImVec2(sz, sz)); + ImGui::Button(names[n], ImVec2(60, 60)); // Our buttons are both drag sources and drag targets here! if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) @@ -1842,7 +1834,6 @@ static void DemoWindowWidgetsDragsAndSliders() //ImGui::DragFloat("DragFloat (0 -> 0)", &drag_f, 0.005f, 0.0f, 0.0f, "%.3f", flags); // To test ClampZeroRange //ImGui::DragFloat("DragFloat (100 -> 100)", &drag_f, 0.005f, 100.0f, 100.0f, "%.3f", flags); ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags); - ImGui::DragFloat("DragFloat (0 -> 100)", &drag_f, 0.2f, 0, 100, "%.2f", flags); ImGui::DragFloat4("DragFloat4 (0 -> 1)", drag_f4, 0.005f, 0.0f, 1.0f, "%.3f", flags); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. // Sliders @@ -1853,7 +1844,7 @@ static void DemoWindowWidgetsDragsAndSliders() ImGui::Text("Underlying float value: %f", slider_f); ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags_for_sliders); ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags_for_sliders); - ImGui::SliderFloat4("SliderFloat4 (0 -> 1)", slider_f4, 0.0f, 1.0f, "%.3f", flags_for_sliders); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. + ImGui::SliderFloat4("SliderFloat4 (0 -> 1)", slider_f4, 0.0f, 1.0f, "%.3f", flags); // Multi-component item, mostly here to document the effect of ImGuiSliderFlags_ColorMarkers. ImGui::TreePop(); } @@ -2068,7 +2059,6 @@ static void DemoWindowWidgetsMixedValues() { if (ImGui::TreeNode("Mixed Values")) { - IMGUI_DEMO_MARKER("Widgets/Mixed Values"); // This is designed for advanced property editors which are generally reusable and data-driven. HelpMarker("Using ImGuiItemFlags_MixedValue."); @@ -2189,12 +2179,10 @@ static void DemoWindowWidgetsPlotting() static bool animate = true; ImGui::Checkbox("Animate", &animate); - ImVec2 plot_sz(0.0f, ImGui::GetFrameHeight() * 4.0f); - // Plot as lines and plot as histogram static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; ImGui::PlotLines("Frame Times", arr, IM_COUNTOF(arr)); - ImGui::PlotHistogram("Histogram", arr, IM_COUNTOF(arr), 0, NULL, 0.0f, 1.0f, plot_sz); + ImGui::PlotHistogram("Histogram", arr, IM_COUNTOF(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f)); //ImGui::SameLine(); HelpMarker("Consider using ImPlot instead!"); // Fill an array of contiguous float values to plot @@ -2223,7 +2211,7 @@ static void DemoWindowWidgetsPlotting() average /= (float)IM_COUNTOF(values); char overlay[32]; sprintf(overlay, "avg %f", average); - ImGui::PlotLines("Lines", values, IM_COUNTOF(values), values_offset, overlay, -1.0f, 1.0f, plot_sz); + ImGui::PlotLines("Lines", values, IM_COUNTOF(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f)); } // Use functions to generate output @@ -2241,8 +2229,8 @@ static void DemoWindowWidgetsPlotting() ImGui::SameLine(); ImGui::SliderInt("Sample count", &display_count, 1, 400); float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; - ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, plot_sz); - ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, plot_sz); + ImGui::PlotLines("Lines##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); + ImGui::PlotHistogram("Histogram##2", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80)); ImGui::TreePop(); } @@ -3954,24 +3942,14 @@ static void DemoWindowWidgetsTextFilter() static ImGuiTextFilter filter; ImGui::Text("Filter usage:\n" " \"\" display all lines\n" - " xxx display lines containing \"xxx\"\n" - " xxx yyy display lines containing \"xxx\" and \"yyy\"\n" - " \"xxx yyy\" display lines containing \"xxx yyy\"\n" - " xxx,yyy display lines containing \"xxx\" or \"yyy\"\n" - " -xxx hide lines containing \"xxx\""); - ImGui::SetNextItemWidth(-FLT_MIN); - filter.DrawWithHint("##Filter", "Filter (incl -excl)"); - if (ImGui::BeginChild("##items", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 15), ImGuiChildFlags_FrameStyle)) - { - const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; - for (const char* item : lines) - if (filter.PassFilter(item)) - ImGui::TextUnformatted(item); - for (const char* item : ExampleNames) - if (filter.PassFilter(item)) - ImGui::TextUnformatted(item); - } - ImGui::EndChild(); + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + filter.Draw(); + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (int i = 0; i < IM_COUNTOF(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); ImGui::TreePop(); } } @@ -4431,7 +4409,6 @@ static void DemoWindowWidgetsTreeNodes() ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Framed", &base_flags, ImGuiTreeNodeFlags_Framed); ImGui::SameLine(); HelpMarker("Draw frame with background (e.g. for CollapsingHeader)"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_FramePadding", &base_flags, ImGuiTreeNodeFlags_FramePadding); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_NavLeftJumpsToParent", &base_flags, ImGuiTreeNodeFlags_NavLeftJumpsToParent); - ImGui::CheckboxFlags("ImGuiTreeNodeFlags_Bullet", &base_flags, ImGuiTreeNodeFlags_Bullet); HelpMarker("Default option for DrawLinesXXX is stored in style.TreeLinesFlags"); ImGui::CheckboxFlags("ImGuiTreeNodeFlags_DrawLinesNone", &base_flags, ImGuiTreeNodeFlags_DrawLinesNone); @@ -4502,34 +4479,27 @@ static void DemoWindowWidgetsVerticalSliders() if (ImGui::TreeNode("Vertical Sliders")) { IMGUI_DEMO_MARKER("Widgets/Vertical Sliders"); - - ImGuiStyle& style = ImGui::GetStyle(); - ImVec2 slider_sz(ImGui::GetFrameHeight(), ImGui::GetFrameHeight() * 9); - - ImGui::PushStyleVarX(ImGuiStyleVar_ItemSpacing, (float)(int)(style.ItemSpacing.x * 0.5f)); - ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, (float)(int)(slider_sz.x * 0.25f)); - ImGui::PushStyleVar(ImGuiStyleVar_GrabRounding, (float)(int)(slider_sz.x * 0.25f)); - float spacing = style.ItemSpacing.x; + const float spacing = 4; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); static int int_value = 0; - ImGui::VSliderInt("##int", slider_sz, &int_value, 0, 5); + ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5); ImGui::SameLine(); static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; ImGui::PushID("set1"); for (int i = 0; i < 7; i++) { - if (i > 0)ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.7f)); - ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); - ImGui::VSliderFloat("##v", slider_sz, &values[i], 0.0f, 1.0f, ""); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values[i]); - ImGui::PopStyleColor(5); + ImGui::PopStyleColor(4); ImGui::PopID(); } ImGui::PopID(); @@ -4538,15 +4508,15 @@ static void DemoWindowWidgetsVerticalSliders() ImGui::PushID("set2"); static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; const int rows = 3; - const ImVec2 slider_size_small(slider_sz.x, (float)(int)((slider_sz.y - (rows - 1) * spacing) / rows)); + const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows)); for (int nx = 0; nx < 4; nx++) { - if (nx > 0)ImGui::SameLine(); + if (nx > 0) ImGui::SameLine(); ImGui::BeginGroup(); for (int ny = 0; ny < rows; ny++) { ImGui::PushID(nx * rows + ny); - ImGui::VSliderFloat("##v", slider_size_small, &values2[nx], 0.0f, 1.0f, ""); + ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values2[nx]); ImGui::PopID(); @@ -4559,17 +4529,15 @@ static void DemoWindowWidgetsVerticalSliders() ImGui::PushID("set3"); for (int i = 0; i < 4; i++) { - if (i > 0) - ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); ImGui::PushID(i); - ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, slider_sz.y * 0.25f); - ImGui::VSliderFloat("##v", ImVec2(slider_sz.x * 2.0f, slider_sz.y), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); + ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); ImGui::PopStyleVar(); ImGui::PopID(); } ImGui::PopID(); - - ImGui::PopStyleVar(3); + ImGui::PopStyleVar(); ImGui::TreePop(); } } @@ -4652,8 +4620,6 @@ static void DemoWindowLayout() IMGUI_DEMO_MARKER("Layout/Child windows"); ImGui::SeparatorText("Child windows"); - const float ref_sz = ImGui::GetTextLineHeightWithSpacing(); - HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window."); static bool disable_mouse_wheel = false; static bool disable_menu = false; @@ -4665,7 +4631,7 @@ static void DemoWindowLayout() ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar; if (disable_mouse_wheel) window_flags |= ImGuiWindowFlags_NoScrollWithMouse; - ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 15 * ref_sz), ImGuiChildFlags_None, window_flags); + ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 260), ImGuiChildFlags_None, window_flags); for (int i = 0; i < 100; i++) ImGui::Text("%04d: scrollable region", i); ImGui::EndChild(); @@ -4681,7 +4647,7 @@ static void DemoWindowLayout() if (!disable_menu) window_flags |= ImGuiWindowFlags_MenuBar; ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); - ImGui::BeginChild("ChildR", ImVec2(0, 15 * ref_sz), ImGuiChildFlags_Borders, window_flags); + ImGui::BeginChild("ChildR", ImVec2(0, 260), ImGuiChildFlags_Borders, window_flags); if (!disable_menu && ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Menu")) @@ -4710,11 +4676,11 @@ static void DemoWindowLayout() ImGui::SeparatorText("Manual-resize"); { HelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents."); - //if (ImGui::Button("Set Height to 300")) - // ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 300.0f)); + //if (ImGui::Button("Set Height to 200")) + // ImGui::SetNextWindowSize(ImVec2(-FLT_MIN, 200.0f)); ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg)); - if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ref_sz * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) + if (ImGui::BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) for (int n = 0; n < 10; n++) ImGui::Text("Line %04d", n); ImGui::PopStyleColor(); @@ -4726,12 +4692,12 @@ static void DemoWindowLayout() { static int draw_lines = 3; static int max_height_in_lines = 10; - ImGui::SetNextItemWidth(ref_sz * 7); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); ImGui::DragInt("Lines Count", &draw_lines, 0.2f); - ImGui::SetNextItemWidth(ref_sz * 7); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); ImGui::DragInt("Max Height (in Lines)", &max_height_in_lines, 0.2f); - ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ref_sz * 1), ImVec2(FLT_MAX, ref_sz * max_height_in_lines)); + ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * 1), ImVec2(FLT_MAX, ImGui::GetTextLineHeightWithSpacing() * max_height_in_lines)); if (ImGui::BeginChild("ConstrainedChild", ImVec2(-FLT_MIN, 0.0f), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY)) for (int n = 0; n < draw_lines; n++) ImGui::Text("Line %04d", n); @@ -4751,7 +4717,7 @@ static void DemoWindowLayout() static int offset_x = 0; static bool override_bg_color = true; static ImGuiChildFlags child_flags = ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY; - ImGui::SetNextItemWidth(ref_sz * 7); + ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8); ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000); ImGui::Checkbox("Override ChildBg color", &override_bg_color); ImGui::CheckboxFlags("ImGuiChildFlags_Borders", &child_flags, ImGuiChildFlags_Borders); @@ -4766,7 +4732,7 @@ static void DemoWindowLayout() ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x); if (override_bg_color) ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100)); - ImGui::BeginChild("Red", ImVec2(ref_sz * 12.0f, ref_sz * 6.0f), child_flags, ImGuiWindowFlags_None); + ImGui::BeginChild("Red", ImVec2(200, 100), child_flags, ImGuiWindowFlags_None); if (override_bg_color) ImGui::PopStyleColor(); @@ -4863,7 +4829,7 @@ static void DemoWindowLayout() if (show_indented_items) { ImGui::Indent(); - ImGui::DragFloat("##float6b (indented)", &f); + ImGui::DragFloat("float (indented)##6b", &f); ImGui::Unindent(); } ImGui::PopItemWidth(); @@ -4928,8 +4894,7 @@ static void DemoWindowLayout() static int selection[4] = { 0, 1, 2, 3 }; for (int i = 0; i < 4; i++) { - if (i > 0) - ImGui::SameLine(); + if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::ListBox("", &selection[i], items, IM_COUNTOF(items)); ImGui::PopID(); @@ -4937,11 +4902,9 @@ static void DemoWindowLayout() } ImGui::PopItemWidth(); - const float ref_sz = ImGui::GetTextLineHeightWithSpacing(); - // Dummy IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Dummy"); - ImVec2 button_sz(ref_sz * 3.0f, ref_sz * 3.0f); + ImVec2 button_sz(40, 40); ImGui::Button("A", button_sz); ImGui::SameLine(); ImGui::Dummy(button_sz); ImGui::SameLine(); ImGui::Button("B", button_sz); @@ -5083,10 +5046,10 @@ static void DemoWindowLayout() ImGui::Indent(); // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. - ImGui::Button("120x120", ImVec2(120, 120)); - ImGui::SameLine(); ImGui::Button("80x80", ImVec2(80, 80)); ImGui::SameLine(); + ImGui::Button("50x50", ImVec2(50, 50)); + ImGui::SameLine(); ImGui::Button("Button()"); ImGui::SameLine(); ImGui::SmallButton("SmallButton()"); @@ -6131,12 +6094,11 @@ static void DemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuter", &flags, ImGuiTableFlags_BordersOuter); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInner", &flags, ImGuiTableFlags_BordersInner); ImGui::Unindent(); - + ImGui::AlignTextToFramePadding(); ImGui::Text("Cell contents:"); ImGui::SameLine(); ImGui::RadioButton("Text", &contents_type, CT_Text); ImGui::SameLine(); ImGui::RadioButton("FillButton", &contents_type, CT_FillButton); ImGui::Checkbox("Display headers", &display_headers); - ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags, ImGuiTableFlags_PadOuterX); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBody", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker("Disable vertical borders in columns Body (borders will always appear in Headers)"); PopStyleCompact(); @@ -6364,7 +6326,6 @@ static void DemoWindowTables() "Actual padding values are using style.CellPadding.\n\n" "In this demo we don't show horizontal borders to emphasize how they don't affect default horizontal padding."); - ImGui::PushID("flags1"); static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV; PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_PadOuterX", &flags1, ImGuiTableFlags_PadOuterX); @@ -6375,11 +6336,9 @@ static void DemoWindowTables() ImGui::SameLine(); HelpMarker("Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)"); ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags1, ImGuiTableFlags_BordersOuterV); ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags1, ImGuiTableFlags_BordersInnerV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersH", &flags1, ImGuiTableFlags_BordersH); static bool show_headers = false; ImGui::Checkbox("show_headers", &show_headers); PopStyleCompact(); - ImGui::PopID(); if (ImGui::BeginTable("table_padding", 3, flags1)) { @@ -6419,7 +6378,7 @@ static void DemoWindowTables() HelpMarker("Setting style.CellPadding to (0,0) or a custom value."); static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg; static ImVec2 cell_padding(0.0f, 0.0f); - static bool show_widget_frame_bg = false; + static bool show_widget_frame_bg = true; PushStyleCompact(); ImGui::CheckboxFlags("ImGuiTableFlags_Borders", &flags2, ImGuiTableFlags_Borders); @@ -6438,9 +6397,7 @@ static void DemoWindowTables() { static char text_bufs[3 * 5][16]; // Mini text storage for 3x5 cells static bool init = true; - if (show_widget_frame_bg) - ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0.0f); - else + if (!show_widget_frame_bg) ImGui::PushStyleColor(ImGuiCol_FrameBg, 0); for (int cell = 0; cell < 3 * 5; cell++) { @@ -6452,9 +6409,7 @@ static void DemoWindowTables() ImGui::InputText("##cell", text_bufs[cell], IM_COUNTOF(text_bufs[cell])); ImGui::PopID(); } - if (show_widget_frame_bg) - ImGui::PopStyleVar(); - else + if (!show_widget_frame_bg) ImGui::PopStyleColor(); init = false; ImGui::EndTable(); @@ -6796,20 +6751,19 @@ static void DemoWindowTables() ImGui::CheckboxFlags("ImGuiTableFlags_Resizable", &flags1, ImGuiTableFlags_Resizable); ImGui::CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", &flags1, ImGuiTableFlags_NoBordersInBodyUntilResize); PopStyleCompact(); - if (ImGui::BeginTable("table1", 4, flags1)) + if (ImGui::BeginTable("table1", 3, flags1)) { - // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed if not specified. + // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthFixed, 100.0f); // Default to 100.0f ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthFixed, 200.0f); // Default to 200.0f ImGui::TableSetupColumn("three", ImGuiTableColumnFlags_WidthFixed); // Default to auto - ImGui::TableSetupColumn("four", ImGuiTableColumnFlags_WidthStretch); // Default to remaining width ImGui::TableHeadersRow(); for (int row = 0; row < 4; row++) { ImGui::TableNextRow(); - for (int column = 0; column < 4; column++) + for (int column = 0; column < 3; column++) { - ImGui::TableNextColumn(); + ImGui::TableSetColumnIndex(column); if (row == 0) ImGui::Text("(w: %5.1f)", ImGui::GetContentRegionAvail().x); else @@ -6818,29 +6772,18 @@ static void DemoWindowTables() } ImGui::EndTable(); } - if (ImGui::BeginTable("table2", 2, flags1)) - { - // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. - ImGui::TableSetupColumn("one", ImGuiTableColumnFlags_WidthStretch, 1.0f); // Default weight - ImGui::TableSetupColumn("two", ImGuiTableColumnFlags_WidthStretch, 2.0f); // Default weight - ImGui::TableHeadersRow(); - for (int column = 0; column < 2; column++) - if (ImGui::TableNextColumn()) - ImGui::Text("Default weight %d%%", (column & 1) ? 200 : 100); - ImGui::EndTable(); - } HelpMarker( "Using TableSetupColumn() to setup explicit width.\n\nUnless _NoKeepColumnsVisible is set, " "fixed columns with set width may still be shrunk down if there's not enough space in the host."); - static ImGuiTableFlags flags3 = ImGuiTableFlags_None; + static ImGuiTableFlags flags2 = ImGuiTableFlags_None; PushStyleCompact(); - ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags3, ImGuiTableFlags_NoKeepColumnsVisible); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags3, ImGuiTableFlags_BordersInnerV); - ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags3, ImGuiTableFlags_BordersOuterV); + ImGui::CheckboxFlags("ImGuiTableFlags_NoKeepColumnsVisible", &flags2, ImGuiTableFlags_NoKeepColumnsVisible); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersInnerV", &flags2, ImGuiTableFlags_BordersInnerV); + ImGui::CheckboxFlags("ImGuiTableFlags_BordersOuterV", &flags2, ImGuiTableFlags_BordersOuterV); PopStyleCompact(); - if (ImGui::BeginTable("table3", 4, flags3)) + if (ImGui::BeginTable("table2", 4, flags2)) { // We could also set ImGuiTableFlags_SizingFixedFit on the table and then all columns // will default to ImGuiTableColumnFlags_WidthFixed. @@ -6980,7 +6923,6 @@ static void DemoWindowTables() if (ImGui::TreeNode("Outer size")) { IMGUI_DEMO_MARKER("Tables/Outer size"); - // Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY // Important to that note how the two flags have slightly different behaviors! ImGui::Text("Using NoHostExtendX and NoHostExtendY:"); @@ -7076,7 +7018,7 @@ static void DemoWindowTables() // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. if (row_bg_type != 0) { - ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.40f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.40f)); // Flat or Gradient? + ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient? ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color); } @@ -8208,8 +8150,7 @@ static void DemoWindowInputs() ImGui::SetNextItemWidth(ImGui::GetFontSize() * 15); ImGui::SliderInt("SetNextFrameWantCaptureKeyboard() on hover", &capture_override_keyboard, -1, +1, capture_override_desc[capture_override_keyboard + 1], ImGuiSliderFlags_AlwaysClamp); - float ref_sz = ImGui::GetFrameHeight() * 4.0f; - ImGui::ColorButton("##panel", ImVec4(0.7f, 0.1f, 0.7f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, ImVec2(ref_sz, ref_sz)); // Dummy item + ImGui::ColorButton("##panel", ImVec4(0.7f, 0.1f, 0.7f, 1.0f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoDragDrop, ImVec2(128.0f, 96.0f)); // Dummy item if (ImGui::IsItemHovered() && capture_override_mouse != -1) ImGui::SetNextFrameWantCaptureMouse(capture_override_mouse == 1); if (ImGui::IsItemHovered() && capture_override_keyboard != -1) @@ -8835,10 +8776,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SliderFloat("ImageRounding", &style.ImageRounding, 0.0f, 12.0f, "%.0f"); SliderFloat("ImageBorderSize", &style.ImageBorderSize, 0.0f, max_border_size, "%.0f"); - SeparatorText("Symbols"); - DragFloat2("SymbolArrowSizeFactor", &style.SymbolArrowSizeFactor.x, 0.01f, 0.0f, 1.0f); - DragFloat("SymbolArrowThicknessFactor", &style.SymbolArrowThicknessFactor, 0.01f, 0.0f, 0.5f); - SeparatorText("Tooltips"); for (int n = 0; n < 2; n++) if (TreeNodeEx(n == 0 ? "HoverFlagsForTooltipMouse" : "HoverFlagsForTooltipNav")) @@ -8883,6 +8820,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) SameLine(); SetNextItemWidth(GetFontSize() * 10); Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); SameLine(); Checkbox("Only Modified Colors", &output_only_modified); + static ImGuiTextFilter filter; + filter.Draw("Filter colors", GetFontSize() * 16); + static ImGuiColorEditFlags alpha_flags = 0; if (RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_AlphaOpaque)) { alpha_flags = ImGuiColorEditFlags_AlphaOpaque; } SameLine(); if (RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } SameLine(); @@ -8892,10 +8832,6 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) "Left-click on color square to open color picker,\n" "Right-click to open edit options menu."); - static ImGuiTextFilter filter; - SetNextItemWidth(-FLT_MIN); - filter.DrawWithHint("##FilterColors", "Filter Colors (incl -excl)"); - SetNextWindowSizeConstraints(ImVec2(0.0f, GetTextLineHeightWithSpacing() * 10), ImVec2(FLT_MAX, FLT_MAX)); BeginChild("##colors", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_NavFlattened, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar); PushItemWidth(GetFontSize() * -12); @@ -8963,21 +8899,12 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) Checkbox("Anti-aliased lines", &style.AntiAliasedLines); SameLine(); HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well."); - BeginDisabled(style.AntiAliasedLines == false); - Checkbox("Anti-aliased line ends", &style.AntiAliasedLineEnds); - EndDisabled(); -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - BeginDisabled(); Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex); SameLine(); HelpMarker("Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering)."); - EndDisabled(); -#endif Checkbox("Anti-aliased fill", &style.AntiAliasedFill); - Checkbox("Debug: DrawList Defaults to _StrokeLegacy", &ImGui::GetIO().ConfigDebugDrawListDefaultsToStrokeLegacy); - PushItemWidth(GetFontSize() * 8); DragFloat("Curve Tessellation Max Error", &style.CurveTessellationMaxError, 0.02f, 0.10f, 10.0f, "%.2f"); if (style.CurveTessellationMaxError < 0.10f) @@ -9034,6 +8961,22 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) EndTabItem(); } + if (BeginTabItem("Shadows")) + { + Text("Window shadows:"); + ColorEdit4("Color", (float*)&style.Colors[ImGuiCol_WindowShadow], ImGuiColorEditFlags_AlphaBar); + SameLine(); + HelpMarker("Same as 'WindowShadow' in Colors tab."); + + SliderFloat("Size", &style.WindowShadowSize, 0.0f, 128.0f, "%.1f"); + SameLine(); + HelpMarker("Set shadow size to zero to disable shadows."); + SliderFloat("Offset distance", &style.WindowShadowOffsetDist, 0.0f, 64.0f, "%.0f"); + SliderAngle("Offset angle", &style.WindowShadowOffsetAngle); + + EndTabItem(); + } + EndTabBar(); } PopItemWidth(); @@ -9243,8 +9186,8 @@ struct ExampleAppConsole } // Portable helpers - static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s1) - toupper(*s2)) == 0 && *s1) { s1++; s2++; } return d; } - static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s1) - toupper(*s2)) == 0 && *s1) { s1++; s2++; n--; } return d; } + static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; } + static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; } static char* Strdup(const char* s) { IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = ImGui::MemAlloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); } static void Strtrimblanks(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; } @@ -9317,10 +9260,7 @@ struct ExampleAppConsole if (ImGui::Button("Options")) ImGui::OpenPopup("Options"); ImGui::SameLine(); - - ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); - ImGui::SetNextItemWidth(-FLT_MIN); - Filter.DrawWithHint("##Filter", "Filter (incl -excl)"); + Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); ImGui::Separator(); // Reserve enough left-over height for 1 separator + 1 input text @@ -9655,8 +9595,7 @@ struct ExampleAppLog ImGui::SameLine(); bool copy = ImGui::Button("Copy"); ImGui::SameLine(); - ImGui::SetNextItemWidth(-FLT_MIN); - Filter.DrawWithHint("##Filter", "Filter (incl -excl)"); + Filter.Draw("Filter", -100.0f); ImGui::Separator(); @@ -9851,7 +9790,7 @@ struct ExampleAppPropertyEditor ImGui::Text("(%d root nodes)", root_node->Childs.Size); ImGui::SetNextItemWidth(-FLT_MIN); ImGui::SetNextItemShortcut(ImGuiMod_Ctrl | ImGuiKey_F, ImGuiInputFlags_Tooltip); - if (ImGui::InputTextWithHint("##Filter", "incl -excl", Filter.InputBuf, IM_COUNTOF(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) + if (ImGui::InputTextWithHint("##Filter", "incl,-excl", Filter.InputBuf, IM_COUNTOF(Filter.InputBuf), ImGuiInputTextFlags_EscapeClearsAll)) Filter.Build(); ImGui::PopItemFlag(); @@ -10392,10 +10331,13 @@ static void ShowExampleAppWindowTitles(bool*) // [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() //----------------------------------------------------------------------------- -// See our Wiki guides: -// - ImDrawList Vector Rendering Reference: https://github.com/ocornut/imgui/wiki/Draw-List -// - Pixel Perfect Anti-aliased Rendering: https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering -// - How Anti-aliased Polyline Rendering is Implemented: https://github.com/ocornut/imgui/wiki/Polyline-Rendering +// Add a |_| looking shape +static void PathConcaveShape(ImDrawList* draw_list, float x, float y, float sz) +{ + const ImVec2 pos_norms[] = { { 0.0f, 0.0f }, { 0.3f, 0.0f }, { 0.3f, 0.7f }, { 0.7f, 0.7f }, { 0.7f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; + for (const ImVec2& p : pos_norms) + draw_list->PathLineTo(ImVec2(x + 0.5f + (int)(sz * p.x), y + 0.5f + (int)(sz * p.y))); +} // Demonstrate using the low-level ImDrawList to draw custom shapes. static void ShowExampleAppCustomRendering(bool* p_open) @@ -10427,250 +10369,118 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::Text("Gradients"); ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight()); { - ImGui::InvisibleButton("##gradient1", gradient_size); + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255)); ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255)); - draw_list->AddRectFilledMultiColor(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), col_a, col_b, col_b, col_a); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); + ImGui::InvisibleButton("##gradient1", gradient_size); } { - ImGui::InvisibleButton("##gradient2", gradient_size); + ImVec2 p0 = ImGui::GetCursorScreenPos(); + ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y); ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255)); ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255)); - draw_list->AddRectFilledMultiColor(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), col_a, col_b, col_b, col_a); + draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a); + ImGui::InvisibleButton("##gradient2", gradient_size); } // Draw a bunch of primitives ImGui::Text("All primitives"); static float sz = 42.0f; - static float base_rounding = 8.0f; - static float base_thickness = 3.0f; - static bool animate_rounding = false; - static bool animate_thickness = false; - static int ngon_segments = 6; + static float thickness = 3.0f; + static int ngon_sides = 6; static bool circle_segments_override = false; static int circle_segments_override_v = 12; static bool curve_segments_override = false; static int curve_segments_override_v = 8; - static ImVec4 colf_stroke = ImVec4(1.000f, 0.384f, 0.169f, 1.000f); - static ImVec4 colf_fill = ImVec4(0.416f, 0.378f, 0.420f, 1.000f); - - ImGui::DragFloat("Size", &sz, 0.2f, 0.2f, 100.0f, "%.0f"); - - const float rounding_anim_period = 3.0f; - const float rounding_wave = 1.0f - fabsf(fmodf((float)ImGui::GetTime(), rounding_anim_period) * (2.0f / rounding_anim_period) - 1.0f); - const float rounding = animate_rounding ? (float)(int)(rounding_wave * base_rounding * 10.0f) / 10.0f : base_rounding; // Sub-integer rounding works but has discontinuities in small values, so best disable we - ImGui::DragFloat("Rounding", &base_rounding, 0.02f, 0.0f, 32.0f, "%.1f"); ImGui::SameLine(); - ImGui::Checkbox("Animate##rounding", &animate_rounding); ImGui::SameLine(); - ImGui::Text("%.2f", rounding); - - const float thickness_anim_period = 5.0f; - const float thickness_wave = 1.0f - fabsf(fmodf((float)ImGui::GetTime(), thickness_anim_period) * (2.0f / thickness_anim_period) - 1.0f); - const float thickness = animate_thickness ? thickness_wave * base_thickness : base_thickness; - ImGui::DragFloat("Thickness", &base_thickness, 0.02f, 0.0f, 32.0f, "%.02f"); ImGui::SameLine(); - ImGui::Checkbox("Animate##thickness", &animate_thickness); ImGui::SameLine(); - ImGui::Text("%.2f", thickness); - - ImGui::SliderInt("N-gon sides", &ngon_segments, 3, 12); - ImGui::Checkbox("##CircleSegmentOverride", &circle_segments_override); + static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f); + ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 100.0f, "%.0f"); + ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f"); + ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12); + ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); - circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 30); - ImGui::Checkbox("##CurvesSegmentOverride", &curve_segments_override); + circle_segments_override |= ImGui::SliderInt("Circle segments override", &circle_segments_override_v, 3, 40); + ImGui::Checkbox("##curvessegmentoverride", &curve_segments_override); ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); - curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 30); - ImGui::ColorEdit4("Stroke Color", &colf_stroke.x); - ImGui::ColorEdit4("Fill Color", &colf_fill.x); + curve_segments_override |= ImGui::SliderInt("Curves segments override", &curve_segments_override_v, 3, 40); + ImGui::ColorEdit4("Color", &colf.x); - static ImDrawFlags prim_stroke_flags = ImDrawFlags_None; - static ImDrawFlags prim_other_flags = ImDrawFlags_AALineEnds; - ImGui::SeparatorText("Per primitive flags (AddXXX functions)"); - ImGui::RadioButton("Default", &prim_stroke_flags, ImDrawFlags_None); ImGui::SameLine(); - ImGui::RadioButton("Inside", &prim_stroke_flags, ImDrawFlags_StrokeInside); ImGui::SameLine(); - ImGui::RadioButton("Center", &prim_stroke_flags, ImDrawFlags_StrokeCenter); ImGui::SameLine(); - ImGui::RadioButton("CenterBiased", &prim_stroke_flags, ImDrawFlags_StrokeCenterBiased); ImGui::SameLine(); - ImGui::RadioButton("Outside", &prim_stroke_flags, ImDrawFlags_StrokeOutside); ImGui::SameLine(); - ImGui::RadioButton("Legacy", &prim_stroke_flags, ImDrawFlags_StrokeLegacy); - ImGui::CheckboxFlags("AAFill", &prim_other_flags, ImDrawFlags_AAFill); ImGui::SameLine(); // Note: Only for functions taking flags. - ImGui::CheckboxFlags("AALines", &prim_other_flags, ImDrawFlags_AALines); ImGui::SameLine(); // Note: Only for functions taking flags. - ImGui::CheckboxFlags("AALineEnds", &prim_other_flags, ImDrawFlags_AALineEnds); ImGui::SameLine(); - ImGui::CheckboxFlags("JoinMiter", &prim_other_flags, ImDrawFlags_JoinMiter); ImGui::SameLine(); - ImGui::CheckboxFlags("CapSquare", &prim_other_flags, ImDrawFlags_CapSquare); - //ImGui::CheckboxFlags("UseTexForRoundCorners", &prim_other_flags, ImDrawFlags_UseTexForRoundCorners); - - static ImDrawFlags scope_flags = draw_list->Flags & ImDrawFlags_AllowInPushScope_; // First init copy current state. - ImGui::SeparatorText("Current ImDrawList flags (e.g. PushDrawFlag function)"); - ImGui::PushID("ScopeFlags"); - ImGui::CheckboxFlags("AAFill", &scope_flags, ImDrawFlags_AAFill); ImGui::SameLine(); - ImGui::CheckboxFlags("AALines", &scope_flags, ImDrawFlags_AALines); ImGui::SameLine(); - ImGui::CheckboxFlags("AALineEnds", &scope_flags, ImDrawFlags_AALineEnds); ImGui::SameLine(); - ImGui::CheckboxFlags("StrokeLegacy", &scope_flags, ImDrawFlags_StrokeLegacy); - //ImGui::CheckboxFlags("UseTexForRoundCorners", &scope_flags, ImDrawFlags_UseTexForRoundCorners); - ImGui::PopID(); - ImGui::Spacing(); - - draw_list->PushDrawFlag(ImDrawFlags_AllowInPushScope_, false); // Reset all existing (very unusual: done for this demo) - draw_list->PushDrawFlag(scope_flags, true); - const ImDrawFlags flags = prim_stroke_flags | prim_other_flags; - - const ImVec2 start_pos = ImGui::GetCursorScreenPos(); - const float pi = 3.141592f; - const float step = sz + 10.0f; - const ImDrawFlags corners_tl_br = ImDrawFlags_RoundTopLeft | ImDrawFlags_RoundBottomRight; - const float half_sz = sz * 0.5f; + const ImVec2 p = ImGui::GetCursorScreenPos(); + const ImU32 col = ImColor(colf); + const float spacing = 10.0f; + const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight; + const float rounding = sz / 5.0f; const int circle_segments = circle_segments_override ? circle_segments_override_v : 0; const int curve_segments = curve_segments_override ? curve_segments_override_v : 0; - const ImVec2 cp3[3] = { { 0.0f, sz * 0.6f }, { sz * 0.5f, -sz * 0.4f }, { sz, sz } }; // Control points for curves - const ImVec2 cp4[4] = { { 0.0f, 0.0f }, { sz * 1.3f, sz * 0.3f }, { sz - sz * 1.3f, sz - sz * 0.3f }, { sz, sz } }; - const ImVec2 concave_shape[] = { { 0.0f, 0.0f }, { 0.3f, 0.0f }, { 0.3f, 0.7f }, { 0.7f, 0.7f }, { 0.7f, 0.0f }, { 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 1.0f } }; // |_| looking shape. Normalized. - const ImVec2 zigzag_shape[] = { { 0.0f, 0.0f }, { 0.9f, 0.0f }, { 1.0f, 0.1f }, { 1.0f, 0.9f }, { 0.9f, 1.0f }, { 0.3f, 1.0f }, { 0.3f, 0.4f }, { 0.9f, 0.4f } }; - ImVec2 rotating_square[4]; - for (int side = 0; side < 4; side++) + const ImVec2 cp3[3] = { ImVec2(0.0f, sz * 0.6f), ImVec2(sz * 0.5f, -sz * 0.4f), ImVec2(sz, sz) }; // Control points for curves + const ImVec2 cp4[4] = { ImVec2(0.0f, 0.0f), ImVec2(sz * 1.3f, sz * 0.3f), ImVec2(sz - sz * 1.3f, sz - sz * 0.3f), ImVec2(sz, sz) }; + + float x = p.x + 4.0f; + float y = p.y + 4.0f; + for (int n = 0; n < 2; n++) { - float t = (float)ImGui::GetTime() * 0.1f + side * pi * 0.5f; - rotating_square[side] = { (float)cosf(t) * half_sz, (float)sinf(t) * half_sz }; + // First line uses a thickness of 1.0f, second line uses the configurable thickness + float th = (n == 0) ? 1.0f : thickness; + draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon + draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th); x += sz + spacing; // Circle + draw_list->AddEllipse(ImVec2(x + sz*0.5f, y + sz*0.5f), ImVec2(sz*0.5f, sz*0.3f), col, -0.3f, circle_segments, th); x += sz + spacing; // Ellipse + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, th); x += sz + spacing; // Square + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th); x += sz + spacing; // Square with all rounded corners + draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing; // Triangle + //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle + PathConcaveShape(draw_list, x, y, sz); draw_list->PathStroke(col, th, ImDrawFlags_Closed); x += sz + spacing; // Concave Shape + //draw_list->AddPolyline(concave_shape, IM_COUNTOF(concave_shape), col, ImDrawFlags_Closed, th); + draw_list->AddLineH(x, x + sz, y, col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!) + draw_list->AddLineV(x, y, y + sz, col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!) + draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line + + // Path + draw_list->PathArcTo(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, 3.141592f, 3.141592f * -0.5f); + draw_list->PathStroke(col, th); + x += sz + spacing; + + // Quadratic Bezier Curve (3 control points) + draw_list->AddBezierQuadratic(ImVec2(x + cp3[0].x, y + cp3[0].y), ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), col, th, curve_segments); + x += sz + spacing; + + // Cubic Bezier Curve (4 control points) + draw_list->AddBezierCubic(ImVec2(x + cp4[0].x, y + cp4[0].y), ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), col, th, curve_segments); + + x = p.x + 4; + y += sz + spacing; } - float x = start_pos.x; - float y = start_pos.y; - for (int row = 0; row < 4; row++) - { - x = start_pos.x; - bool draw_fill = (row == 2 || row == 3); - bool draw_strokes = (row == 0 || row == 1 || row == 3); - if (draw_fill) - { - // FILLED SHAPES - const ImU32 col = ImColor(colf_fill); - draw_list->AddNgonFilled({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments); x += step; // N-gon - draw_list->AddCircleFilled({ x + half_sz, y + half_sz }, half_sz, col, circle_segments); x += step; // Circle - draw_list->AddEllipseFilled({ x + half_sz, y + half_sz }, { half_sz, sz * 0.3f }, col, -0.3f, circle_segments); x += step;// Ellipse - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, 0.0f, flags); x += step; // Square - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, flags); x += step; // Square with all rounded corners - draw_list->AddRectFilled({ x, y }, { x + sz, y + sz }, col, rounding, flags | corners_tl_br); x += step; // Square with two rounded corners - draw_list->AddTriangleFilled({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col); x += step; // Triangle - draw_list->AddTriangleFilled({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col); x += step - (float)(int)(sz * 0.6f); // Thin triangle + // Filled shapes + draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, ngon_sides); x += sz + spacing; // N-gon + draw_list->AddCircleFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, circle_segments); x += sz + spacing; // Circle + draw_list->AddEllipseFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), ImVec2(sz * 0.5f, sz * 0.3f), col, -0.3f, circle_segments); x += sz + spacing;// Ellipse + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners + draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col); x += sz + spacing; // Triangle + //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle + PathConcaveShape(draw_list, x, y, sz); draw_list->PathFillConcave(col); x += sz + spacing; // Concave shape + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness) + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine) - // Concave shape: U - for (const ImVec2& p : concave_shape) - draw_list->PathLineTo({ x + (int)(sz * p.x), y + (int)(sz * p.y) }); - draw_list->PathFillConcave(col); - x += step; + // Path + draw_list->PathArcTo(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, 3.141592f * -0.5f, 3.141592f); + draw_list->PathFillConvex(col); + x += sz + spacing; - // Concave shape: Zig-Zag with sharp angles (see difference with/without JoinMiter) - for (const ImVec2& p : zigzag_shape) - draw_list->PathLineTo({ x + (int)(sz * p.x), y + (int)(sz * p.y) }); - draw_list->PathFillConcave(col); - x += step; + // Quadratic Bezier Curve (3 control points) + draw_list->PathLineTo(ImVec2(x + cp3[0].x, y + cp3[0].y)); + draw_list->PathBezierQuadraticCurveTo(ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), curve_segments); + draw_list->PathFillConvex(col); + x += sz + spacing; - // Horizontal/Vertical lines - // (here for consistency with the strokes section. AddRectFilled() is roughly close to AddLineH(), AddLineV() - draw_list->AddRectFilled({ x, y }, { x + sz, y + thickness }, col); x += step; - draw_list->AddRectFilled({ x, y }, { x + thickness, y + sz }, col); x += step - (float)(int)half_sz; - if (!(draw_fill && draw_strokes)) //-V560 - for (int block_sz = 1, off = 0; block_sz < 16 && off + block_sz <= sz; off += block_sz + 1, block_sz++) - draw_list->AddRectFilled({ x, y + off }, { x + block_sz, y + off + block_sz }, col); - x += step - (float)(int)half_sz; - - // Rotating square - for (int n = 0; n < 4; n++) - draw_list->PathLineTo({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }); - draw_list->PathFillConvex(col, flags); - x += step; - - // Path - draw_list->PathArcTo({ x + half_sz, y + half_sz }, half_sz, pi * -0.5f, pi * 1.1f); - draw_list->PathFillConvex(col); - x += step; - - // Quadratic Bezier Curve (3 control points) - draw_list->PathLineTo({ x + cp3[0].x, y + cp3[0].y }); - draw_list->PathBezierQuadraticCurveTo({ x + cp3[1].x, y + cp3[1].y }, { x + cp3[2].x, y + cp3[2].y }, curve_segments); - draw_list->PathFillConvex(col); - x += step; - - if (!(draw_fill && draw_strokes)) //-V560 - { - draw_list->AddRectFilledMultiColor({ x, y }, { x + sz, y + sz }, IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255)); - x += step; - } - } - if (draw_fill && draw_strokes) - x = start_pos.x; - if (draw_strokes) - { - // STROKES - // First row uses a thickness of 1.0f, second row uses the configurable thickness - const ImU32 col = ImColor(colf_stroke); - float th = (row == 0) ? 1.0f : thickness; - draw_list->AddNgon({ x + half_sz, y + half_sz }, half_sz, col, ngon_segments, th, flags); x += step; // N-gon - draw_list->AddCircle({ x + half_sz, y + half_sz }, half_sz, col, circle_segments, th, flags); x += step; // Circle - draw_list->AddEllipse({ x + half_sz, y + half_sz }, { half_sz, sz * 0.3f }, col, -0.3f, circle_segments, th, flags); x += step; // Ellipse - draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, 0.0f, th, flags); x += step; // Square - draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, rounding, th, flags); x += step; // Square with all rounded corners - draw_list->AddRect({ x, y }, { x + sz, y + sz }, col, rounding, th, flags | corners_tl_br); x += step; // Square with two rounded corners - draw_list->AddTriangle({ x + sz * 0.5f, y }, { x + sz, y + sz }, { x, y + sz }, col, th, flags); x += step; // Triangle - draw_list->AddTriangle({ x + sz * 0.2f, y }, { x + sz * 0.4f, y + sz }, { x, y + sz }, col, th, flags); x += step - (float)(int)(sz * 0.6f); // Thin triangle - - // Concave shape: U - for (const ImVec2& p : concave_shape) - draw_list->PathLineTo({ x + (int)(sz * p.x), y + (int)(sz * p.y) }); - draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); - x += step; - - // Concave shape: Zig-Zag with sharp angles (see difference with/without JoinMiter) - for (const ImVec2& p : zigzag_shape) - draw_list->PathLineTo({ x + (int)(sz * p.x), y + (int)(sz * p.y) }); - draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); - x += step; - - // Horizontal/Vertical/Diagonal lines - const float off = (float)(int)(sz * 0.4f); - draw_list->AddLineH(x, x + sz, y, col, th, flags); - draw_list->AddLine({ x, y + off }, { x + sz, y + off }, col, th, flags); - x += step; - draw_list->AddLineV(x, y, y + sz, col, th, flags); - draw_list->AddLine({ x + off, y + sz }, { x + off, y }, col, th, flags); - x += step - (float)(int)half_sz; - if (!(draw_fill && draw_strokes)) //-V560 - { - draw_list->AddLine({ x, y }, { x + half_sz, y + sz }, col, th, flags); - draw_list->AddLine({ x, y + sz }, { x + half_sz, y }, col, th, flags); - } - x += step - (float)(int)half_sz; - - // Rotating square - for (int n = 0; n < 4; n++) - draw_list->PathLineTo({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }); - draw_list->PathStroke(col, th, flags | ImDrawFlags_Closed); - //for (int n = 0; n < 4; n++) // ...made of individual line - // draw_list->AddLine({ x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y }, { x + half_sz + rotating_square[(n + 1) & 3].x, y + half_sz + rotating_square[(n + 1) & 3].y }, col, th, flags); - x += step; - - // Path - draw_list->PathArcTo({ x + half_sz, y + half_sz }, half_sz, pi * -0.5f, pi * 1.1f); - draw_list->PathStroke(col, th, flags); - x += step; - - // Quadratic Bezier Curve (3 control points) - draw_list->AddBezierQuadratic({ x + cp3[0].x, y + cp3[0].y }, { x + cp3[1].x, y + cp3[1].y }, { x + cp3[2].x, y + cp3[2].y }, col, th, curve_segments, flags); - x += step; - - // Cubic Bezier Curve (4 control points) - if (!(draw_fill && draw_strokes)) //-V560 - { - draw_list->AddBezierCubic({ x + cp4[0].x, y + cp4[0].y }, { x + cp4[1].x, y + cp4[1].y }, { x + cp4[2].x, y + cp4[2].y }, { x + cp4[3].x, y + cp4[3].y }, col, th, curve_segments, flags); - x += step; - } - } - y += step; - } - - ImGui::Dummy(ImVec2(step * 15.5f, step * 4.0f)); - draw_list->PopDrawFlag(); - draw_list->PopDrawFlag(); - - ImGui::Text("ImDrawList Vector Rendering Reference:"); - ImGui::TextLinkOpenURL("https://github.com/ocornut/imgui/wiki/Draw-List"); + draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255)); + x += sz + spacing; + ImGui::Dummy(ImVec2((sz + spacing) * 13.2f, (sz + spacing) * 3.0f)); ImGui::PopItemFlag(); ImGui::PopItemWidth(); ImGui::EndTabItem(); @@ -10774,6 +10584,168 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::EndTabItem(); } + if (ImGui::BeginTabItem("Shadows")) + { + static float shadow_thickness = 40.0f; + static ImVec4 shadow_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + static bool shadow_filled = false; + static ImVec4 shape_color = ImVec4(0.9f, 0.6f, 0.3f, 1.0f); + static float shape_rounding = 0.0f; + static ImVec2 shadow_offset(0.0f, 0.0f); + static ImVec4 background_color = ImVec4(0.5f, 0.5f, 0.7f, 1.0f); + static bool wireframe = false; + static bool aa = true; + static int poly_shape_index = 0; + ImGui::Checkbox("Shadow filled", &shadow_filled); + ImGui::SameLine(); + HelpMarker("This will fill the section behind the shape to shadow. It's often unnecessary and wasteful but provided for consistency."); + ImGui::Checkbox("Wireframe shapes", &wireframe); + ImGui::SameLine(); + HelpMarker("This draws the shapes in wireframe so you can see the shadow underneath."); + ImGui::Checkbox("Anti-aliasing", &aa); + + ImGui::DragFloat("Shadow Thickness", &shadow_thickness, 1.0f, 0.0f, 100.0f, "%.02f"); + ImGui::SliderFloat2("Offset", (float*)&shadow_offset, -32.0f, 32.0f); + ImGui::SameLine(); + HelpMarker("Note that currently circles/convex shapes do not support non-zero offsets for unfilled shadows."); + ImGui::ColorEdit4("Background Color", &background_color.x); + ImGui::ColorEdit4("Shadow Color", &shadow_color.x); + ImGui::ColorEdit4("Shape Color", &shape_color.x); + ImGui::DragFloat("Shape Rounding", &shape_rounding, 1.0f, 0.0f, 20.0f, "%.02f"); + ImGui::Combo("Convex shape", &poly_shape_index, "Shape 1\0Shape 2\0Shape 3\0Shape 4\0Shape 4 (winding reversed)\0"); + + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + ImDrawListFlags old_flags = draw_list->Flags; + + if (aa) + draw_list->Flags |= ~ImDrawListFlags_AntiAliasedFill; + else + draw_list->Flags &= ~ImDrawListFlags_AntiAliasedFill; + + // Fill a strip of background + { + ImVec2 p = ImGui::GetCursorScreenPos(); + draw_list->AddRectFilled(p, ImVec2(p.x + ImGui::GetContentRegionAvail().x, p.y + 200.0f), ImGui::GetColorU32(background_color)); + } + + // Rectangle + { + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::Dummy(ImVec2(200.0f, 200.0f)); + + ImVec2 r1(p.x + 50.0f, p.y + 50.0f); + ImVec2 r2(p.x + 150.0f, p.y + 150.0f); + ImDrawFlags draw_flags = shadow_filled ? ImDrawFlags_None : ImDrawFlags_ShadowCutOutShapeBackground; + draw_list->AddShadowRect(r1, r2, ImGui::GetColorU32(shadow_color), shadow_thickness, shadow_offset, draw_flags, shape_rounding); + + if (wireframe) + draw_list->AddRect(r1, r2, ImGui::GetColorU32(shape_color), shape_rounding); + else + draw_list->AddRectFilled(r1, r2, ImGui::GetColorU32(shape_color), shape_rounding); + } + + ImGui::SameLine(); + + // Circle + { + ImVec2 p = ImGui::GetCursorScreenPos(); + ImGui::Dummy(ImVec2(200.0f, 200.0f)); + + // FIXME-SHADOWS: Offset forced to zero when shadow is not filled because it isn't supported + float off = 10.0f; + ImVec2 r1(p.x + 50.0f + off, p.y + 50.0f + off); + ImVec2 r2(p.x + 150.0f - off, p.y + 150.0f - off); + ImVec2 center(p.x + 100.0f, p.y + 100.0f); + ImDrawFlags draw_flags = shadow_filled ? ImDrawFlags_None : ImDrawFlags_ShadowCutOutShapeBackground; + draw_list->AddShadowCircle(center, 50.0f, ImGui::GetColorU32(shadow_color), shadow_thickness, shadow_filled ? shadow_offset : ImVec2(0.0f, 0.0f), draw_flags, 0); + + if (wireframe) + draw_list->AddCircle(center, 50.0f, ImGui::GetColorU32(shape_color), 0); + else + draw_list->AddCircleFilled(center, 50.0f, ImGui::GetColorU32(shape_color), 0); + } + + ImGui::SameLine(); + + // Convex shape + { + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::Dummy(ImVec2(200.0f, 200.0f)); + + const ImVec2 poly_centre(pos.x + 50.0f, pos.y + 100.0f); + ImVec2 poly_points[8]; + int poly_points_count = 0; + + switch (poly_shape_index) + { + default: + case 0: + { + poly_points[0] = ImVec2(poly_centre.x - 32.0f, poly_centre.y); + poly_points[1] = ImVec2(poly_centre.x - 24.0f, poly_centre.y + 24.0f); + poly_points[2] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[3] = ImVec2(poly_centre.x + 24.0f, poly_centre.y + 24.0f); + poly_points[4] = ImVec2(poly_centre.x + 32.0f, poly_centre.y); + poly_points[5] = ImVec2(poly_centre.x + 24.0f, poly_centre.y - 24.0f); + poly_points[6] = ImVec2(poly_centre.x, poly_centre.y - 32.0f); + poly_points[7] = ImVec2(poly_centre.x - 32.0f, poly_centre.y - 32.0f); + poly_points_count = 8; + break; + } + case 1: + { + poly_points[0] = ImVec2(poly_centre.x + 40.0f, poly_centre.y - 20.0f); + poly_points[1] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[2] = ImVec2(poly_centre.x - 24.0f, poly_centre.y - 32.0f); + poly_points_count = 3; + break; + } + case 2: + { + poly_points[0] = ImVec2(poly_centre.x - 32.0f, poly_centre.y); + poly_points[1] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[2] = ImVec2(poly_centre.x + 32.0f, poly_centre.y); + poly_points[3] = ImVec2(poly_centre.x, poly_centre.y - 32.0f); + poly_points_count = 4; + break; + } + case 3: + { + poly_points[0] = ImVec2(poly_centre.x - 4.0f, poly_centre.y - 20.0f); + poly_points[1] = ImVec2(poly_centre.x + 12.0f, poly_centre.y + 2.0f); + poly_points[2] = ImVec2(poly_centre.x + 8.0f, poly_centre.y + 16.0f); + poly_points[3] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[4] = ImVec2(poly_centre.x - 16.0f, poly_centre.y - 32.0f); + poly_points_count = 5; + break; + } + case 4: // Same as test case 3 but with reversed winding + { + poly_points[0] = ImVec2(poly_centre.x - 16.0f, poly_centre.y - 32.0f); + poly_points[1] = ImVec2(poly_centre.x, poly_centre.y + 32.0f); + poly_points[2] = ImVec2(poly_centre.x + 8.0f, poly_centre.y + 16.0f); + poly_points[3] = ImVec2(poly_centre.x + 12.0f, poly_centre.y + 2.0f); + poly_points[4] = ImVec2(poly_centre.x - 4.0f, poly_centre.y - 20.0f); + poly_points_count = 5; + break; + } + } + + // FIXME-SHADOWS: Offset forced to zero when shadow is not filled because it isn't supported + ImDrawFlags draw_flags = shadow_filled ? ImDrawFlags_None : ImDrawFlags_ShadowCutOutShapeBackground; + draw_list->AddShadowConvexPoly(poly_points, poly_points_count, ImGui::GetColorU32(shadow_color), shadow_thickness, shadow_filled ? shadow_offset : ImVec2(0.0f, 0.0f), draw_flags); + + if (wireframe) + draw_list->AddPolyline(poly_points, poly_points_count, ImGui::GetColorU32(shape_color), 1.0f, ImDrawFlags_Closed); + else + draw_list->AddConvexPolyFilled(poly_points, poly_points_count, ImGui::GetColorU32(shape_color)); + } + + draw_list->Flags = old_flags; + + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem("BG/FG draw lists")) { IMGUI_DEMO_MARKER("Examples/Custom rendering/BG & FG draw lists"); @@ -10804,9 +10776,9 @@ static void ShowExampleAppCustomRendering(bool* p_open) ImGui::Text("Blue shape is drawn first: appears in back"); ImGui::Text("Red shape is drawn after: appears in front"); ImVec2 p0 = ImGui::GetCursorScreenPos(); - draw_list->AddRectFilled({ p0.x, p0.y }, { p0.x + 50, p0.y + 50 }, IM_COL32(0, 0, 255, 255)); // Blue - draw_list->AddRectFilled({ p0.x + 25, p0.y + 25 }, { p0.x + 75, p0.y + 75 }, IM_COL32(255, 0, 0, 255)); // Red - ImGui::Dummy({ 75, 75 }); + draw_list->AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)); // Blue + draw_list->AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)); // Red + ImGui::Dummy(ImVec2(75, 75)); } ImGui::Separator(); { @@ -10818,14 +10790,14 @@ static void ShowExampleAppCustomRendering(bool* p_open) // You can create any number of channels. Tables API use 1 channel per column in order to better batch draw calls. draw_list->ChannelsSplit(2); draw_list->ChannelsSetCurrent(1); - draw_list->AddRectFilled({ p1.x, p1.y }, { p1.x + 50, p1.y + 50 }, IM_COL32(0, 0, 255, 255)); // Blue + draw_list->AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)); // Blue draw_list->ChannelsSetCurrent(0); - draw_list->AddRectFilled({ p1.x + 25, p1.y + 25 }, { p1.x + 75, p1.y + 75 }, IM_COL32(255, 0, 0, 255)); // Red + draw_list->AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)); // Red // Flatten/reorder channels. Red shape is in channel 0 and it appears below the Blue shape in channel 1. // This works by copying draw indices only (vertices are not copied). draw_list->ChannelsMerge(); - ImGui::Dummy({ 75, 75 }); + ImGui::Dummy(ImVec2(75, 75)); ImGui::Text("After reordering, contents of channel 0 appears below channel 1."); } ImGui::EndTabItem(); diff --git a/imgui_draw.cpp b/imgui_draw.cpp index 7b2b7138d..b77fb38cd 100644 --- a/imgui_draw.cpp +++ b/imgui_draw.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.1 WIP +// dear imgui, v1.93.0 WIP // (drawing and font code) /* @@ -9,9 +9,11 @@ Index of this file: // [SECTION] Style functions // [SECTION] ImDrawList // [SECTION] ImTriangulator, ImDrawList concave polygon fill +// [SECTION] ImDrawList Shadow Primitives // [SECTION] ImDrawListSplitter // [SECTION] ImDrawData // [SECTION] Helpers ShadeVertsXXX functions +// [SECTION] ImFontAtlasShadowTexConfig // [SECTION] ImFontConfig // [SECTION] ImFontAtlas, ImFontAtlasBuilder // [SECTION] ImFontAtlas: backend for stb_truetype @@ -62,7 +64,6 @@ Index of this file: #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness -#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here #pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier @@ -113,6 +114,7 @@ namespace IMGUI_STB_NAMESPACE #if defined(__clang__) #pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wmissing-prototypes" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #endif @@ -190,15 +192,15 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) ImVec4* colors = style->Colors; colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); - colors[ImGuiCol_TextDisabled] = ImVec4(0.58f, 0.58f, 0.58f, 1.00f); - colors[ImGuiCol_WindowBg] = ImVec4(0.15f, 0.15f, 0.15f, 1.00f); - colors[ImGuiCol_ChildBg] = ImVec4(0.17f, 0.17f, 0.17f, 0.00f); - colors[ImGuiCol_PopupBg] = ImVec4(0.14f, 0.14f, 0.14f, 0.94f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f); + colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_FrameBg] = ImVec4(0.10f, 0.10f, 0.10f, 1.00f); - colors[ImGuiCol_FrameBgHovered] = ImVec4(0.19f, 0.25f, 0.31f, 1.00f); - colors[ImGuiCol_FrameBgActive] = ImVec4(0.21f, 0.33f, 0.47f, 1.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); @@ -235,9 +237,9 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); - colors[ImGuiCol_TableHeaderBg] = ImVec4(0.28f, 0.28f, 0.29f, 1.00f); - colors[ImGuiCol_TableBorderStrong] = ImVec4(0.40f, 0.40f, 0.45f, 1.00f); // Prefer using Alpha=1.0 here - colors[ImGuiCol_TableBorderLight] = ImVec4(0.32f, 0.32f, 0.34f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); // Prefer using Alpha=1.0 here + colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); // Prefer using Alpha=1.0 here colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f); colors[ImGuiCol_TextLink] = colors[ImGuiCol_HeaderActive]; @@ -250,6 +252,7 @@ void ImGui::StyleColorsDark(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f); + colors[ImGuiCol_WindowShadow] = ImVec4(0.08f, 0.08f, 0.08f, 0.35f); } void ImGui::StyleColorsClassic(ImGuiStyle* dst) @@ -318,6 +321,7 @@ void ImGui::StyleColorsClassic(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); + colors[ImGuiCol_WindowShadow] = ImVec4(0.08f, 0.08f, 0.08f, 0.35f); } // Those light colors are better suited with a thicker font than the default one + FrameBorder @@ -336,9 +340,9 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f); - colors[ImGuiCol_TitleBg] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); - colors[ImGuiCol_TitleBgActive] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); - colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.43f); + colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f); colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f); @@ -387,6 +391,31 @@ void ImGui::StyleColorsLight(ImGuiStyle* dst) colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); + colors[ImGuiCol_WindowShadow] = ImVec4(0.08f, 0.08f, 0.08f, 0.35f); +} + +//----------------------------------------------------------------------------- +// [SECTION] ImFontAtlasShadowTexConfig +//----------------------------------------------------------------------------- + +void ImFontAtlasShadowTexConfig::SetupDefaults() +{ + TexCornerSize = 16; + TexEdgeSize = 1; + TexFalloffPower = 4.8f; + TexDistanceFieldOffset = 3.8f; + TexBlur = true; +} + +int ImFontAtlasShadowTexConfig::CalcConvexTexWidth() const +{ + // We have to pad the texture enough that we don't go off the edges when we expand the corner triangles + return (int)((TexCornerSize / ImCos(IM_PI * 0.25f)) + (GetConvexTexPadding() * 2)); +} + +int ImFontAtlasShadowTexConfig::CalcConvexTexHeight() const +{ + return CalcConvexTexWidth(); // Same value } //----------------------------------------------------------------------------- @@ -461,8 +490,7 @@ void ImDrawList::_ResetForNewFrame() CmdBuffer.resize(0); IdxBuffer.resize(0); VtxBuffer.resize(0); - Flags = _Data->InitialDrawFlags; - IM_ASSERT((Flags & ~ImDrawFlags_AllowInFrameScope_) == 0); + Flags = _Data->InitialFlags; memset(&_CmdHeader, 0, sizeof(_CmdHeader)); _VtxCurrentIdx = 0; _VtxWritePtr = NULL; @@ -470,7 +498,6 @@ void ImDrawList::_ResetForNewFrame() _ClipRectStack.resize(0); _TextureStack.resize(0); _CallbacksDataBuf.resize(0); - _DrawFlagsStack.clear(); _Path.resize(0); _Splitter.Clear(); CmdBuffer.push_back(ImDrawCmd()); @@ -482,14 +509,13 @@ void ImDrawList::_ClearFreeMemory() CmdBuffer.clear(); IdxBuffer.clear(); VtxBuffer.clear(); - Flags = ImDrawFlags_None; + Flags = ImDrawListFlags_None; _VtxCurrentIdx = 0; _VtxWritePtr = NULL; _IdxWritePtr = NULL; _ClipRectStack.clear(); _TextureStack.clear(); _CallbacksDataBuf.clear(); - _DrawFlagsStack.clear(); _Path.clear(); _Splitter.ClearFreeMemory(); } @@ -713,26 +739,6 @@ void ImDrawList::PopTexture() _OnChangedTexture(); } -// IMPORTANT: currently limited to 3 deep -void ImDrawList::PushDrawFlag(ImDrawFlags flags, bool enabled) -{ - IM_ASSERT((flags & ~ImDrawFlags_AllowInPushScope_) == 0); - IM_ASSERT((flags & ImDrawFlags_StrokeMask_) == 0 || (flags & ImDrawFlags_StrokeMask_) == ImDrawFlags_StrokeLegacy); - IM_ASSERT_USER_ERROR_RET(_DrawFlagsStack.Size < _DrawFlagsStack.capacity(), "PushDrawFlag() has a depth limit. Contact us."); - _DrawFlagsStack.push_back(Flags); - if (enabled) - Flags |= flags; - else - Flags &= ~flags; -} - -void ImDrawList::PopDrawFlag() -{ - IM_ASSERT_USER_ERROR_RET(_DrawFlagsStack.Size > 0, "Calling PopDrawFlag() too many times!"); - Flags = _DrawFlagsStack.back(); - _DrawFlagsStack.pop_back(); -} - // This is used by ImGui::PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture(). void ImDrawList::_SetTexture(ImTextureRef tex_ref) { @@ -748,10 +754,8 @@ void ImDrawList::_SetPixelDensity(float pixel_density) IM_ASSERT(pixel_density > 0.0f); _FringeScale = 1.0f / pixel_density; _InvFringeScale = pixel_density; - _FringeScaleIsInteger = ImIsTruncated(_InvFringeScale); } -IM_MSVC_RUNTIME_CHECKS_OFF // Reserve space for a number of vertices and indices. // You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or // submit the intermediate results. PrimUnreserve() can be used to release unused allocations. @@ -759,7 +763,7 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) { // Large mesh support (when enabled) IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0); - if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawFlags_UseVtxOffset)) + if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset)) { // FIXME: In theory we should be testing that vtx_count <64k here. // In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us @@ -791,26 +795,6 @@ void ImDrawList::PrimUnreserve(int idx_count, int vtx_count) IdxBuffer.shrink(IdxBuffer.Size - idx_count); } -// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. -// We avoid using the 'do { } while (false)` idiom in those macros as they typically have overhead in debug builds. -#define IM_APPEND_VTX(PX, PY, UV, COL) \ - { \ - _VtxWritePtr->pos.x = PX; \ - _VtxWritePtr->pos.y = PY; \ - _VtxWritePtr->uv = UV; \ - _VtxWritePtr->col = COL; \ - _VtxWritePtr++; \ - _VtxCurrentIdx++; \ - } (void)0 - -#define IM_APPEND_TRI(a, b, c) \ - { \ - _IdxWritePtr[0] = (ImDrawIdx)(a); \ - _IdxWritePtr[1] = (ImDrawIdx)(b); \ - _IdxWritePtr[2] = (ImDrawIdx)(c); \ - _IdxWritePtr += 3; \ - } (void)0 - // Fully unrolled with inline call to keep our debug builds decently fast. void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) { @@ -856,24 +840,6 @@ void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, c _IdxWritePtr += 6; } -float ImDrawList::_CalculateCenterBiasedOffset(float thickness) -{ - // Old jumpy one. - // return IM_TRUNC(thickness * 0.5f / _FringeScale) * _FringeScale; - - // Calculate outside offset for stroke position ImDrawFlags_StrokeCenterBiased - // so that one side the of the line is always at pixel boundary. - // On integer thickness both sides of the line are on pixel boundary. - const float screen_thickness = thickness * _InvFringeScale; - const int s_thickness = (int)screen_thickness; - return ((float)(s_thickness / 2) + (s_thickness & 1) * (screen_thickness - s_thickness)) * _FringeScale; -} -IM_MSVC_RUNTIME_CHECKS_RESTORE - -// Check if R is considered to be worthy rounding. Can be only used within ImDrawList due to use of _FringeScale. -// FIXME-OPT: Given unused padding space in ImDrawList would it make sense to store 0.25f * _FringeScale? -#define IM_HAS_ROUNDING(RAD) ((RAD) >= (0.25f * _FringeScale)) - // On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds. // - Those macros expects l-values and need to be used as their own statement. // - Those macros are intentionally not surrounded by the 'do {} while (0)' idiom because even that translates to runtime with debug compilers. @@ -881,650 +847,357 @@ IM_MSVC_RUNTIME_CHECKS_RESTORE #define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366) #define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0 -// - The miter limit describes how much the miter cross section can be scaled before we turn it into a bevel instead. -// The minimum value of miter limit is 1.0, which translates to 180 (all corners are bevels), the higher the number, -// the closer to zero the angle is (never bevel a corner). The miter limit angle can be calculated as: -// miter_limit_angle = 2 * acos(1 / miter_limit) -// - We can use the miter limit angle to figure maximum number of beveled corners in a convex polygon, -// to prevent having allocate much extra memory (for a reasonable miter limit). -// (n - 2) * 360 > k * miter_limit_angle + (n - k) * 360 -// Where, n = number of corners in a polygon, k = beveled corners. Solved for k, simplifies to: -// k < 360 / (180 - miter_limit_angle) -// To find value strictly less than: -// max_bevels = k = floor(360/(180-miter_limit_angle)) -#define IM_POLYLINE_MITER_ANGLE_LIMIT (-0.9999619f) // Safeguard for miter corner calculation to avoid div by zero. cos(179.5) -#define IM_POLYLINE_MITER_LIMIT (4.0f) // (~29 deg corner) -#define IM_POLYLINE_CONVEX_POLY_MAX_BEVELS (2) // For miter value 4.0 - -// In debug builds the functions are likely not inlined, so inlined check is cheaper. -#if defined(DEBUG) || defined(_DEBUG) -#define IM_IS_TRUNCATED4(a, b, c, d) ((float)(int)(a) == (a)) && ((float)(int)(b) == (b)) && ((float)(int)(c) == (c)) && ((float)(int)(d) == (d)) -#define IM_IS_TRUNCATED(a) ((float)(int)(a) == (a)) -#else -#define IM_IS_TRUNCATED4(a, b, c, d) ImIsTruncated4(a, b, c, d) -#define IM_IS_TRUNCATED(a) ImIsTruncated(a) -#endif - -IM_MSVC_RUNTIME_CHECKS_OFF -static ImU32 ImAlphaMultiply(ImU32 col, float alpha_mul) -{ - IM_ASSERT_PARANOID(alpha_mul >= 0.0f && alpha_mul < 1.0f); // We don't clamp! - ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; - a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range. - return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); -} - -// Select texture and adjust fringe size for specified line thickness. -void ImDrawList::_SelectLineTexture(float screen_thickness, ImVec2* out_uv0, ImVec2* out_uv1, float* out_fringe, ImDrawFlags flags) -{ - // We assume that the screen_thickness has been clamped to 1.0 by the caller. - IM_ASSERT_PARANOID(screen_thickness >= 1.0f); - - if (flags & ImDrawFlags_AALines) - { - // Handle the thickness between 1.0 - IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH]. - // We use super sampled textures in this range to make texture changes less noticeable. - // There are IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT textures, where 0 maps to 1.0 and IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT-1 maps to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4.0). - int texture_idx; - if (screen_thickness <= IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH) IM_LIKELY - texture_idx = (int)((screen_thickness - 1.0f) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 0.5f) + (IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); - else if (screen_thickness < (float)IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1.5f) IM_LIKELY - texture_idx = (int)(screen_thickness + 0.5f); - else - texture_idx = IM_DRAWLIST_TEX_LINES_WIDTH_MAX - 1; // Catches large values of screen_thickness (and +inf/NaN) that a ImMin() wouldn't. - - // Scale the fringe so that the texture matches the line thickness. - ImVec4 tex_uvs = _Data->TexUvLines[texture_idx]; - out_uv0->x = tex_uvs.x; - out_uv1->x = tex_uvs.y; - out_uv0->y = out_uv1->y = tex_uvs.z; - *out_fringe = _FringeScale * screen_thickness * tex_uvs.w; // tex_uvs.w = 1 / thickness - } - else - { - // For no anti-alias we use fully opaque texture, and no fringe expansion. - *out_uv0 = *out_uv1 = _Data->TexUvWhitePixel; - *out_fringe = 0.0f; - } -} - -#define _GetStrokePos(_FLAGS, _DEFAULT_STROKE_POS) (((_FLAGS) & ImDrawFlags_StrokeMask_) ? ((_FLAGS) & ImDrawFlags_StrokeMask_) : _DEFAULT_STROKE_POS) - -IM_MSVC_RUNTIME_CHECKS_RESTORE - -void ImDrawList::_AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags, float max_inner_offset) +// TODO: Thickness anti-aliased lines cap are missing their AA fringe. +// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds. +void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, float thickness, ImDrawFlags flags) { if (points_count < 2 || (col & IM_COL32_A_MASK) == 0) return; - float screen_thickness = thickness * _InvFringeScale; - if (screen_thickness < 1.0f) IM_UNLIKELY - { - if (screen_thickness < 1.0f / 255.0f) IM_UNLIKELY - return; - col = ImAlphaMultiply(col, screen_thickness); - screen_thickness = 1.0f; - thickness = _FringeScale; - } + const bool closed = (flags & ImDrawFlags_Closed) != 0; + const ImVec2 opaque_uv = _Data->TexUvWhitePixel; + const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw + const bool thick_line = (thickness > _FringeScale); // If this assert triggers on legacy code: // - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. // - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. // Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. - flags |= Flags; IM_ASSERT_USER_ERROR_RET((flags & ImDrawFlags_InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?"); - // Allocate data for temp buffers - _Data->TempBuffer.reserve_discard(points_count * 2); - ImVec2* normals = _Data->TempBuffer.Data; - float* sqr_lengths = (float*)(normals + points_count); - - // Calculate normals for each line segment - for (int i = 0; i < points_count - 1; i++) + if (Flags & ImDrawListFlags_AntiAliasedLines) { - float dx = points[i + 1].x - points[i].x; - float dy = points[i + 1].y - points[i].y; - const float d2 = dx * dx + dy * dy; - const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; - normals[i].x = -dy * inv_len; - normals[i].y = dx * inv_len; - sqr_lengths[i] = d2; - } - if ((flags & ImDrawFlags_Closed) != 0) - { - const float dx = points[0].x - points[points_count - 1].x; - const float dy = points[0].y - points[points_count - 1].y; - const float d2 = dx * dx + dy * dy; - const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; - normals[points_count - 1].x = -dy * inv_len; - normals[points_count - 1].y = dx * inv_len; - sqr_lengths[points_count - 1] = d2; - } - else - { - normals[points_count - 1] = normals[points_count - 2]; - sqr_lengths[points_count - 1] = 0.0f; - } + // Anti-aliased stroke + const float AA_SIZE = _FringeScale; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; - ImVec2 uv0, uv1; - float fringe; - _SelectLineTexture(screen_thickness, &uv0, &uv1, &fringe, flags); + // Thicknesses <1.0 should behave like thickness 1.0 + thickness = ImMax(thickness, 1.0f); + const int integer_thickness = (int)thickness; + const float fractional_thickness = thickness - integer_thickness; - const ImU32 col_trans = col & ~IM_COL32_A_MASK; + // Do we want to draw this line using a texture? + // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved. + // - If AA_SIZE is not 1.0f we cannot use the texture path. + const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f); - const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); - if (stroke_pos == ImDrawFlags_StrokeLegacy) - flags = (flags | ImDrawFlags_JoinMiter) & ~ImDrawFlags_AALineEnds; + // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off + IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)); - const bool closed = (flags & ImDrawFlags_Closed) != 0; - const bool miters_only = (flags & ImDrawFlags_JoinMiter) != 0; - const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; + const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12); + const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3); + PrimReserve(idx_count, vtx_count); - float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) - if (stroke_pos == ImDrawFlags_StrokeOutside) - thickness0 = thickness + fringe * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - thickness0 = _CalculateCenterBiasedOffset(thickness) + fringe * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeInside) - thickness0 = fringe * 0.5f; - float thickness1 = (thickness + fringe) - thickness0; + // Temporary buffer + // The first items are normals at each line point, then after that there are either 2 or 4 temp points for each line point + _Data->TempBuffer.reserve_discard(points_count * ((use_texture || !thick_line) ? 3 : 5)); + ImVec2* temp_normals = _Data->TempBuffer.Data; + ImVec2* temp_points = temp_normals + points_count; - int idx_count = 0; - int vtx_count = 0; - const int max_verts_per_point = miters_only ? 2 : 4; - const int max_tris_per_point = miters_only ? 2 : 5; - if (closed) - { - vtx_count = /*body*/points_count * max_verts_per_point + /*closing*/2; - idx_count = (/*body*/points_count * max_tris_per_point + /*closing*/2) * 3; - } - else - { - vtx_count = /*body*/(points_count - 2) * max_verts_per_point + /*caps*/(4 * 2); - idx_count = (/*body*/(points_count - 2) * max_tris_per_point + /*last seg*/2 + /*caps*/(2 * 2)) * 3; - } - PrimReserve(idx_count, vtx_count); - - const float ratio = thickness0 / (thickness0 + thickness1); // The points that use uv2 are placed directly on the path (offset = 0), calculate the texture position from stroke offsets. - const ImVec2 uv2(uv0.x + (uv1.x - uv0.x) * ratio, uv0.y); - - // Clamp inner offset and adjust texture coordinates to match the change. - // This is used by some of the convex shape rendering to avoid rendering artifacts when thickness is about to fill the whole shape. - if (thickness1 > max_inner_offset) - { - thickness1 = max_inner_offset; - const float s = (thickness0 + thickness1) / (thickness + fringe); - const float du = uv1.x - uv0.x; - uv1.x = uv0.x + du * s; - } - - const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. - const bool use_aa_ends = (flags & (ImDrawFlags_AALines | ImDrawFlags_AALineEnds)) == (ImDrawFlags_AALines | ImDrawFlags_AALineEnds); - - const int first_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); - int base_idx = (int)_VtxCurrentIdx; - - ImVec2 pa, pb, dir; - ImVec2 p1; - ImVec2 n1; - float len_sqr1; - - int point_idx = 0; - int point_end = points_count; - if (!closed) - { - // Start cap - point_idx++; - point_end--; - p1 = points[0]; - n1 = normals[0]; - len_sqr1 = sqr_lengths[0]; - - dir.x = n1.y; - dir.y = -n1.x; - if (flags & ImDrawFlags_CapSquare) + // Calculate normals (tangents) for each line segment + for (int i1 = 0; i1 < count; i1++) { - p1.x -= dir.x * thickness * 0.5f; - p1.y -= dir.y * thickness * 0.5f; + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; + float dx = points[i2].x - points[i1].x; + float dy = points[i2].y - points[i1].y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + temp_normals[i1].x = dy; + temp_normals[i1].y = -dx; } + if (!closed) + temp_normals[points_count - 1] = temp_normals[points_count - 2]; - if (!use_aa_ends) + // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point + if (use_texture || !thick_line) { - base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); - IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); - } - else - { - pa.x = p1.x - dir.x * half_aa; - pa.y = p1.y - dir.y * half_aa; - pb.x = p1.x + dir.x * half_aa; - pb.y = p1.y + dir.y * half_aa; + // [PATH 1] Texture-based lines (thick or non-thick) + // [PATH 2] Non texture-based lines (non-thick) - base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col_trans); - IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col_trans); + // The width of the geometry we need to draw - this is essentially pixels for the line itself, plus "one pixel" for AA. + // - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture + // (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code. + // - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to + // allow scaling geometry while preserving one-screen-pixel AA fringe). + const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE; - int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pb.x - n1.x * thickness0, pb.y - n1.y * thickness0, uv0, col); - IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1, uv1, col); - - // AA cap - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - base_idx = next_base_idx; - } - } - else - { - // Wrap around segment - p1 = points[points_count - 1]; - n1 = normals[points_count - 1]; - len_sqr1 = sqr_lengths[points_count - 1]; - - // This will be filled later, allocate space. - base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(0, 0, uv0, col); - IM_APPEND_VTX(0, 0, uv1, col); - } - - if (miters_only) - { - while (point_idx < point_end) - { - ImVec2 n0 = n1; - p1 = points[point_idx]; - n1 = normals[point_idx]; - - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); - const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; - const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; - - // Miter - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 2 - IM_APPEND_VTX(p1.x + miter_offset_x * thickness1, p1.y + miter_offset_y * thickness1, uv1, col); // 3 - - // Connect prev to next - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - - base_idx = next_base_idx; - - point_idx++; - } - } - else - { - while (point_idx < point_end) - { - ImVec2 n0 = n1; - float len_sqr0 = len_sqr1; - p1 = points[point_idx]; - n1 = normals[point_idx]; - len_sqr1 = sqr_lengths[point_idx]; - - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - const float sin_theta = n0.y * n1.x - n0.x * n1.y; - - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); - float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; - float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; - - const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; - - if (miter_distance_sqr > miter_distance_limit_sqr) + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend + if (!closed) { - // Clipped bevel + temp_points[0] = points[0] + temp_normals[0] * half_draw_size; + temp_points[1] = points[0] - temp_normals[0] * half_draw_size; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * half_draw_size; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * half_draw_size; + } - // Limit the inner miter offset to avoid overshooting. - const float ref_thickness = (sin_theta < 0.0f) ? thickness1 : thickness0; - const float ref_thickness_sqr = ref_thickness * ref_thickness; - const float limit_sqr = ImMax(ImMax(len_sqr0, len_sqr1), ref_thickness_sqr); - const float ref_miter_dist_sqr = miter_distance_sqr * ref_thickness_sqr; - if (ref_miter_dist_sqr > limit_sqr) + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment + { + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment + const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment + + // Average normals + float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; + float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area + dm_y *= half_draw_size; + + // Add temporary vertices for the outer edges + ImVec2* out_vtx = &temp_points[i2 * 2]; + out_vtx[0].x = points[i2].x + dm_x; + out_vtx[0].y = points[i2].y + dm_y; + out_vtx[1].x = points[i2].x - dm_x; + out_vtx[1].y = points[i2].y - dm_y; + + if (use_texture) { - const float scale = ImSqrt(limit_sqr / ref_miter_dist_sqr); - miter_offset_x *= scale; - miter_offset_y *= scale; - } - - float bn_x = n0.x + n1.x; - float bn_y = n0.y + n1.y; - IM_NORMALIZE2F_OVER_ZERO(bn_x, bn_y); - - const float side_offset = ((n0.x * bn_x + n0.y * bn_y) - 1.0f) / (n0.y * bn_x - n0.x * bn_y); - const float sd_x = bn_y * side_offset; - const float sd_y = -bn_x * side_offset; - - // Bevel - if (sin_theta < 0.0f) - { - IM_APPEND_VTX(p1.x - (bn_x + sd_x) * thickness0, p1.y - (bn_y + sd_y) * thickness0, uv0, col); // 2 - IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - (bn_x - sd_x) * thickness0, p1.y - (bn_y - sd_y) * thickness0, uv0, col); // 4 - IM_APPEND_VTX(p1.x + miter_offset_x * thickness1, p1.y + miter_offset_y * thickness1, uv1, col); // 5 - - // Connect prev to next - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 5); - IM_APPEND_TRI(base_idx + 0, base_idx + 5, base_idx + 1); - // Bevel - IM_APPEND_TRI(base_idx + 3, base_idx + 5, base_idx + 2); - IM_APPEND_TRI(base_idx + 3, base_idx + 2, base_idx + 4); - IM_APPEND_TRI(base_idx + 3, base_idx + 4, base_idx + 5); - base_idx = next_base_idx; + // Add indices for two triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri + _IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri + _IdxWritePtr += 6; } else { - IM_APPEND_VTX(p1.x + (bn_x + sd_x) * thickness1, p1.y + (bn_y + sd_y) * thickness1, uv1, col); // 2 - IM_APPEND_VTX(p1.x, p1.y, uv2, col); // 3 - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 4 - IM_APPEND_VTX(p1.x + (bn_x - sd_x) * thickness1, p1.y + (bn_y - sd_y) * thickness1, uv1, col); // 5 + // Add indexes for four triangles + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1 + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2 + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1 + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2 + _IdxWritePtr += 12; + } - // Connect prev to next - IM_APPEND_TRI(base_idx + 0, base_idx + 4, base_idx + 2); - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 1); - // Bevel - IM_APPEND_TRI(base_idx + 3, base_idx + 2, base_idx + 4); - IM_APPEND_TRI(base_idx + 3, base_idx + 4, base_idx + 5); - IM_APPEND_TRI(base_idx + 3, base_idx + 5, base_idx + 2); - base_idx = next_base_idx; + idx1 = idx2; + } + + // Add vertices for each point on the line + if (use_texture) + { + // If we're using textures we only need to emit the left/right edge vertices + ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness]; + /*if (fractional_thickness != 0.0f) // Currently always zero when use_texture==false! + { + const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1]; + tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp() + tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness; + tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness; + tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness; + }*/ + ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y); + ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w); + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge + _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = tex_uv1; _VtxWritePtr[1].col = col; // Right-side outer edge + _VtxWritePtr += 2; } } else { - // Miter - const int next_base_idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p1.x - miter_offset_x * thickness0, p1.y - miter_offset_y * thickness0, uv0, col); // 2 - IM_APPEND_VTX(p1.x + miter_offset_x * thickness1, p1.y + miter_offset_y * thickness1, uv1, col); // 3 - - // Connect prev to next - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - base_idx = next_base_idx; + // If we're not using a texture, we need the center vertex as well + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Center of line + _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge + _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge + _VtxWritePtr += 3; + } } - - point_idx++; - } - } - - // End cap - if (!closed) - { - p1 = points[points_count - 1]; - n1 = normals[points_count - 1]; - - // End cap - dir.x = n1.y; - dir.y = -n1.x; - if (flags & ImDrawFlags_CapSquare) - { - p1.x += dir.x * thickness * 0.5f; - p1.y += dir.y * thickness * 0.5f; - } - - if (!use_aa_ends) - { - IM_APPEND_VTX(p1.x - n1.x * thickness0, p1.y - n1.y * thickness0, uv0, col); - IM_APPEND_VTX(p1.x + n1.x * thickness1, p1.y + n1.y * thickness1, uv1, col); - - // Connect - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); } else { - pa.x = p1.x - dir.x * half_aa; - pa.y = p1.y - dir.y * half_aa; - pb.x = p1.x + dir.x * half_aa; - pb.y = p1.y + dir.y * half_aa; + // [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point + const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; - int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa.x - n1.x * thickness0, pa.y - n1.y * thickness0, uv0, col); - IM_APPEND_VTX(pa.x + n1.x * thickness1, pa.y + n1.y * thickness1, uv1, col); + // If line is not closed, the first and last points need to be generated differently as there are no normals to blend + if (!closed) + { + const int points_last = points_count - 1; + temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); + temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); + temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE); + temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness); + temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE); + } - IM_APPEND_VTX(pb.x - n1.x * thickness0, pb.y - n1.y * thickness0, uv0, col_trans); - IM_APPEND_VTX(pb.x + n1.x * thickness1, pb.y + n1.y * thickness1, uv1, col_trans); + // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges + // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps) + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment + for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment + { + const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment + const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment - // Connect - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - base_idx = next_base_idx; + // Average normals + float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; + float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE); + float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE); + float dm_in_x = dm_x * half_inner_thickness; + float dm_in_y = dm_y * half_inner_thickness; - // AA cap - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); + // Add temporary vertices + ImVec2* out_vtx = &temp_points[i2 * 4]; + out_vtx[0].x = points[i2].x + dm_out_x; + out_vtx[0].y = points[i2].y + dm_out_y; + out_vtx[1].x = points[i2].x + dm_in_x; + out_vtx[1].y = points[i2].y + dm_in_y; + out_vtx[2].x = points[i2].x - dm_in_x; + out_vtx[2].y = points[i2].y - dm_in_y; + out_vtx[3].x = points[i2].x - dm_out_x; + out_vtx[3].y = points[i2].y - dm_out_y; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2); + _IdxWritePtr += 18; + + idx1 = idx2; + } + + // Add vertices + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i * 4 + 0]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i * 4 + 1]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i * 4 + 2]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i * 4 + 3]; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr += 4; + } } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; } else { - // Connect the path. - VtxBuffer.Data[first_vtx_offset + 0] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 0]; - VtxBuffer.Data[first_vtx_offset + 1] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 1]; - } + // [PATH 4] Non texture-based, Non anti-aliased lines + const int idx_count = count * 6; + const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges + PrimReserve(idx_count, vtx_count); - // Restore unused memory - const int cur_idx_offset = (int)(_IdxWritePtr - IdxBuffer.Data); - const int cur_vtx_offset = (int)(_VtxWritePtr - VtxBuffer.Data); - const int remaining_idx_count = IdxBuffer.Size - cur_idx_offset; - const int remaining_vtx_count = VtxBuffer.Size - cur_vtx_offset; - IM_ASSERT_PARANOID(remaining_idx_count >= 0 && remaining_vtx_count >= 0); - PrimUnreserve(remaining_idx_count, remaining_vtx_count); + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; + const ImVec2& p1 = points[i1]; + const ImVec2& p2 = points[i2]; + + float dx = p2.x - p1.x; + float dy = p2.y - p1.y; + IM_NORMALIZE2F_OVER_ZERO(dx, dy); + dx *= (thickness * 0.5f); + dy *= (thickness * 0.5f); + + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3); + _IdxWritePtr += 6; + _VtxCurrentIdx += 4; + } + } } // - We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. // - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. -void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, ImDrawFlags flags) +void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col) { if (points_count < 3 || (col & IM_COL32_A_MASK) == 0) return; const ImVec2 uv = _Data->TexUvWhitePixel; - flags |= Flags; - if (flags & ImDrawFlags_AAFill) + + if (Flags & ImDrawListFlags_AntiAliasedFill) { - const float half_aa = _FringeScale * 0.5f; - ImU32 col_trans = col & ~IM_COL32_A_MASK; - const bool miters_only = (flags & ImDrawFlags_JoinMiter) != 0; - const float miter_distance_limit_sqr = IM_POLYLINE_MITER_LIMIT * IM_POLYLINE_MITER_LIMIT; - - const int idx_count = ((points_count - 2) + points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) * 3; - const int vtx_count = points_count * 2 + IM_POLYLINE_CONVEX_POLY_MAX_BEVELS; + // Anti-aliased Fill + const float AA_SIZE = _FringeScale; + const ImU32 col_trans = col & ~IM_COL32_A_MASK; + const int idx_count = (points_count - 2)*3 + points_count * 6; + const int vtx_count = (points_count * 2); PrimReserve(idx_count, vtx_count); - ImDrawVert* start_vtx_ptr = _VtxWritePtr; - ImDrawIdx* start_idx_ptr = _IdxWritePtr; - // Compute normals and segment lengths - _Data->TempBuffer.reserve_discard(points_count * 2); + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx + 1; + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1)); + _IdxWritePtr += 3; + } + + // Compute normals + _Data->TempBuffer.reserve_discard(points_count); ImVec2* temp_normals = _Data->TempBuffer.Data; - float* temp_sqr_lengths = (float*)(_Data->TempBuffer.Data + points_count); for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { const ImVec2& p0 = points[i0]; const ImVec2& p1 = points[i1]; float dx = p1.x - p0.x; float dy = p1.y - p0.y; - float d2 = dx * dx + dy * dy; - if (d2 > 0.0f) - { - const float inv_len = ImRsqrtPrecise(d2); - dx *= inv_len; - dy *= inv_len; - } + IM_NORMALIZE2F_OVER_ZERO(dx, dy); temp_normals[i0].x = dy; temp_normals[i0].y = -dx; - temp_sqr_lengths[i0] = d2; } - unsigned int vtx_inner_idx = _VtxCurrentIdx; - ImDrawVert* inner_vtx_ptr = _VtxWritePtr; - _VtxWritePtr += points_count; - _VtxCurrentIdx += points_count; - - unsigned int prev_outer_idx = 0; // This should be the index of the last vertex, but we don't know it yet. Will need to patch once we're done. - if (miters_only) + for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) { - for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) - { - const ImVec2 p1 = points[i1]; - const ImVec2 n0 = temp_normals[i0]; - const ImVec2 n1 = temp_normals[i1]; + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + float dm_x = (n0.x + n1.x) * 0.5f; + float dm_y = (n0.y + n1.y) * 0.5f; + IM_FIXNORMAL2F(dm_x, dm_y); + dm_x *= AA_SIZE * 0.5f; + dm_y *= AA_SIZE * 0.5f; - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); - const float miter_offset_x = (n0.x + n1.x) * miter_scale_factor * half_aa; - const float miter_offset_y = (n0.y + n1.y) * miter_scale_factor * half_aa; + // Add vertices + _VtxWritePtr[0].pos.x = (points[i1].x - dm_x); _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos.x = (points[i1].x + dm_x); _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; - // Inner - inner_vtx_ptr->pos.x = p1.x - miter_offset_x; - inner_vtx_ptr->pos.y = p1.y - miter_offset_y; - inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; - inner_vtx_ptr++; - - const unsigned int prev_inner_idx = vtx_inner_idx + i0; - const unsigned int inner_idx = vtx_inner_idx + i1; - const unsigned int outer_idx = _VtxCurrentIdx; - - // Outer - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv, col_trans); - // Connect with previous - IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); - IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); - - prev_outer_idx = outer_idx; - } + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); + _IdxWritePtr += 6; } - else - { - int bevel_count = 0; - for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++) - { - const ImVec2 p1 = points[i1]; - const ImVec2 n0 = temp_normals[i0]; - const ImVec2 n1 = temp_normals[i1]; - - // theta is the angle between two segments - const float cos_theta = n0.x * n1.x + n0.y * n1.y; - // miter offset formula is derived here: https://www.angusj.com/clipper2/Docs/Trigonometry.htm - const float cos_theta_clamped = ImMax(IM_POLYLINE_MITER_ANGLE_LIMIT, cos_theta); // Avoid div by 0. - const float miter_scale_factor = ImMin(1000.0f, 1.0f / (1.0f + cos_theta_clamped)); - float miter_offset_x = (n0.x + n1.x) * miter_scale_factor; - float miter_offset_y = (n0.y + n1.y) * miter_scale_factor; - - const float miter_distance_sqr = miter_offset_x * miter_offset_x + miter_offset_y * miter_offset_y; - const bool bevel = miter_distance_sqr > miter_distance_limit_sqr; - if (bevel) - { - // Limit inner bevel so that it is does not shoot out outside the polygon. - // (using ImMax is intentional: using min limited too much in Mikko's tests when you have short edge next to long one. - // The idea of that check is to keep that worst case overshoot no bigger than the polygon) - const float ref_thickness_sqr = half_aa * half_aa; - const float limit_sqr = ImMax(temp_sqr_lengths[i0], temp_sqr_lengths[i1]); - const float ref_miter_dist_sqr = miter_distance_sqr * ref_thickness_sqr; - if (ref_miter_dist_sqr > limit_sqr) - { - const float scale = ImSqrt(limit_sqr / ref_miter_dist_sqr); - miter_offset_x *= scale; - miter_offset_y *= scale; - } - } - - miter_offset_x *= half_aa; - miter_offset_y *= half_aa; - - // Inner - inner_vtx_ptr->pos.x = p1.x - miter_offset_x; - inner_vtx_ptr->pos.y = p1.y - miter_offset_y; - inner_vtx_ptr->uv = uv; inner_vtx_ptr->col = col; - inner_vtx_ptr++; - - const unsigned int prev_inner_idx = vtx_inner_idx + i0; - const unsigned int inner_idx = vtx_inner_idx + i1; - unsigned int outer_idx = _VtxCurrentIdx; - - // Outer - if (bevel && bevel_count < IM_POLYLINE_CONVEX_POLY_MAX_BEVELS) IM_UNLIKELY - { - // Because the polygon is convex, we know the maximum number of bevel corners we can hit (which is very small number). - // We keep track of them just in case the calculations disagree. - bevel_count++; - - IM_APPEND_VTX(p1.x + n0.x * half_aa, p1.y + n0.y * half_aa, uv, col_trans); - IM_APPEND_VTX(p1.x + n1.x * half_aa, p1.y + n1.y * half_aa, uv, col_trans); - // Connect with previous - IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); - IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); - // Fill bevel - IM_APPEND_TRI(outer_idx, outer_idx + 1, inner_idx); - outer_idx++; - } - else - { - IM_APPEND_VTX(p1.x + miter_offset_x, p1.y + miter_offset_y, uv, col_trans); - // Connect with previous - IM_APPEND_TRI(prev_outer_idx, outer_idx, inner_idx); - IM_APPEND_TRI(prev_outer_idx, inner_idx, prev_inner_idx); - } - - prev_outer_idx = outer_idx; - } - } - - // Patch first segment to wrap around - start_idx_ptr[0] = (ImDrawIdx)prev_outer_idx; - start_idx_ptr[3] = (ImDrawIdx)prev_outer_idx; - - // Add indices for fill - for (int i = 2; i < points_count; i++) - IM_APPEND_TRI(vtx_inner_idx, vtx_inner_idx + i - 1, vtx_inner_idx + i); - - const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); - const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); - IM_ASSERT(idx_used <= idx_count && vtx_used <= vtx_count); - if (idx_used < idx_count || vtx_used < vtx_count) - PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); + _VtxCurrentIdx += (ImDrawIdx)vtx_count; } else { // Non Anti-aliased Fill - const int idx_count = (points_count - 2) * 3; + const int idx_count = (points_count - 2)*3; const int vtx_count = points_count; PrimReserve(idx_count, vtx_count); - int base_idx = _VtxCurrentIdx; for (int i = 0; i < vtx_count; i++) - IM_APPEND_VTX(points[i].x, points[i].y, uv, col); + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } for (int i = 2; i < points_count; i++) - IM_APPEND_TRI(base_idx, base_idx + i - 1, base_idx + i); + { + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; } } -// Calculates arc step and step count for 90 degree arc. The calculated arc step will complete a 90 degree arc when stepped arc_step_count times. -IM_MSVC_RUNTIME_CHECKS_OFF -static void CalcCornerArcStepAndCount(int segment_count, int& arc_step, int& arc_step_count) -{ - arc_step = ImClamp(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / segment_count, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); - arc_step_count = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step; - if ((arc_step * arc_step_count) != (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4)) // Make sure that the arc step can iterate 90 degree arc. - arc_step = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) / arc_step_count; -} -IM_MSVC_RUNTIME_CHECKS_RESTORE - void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step) { - if (!IM_HAS_ROUNDING(radius)) + if (radius < 0.5f) { _Path.push_back(center); return; @@ -1532,17 +1205,10 @@ void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_ // Calculate arc auto segment step size if (a_step <= 0) - { - // Calculate step size using the common function. No need to clamp, the step is already in range. - const int auto_seg_count = _CalcCircleAutoSegmentCount(radius); - int arc_step_count; - CalcCornerArcStepAndCount(auto_seg_count, a_step, arc_step_count); - } - else - { - // Make sure we never do steps larger than one quarter of the circle - a_step = ImClamp(a_step, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); - } + a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius); + + // Make sure we never do steps larger than one quarter of the circle + a_step = ImClamp(a_step, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4); const int sample_range = ImAbs(a_max_sample - a_min_sample); const int a_next_step = a_step; @@ -1623,7 +1289,7 @@ void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_ void ImDrawList::_PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments) { - if (!IM_HAS_ROUNDING(radius)) + if (radius < 0.5f) { _Path.push_back(center); return; @@ -1642,7 +1308,7 @@ void ImDrawList::_PathArcToN(const ImVec2& center, float radius, float a_min, fl // 0: East, 3: South, 6: West, 9: North, 12: East void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12) { - if (!IM_HAS_ROUNDING(radius)) + if (radius < 0.5f) { _Path.push_back(center); return; @@ -1652,7 +1318,7 @@ void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments) { - if (!IM_HAS_ROUNDING(radius)) + if (radius < 0.5f) { _Path.push_back(center); return; @@ -1666,25 +1332,16 @@ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, floa // Automatic segment count if (radius <= _Data->ArcFastRadiusCutoff) - { + { const bool a_is_reverse = a_max < a_min; - // Calculate number of segments per circle. - // First we calculate the step count as usual, then match to the precomputed directions. - // This will give us the spacing between the samples (step), and how many segments to use in total for a full circle. - const int auto_seg_count = _CalcCircleAutoSegmentCount(radius); - int arc_step, arc_step_count; - CalcCornerArcStepAndCount(auto_seg_count, arc_step, arc_step_count); - const int arc_seg_count = arc_step_count * 4; // Seg count for full circle. - // We are going to use precomputed values for mid samples. // Determine first and last sample in lookup table that belong to the arc. - // In first step we use the coarser segment count, and after rounding, convert back to the precomputed array index. - const float a_min_sample_f = arc_seg_count * a_min / (IM_PI * 2.0f); - const float a_max_sample_f = arc_seg_count * a_max / (IM_PI * 2.0f); + const float a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0f); + const float a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0f); - const int a_min_sample = (a_is_reverse ? (int)ImFloor(a_min_sample_f) : (int)ImCeil(a_min_sample_f)) * arc_step; - const int a_max_sample = (a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloor(a_max_sample_f)) * arc_step; + const int a_min_sample = a_is_reverse ? (int)ImFloor(a_min_sample_f) : (int)ImCeil(a_min_sample_f); + const int a_max_sample = a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloor(a_max_sample_f); const int a_mid_samples = a_is_reverse ? ImMax(a_min_sample - a_max_sample, 0) : ImMax(a_max_sample - a_min_sample, 0); const float a_min_segment_angle = a_min_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX; @@ -1696,7 +1353,7 @@ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, floa if (a_emit_start) _Path.push_back(ImVec2(center.x + ImCos(a_min) * radius, center.y + ImSin(a_min) * radius)); if (a_mid_samples > 0) - _PathArcToFastEx(center, radius, a_min_sample, a_max_sample, arc_step); + _PathArcToFastEx(center, radius, a_min_sample, a_max_sample, 0); if (a_emit_end) _Path.push_back(ImVec2(center.x + ImCos(a_max) * radius, center.y + ImSin(a_max) * radius)); } @@ -1828,16 +1485,15 @@ void ImDrawList::PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDrawFlags flags) { - const bool has_rounding = IM_HAS_ROUNDING(rounding); - if (has_rounding) + if (rounding >= 0.5f) { - if ((flags & ImDrawFlags_RoundMask_) == 0) - flags |= ImDrawFlags_RoundAll; + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; - rounding = ImMin(rounding, ImFabs(b.x - a.x) * (((flags & ImDrawFlags_RoundTop) == ImDrawFlags_RoundTop) || ((flags & ImDrawFlags_RoundBottom) == ImDrawFlags_RoundBottom) ? 0.5f : 1.0f) - 1.0f); - rounding = ImMin(rounding, ImFabs(b.y - a.y) * (((flags & ImDrawFlags_RoundLeft) == ImDrawFlags_RoundLeft) || ((flags & ImDrawFlags_RoundRight) == ImDrawFlags_RoundRight) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(b.x - a.x) * (((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f) - 1.0f); + rounding = ImMin(rounding, ImFabs(b.y - a.y) * (((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f) - 1.0f); } - if (!has_rounding || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { PathLineTo(a); PathLineTo(ImVec2(b.x, a.y)); @@ -1846,10 +1502,10 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } else { - const float rounding_tl = (flags & ImDrawFlags_RoundTopLeft) ? rounding : 0.0f; - const float rounding_tr = (flags & ImDrawFlags_RoundTopRight) ? rounding : 0.0f; - const float rounding_br = (flags & ImDrawFlags_RoundBottomRight) ? rounding : 0.0f; - const float rounding_bl = (flags & ImDrawFlags_RoundBottomLeft) ? rounding : 0.0f; + const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? rounding : 0.0f; + const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? rounding : 0.0f; + const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? rounding : 0.0f; + const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? rounding : 0.0f; PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9); PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12); PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3); @@ -1857,777 +1513,71 @@ void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDr } } -void ImDrawList::_AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) -{ - if ((col & IM_COL32_A_MASK) == 0) IM_UNLIKELY - return; - - float screen_thickness = thickness * _InvFringeScale; - if (screen_thickness < 1.0f) IM_UNLIKELY - { - if (screen_thickness < 1.0f / 255.0f) IM_UNLIKELY - return; - col = ImAlphaMultiply(col, screen_thickness); - screen_thickness = 1.0f; - thickness = _FringeScale; - } - - flags |= Flags; - ImVec2 uv0, uv1; - float fringe; - _SelectLineTexture(screen_thickness, &uv0, &uv1, &fringe, flags); - - float dir_x = p2.x - p1.x; - float dir_y = p2.y - p1.y; - const float d2 = dir_x * dir_x + dir_y * dir_y; - const float inv_len = (d2 > 0.0f) ? ImRsqrtPrecise(d2) : 0.0f; - dir_x *= inv_len; - dir_y *= inv_len; - const float norm_x = -dir_y; - const float norm_y = dir_x; - - const ImU32 col_trans = col & ~IM_COL32_A_MASK; - - const ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); - if (stroke_pos == ImDrawFlags_StrokeLegacy) - flags = (flags | ImDrawFlags_JoinMiter) & ~ImDrawFlags_AALineEnds; - - float thickness0 = (thickness + fringe) * 0.5f; // Center (or legacy) - if (stroke_pos == ImDrawFlags_StrokeOutside) - thickness0 = thickness + fringe * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - thickness0 = _CalculateCenterBiasedOffset(thickness) + fringe * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeInside) - thickness0 = fringe * 0.5f; - const float thickness1 = (thickness + fringe) - thickness0; - - const float ratio = thickness0 / (thickness0 + thickness1); // The points using uv2 are placed on the path, calculate the position from stroke offsets. - const ImVec2 uv2(uv0.x + (uv1.x - uv0.x) * ratio, uv0.y); - - const float half_aa = _FringeScale * 0.5f; // Used for end caps, does not use "fringe" since end cap AA is not using the texture. - const bool use_aa_ends = (flags & (ImDrawFlags_AALines | ImDrawFlags_AALineEnds)) == (ImDrawFlags_AALines | ImDrawFlags_AALineEnds); - - if (!use_aa_ends) - PrimReserve(2*3, 4); - else - PrimReserve(6*3, 8); - - int base_idx = (int)_VtxCurrentIdx; - - float p1_x = p1.x; - float p1_y = p1.y; - float p2_x = p2.x; - float p2_y = p2.y; - if (flags & ImDrawFlags_CapSquare) - { - const float half_thickness = thickness * 0.5f; - p1_x -= dir_x * half_thickness; - p1_y -= dir_y * half_thickness; - p2_x += dir_x * half_thickness; - p2_y += dir_y * half_thickness; - } - - // Start cap - if (!use_aa_ends) - { - base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(p1_x - norm_x * thickness0, p1_y - norm_y * thickness0, uv0, col); - IM_APPEND_VTX(p1_x + norm_x * thickness1, p1_y + norm_y * thickness1, uv1, col); - IM_APPEND_VTX(p2_x - norm_x * thickness0, p2_y - norm_y * thickness0, uv0, col); - IM_APPEND_VTX(p2_x + norm_x * thickness1, p2_y + norm_y * thickness1, uv1, col); - - // Connect - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - } - else - { - // Start - float pa_x = p1_x - dir_x * half_aa; - float pa_y = p1_y - dir_y * half_aa; - float pb_x = p1_x + dir_x * half_aa; - float pb_y = p1_y + dir_y * half_aa; - - base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa_x - norm_x * thickness0, pa_y - norm_y * thickness0, uv0, col_trans); - IM_APPEND_VTX(pa_x + norm_x * thickness1, pa_y + norm_y * thickness1, uv1, col_trans); - - int next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pb_x - norm_x * thickness0, pb_y - norm_y * thickness0, uv0, col); - IM_APPEND_VTX(pb_x + norm_x * thickness1, pb_y + norm_y * thickness1, uv1, col); - - // AA cap - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - base_idx = next_base_idx; - - // End - pa_x = p2_x - dir_x * half_aa; - pa_y = p2_y - dir_y * half_aa; - pb_x = p2_x + dir_x * half_aa; - pb_y = p2_y + dir_y * half_aa; - - next_base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(pa_x - norm_x * thickness0, pa_y - norm_y * thickness0, uv0, col); - IM_APPEND_VTX(pa_x + norm_x * thickness1, pa_y + norm_y * thickness1, uv1, col); - IM_APPEND_VTX(pb_x - norm_x * thickness0, pb_y - norm_y * thickness0, uv0, col_trans); - IM_APPEND_VTX(pb_x + norm_x * thickness1, pb_y + norm_y * thickness1, uv1, col_trans); - - // Connect - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - base_idx = next_base_idx; - - // AA cap - IM_APPEND_TRI(base_idx + 0, base_idx + 2, base_idx + 3); - IM_APPEND_TRI(base_idx + 0, base_idx + 3, base_idx + 1); - } -} - -void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness, ImDrawFlags flags) +void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - - flags |= Flags; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeCenter); - if (stroke_pos == ImDrawFlags_StrokeLegacy) - { - _AddLine(ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f), col, thickness, flags); - return; - } - - _AddLine(p1, p2, col, thickness, flags); + const ImVec2 points[2] = { ImVec2(p1.x + 0.5f, p1.y + 0.5f), ImVec2(p2.x + 0.5f, p2.y + 0.5f) }; + AddPolyline(points, 2, col, thickness); } -// AddLineH(10, 20, 5, col, 1.0f) == AddLine( {10,5.5}, {20,5.5}, col, 1.0f) -// == AddLine( {10,5}, {20,5}, col, 1.0f, ImDrawFlags_StrokeLegacy); // or before 1.93.0 -// Thickness extend inside/bottom by default. Faster than equivalent AddLine() call. -void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness, ImDrawFlags flags) +void ImDrawList::AddLineH(float min_x, float max_x, float y, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - - flags |= Flags; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (stroke_pos == ImDrawFlags_StrokeLegacy) - { - _AddLine(ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f), col, thickness, flags); - return; - } - - float top_y = y; // Inside - if (stroke_pos == ImDrawFlags_StrokeCenter) - top_y -= thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - top_y -= _CalculateCenterBiasedOffset(thickness); - else if (stroke_pos == ImDrawFlags_StrokeOutside) - top_y -= thickness; - - const bool is_truncated = IM_IS_TRUNCATED4(min_x, max_x, top_y, thickness); - if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_CapSquare) == 0) - { - if (thickness < _FringeScale) IM_UNLIKELY - { - if (thickness < (1.0f / 255.0f) * _FringeScale) - return; - col = ImAlphaMultiply(col, thickness * _InvFringeScale); - thickness = _FringeScale; - } - - // For pixel aligned case, use simple rectangle. - PrimReserve(6, 4); - PrimRect(ImVec2(min_x, top_y), ImVec2(max_x, top_y + thickness), col); - } - else - { - // Replace stroke pos with the already calculated one, as AddPolyline() default is different. - flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; - - // For generic case use line, since it needs less triangles than AA rectangle. - _AddLine(ImVec2(min_x, y), ImVec2(max_x, y), col, thickness, flags); - } + const ImVec2 points[2] = { ImVec2(min_x + 0.5f, y + 0.5f), ImVec2(max_x + 0.5f, y + 0.5f) }; // Same as AddLine() above. + AddPolyline(points, 2, col, thickness); } -// AddLineV(5, 10, 20, col, 1.0f) == AddLine( {5.5,10}, {5.5,20}, col, 1.0f) -// == AddLine( {5,10}, {5,20}, col, 1.0f, ImDrawFlags_StrokeLegacy); // or before 1.93.0 -// Thickness extend inside/right by default. Faster than equivalent AddLine() call. -void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness, ImDrawFlags flags) +void ImDrawList::AddLineV(float x, float min_y, float max_y, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - - flags |= Flags; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (stroke_pos == ImDrawFlags_StrokeLegacy) - { - _AddLine(ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f), col, thickness, flags); - return; - } - - float left_x = x; // Inside - if (stroke_pos == ImDrawFlags_StrokeCenter) - left_x -= thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - left_x -= _CalculateCenterBiasedOffset(thickness); - else if (stroke_pos == ImDrawFlags_StrokeOutside) - left_x -= thickness; - - const bool is_truncated = IM_IS_TRUNCATED4(left_x, min_y, max_y, thickness); - if (_FringeScaleIsInteger && is_truncated && (flags & ImDrawFlags_CapSquare) == 0) - { - if (thickness < _FringeScale) IM_UNLIKELY - { - if (thickness < (1.0f / 255.0f) * _FringeScale) - return; - col = ImAlphaMultiply(col, thickness * _InvFringeScale); - thickness = _FringeScale; - } - - // For pixel aligned case, use simple rectangle. - PrimReserve(6, 4); - PrimRect(ImVec2(left_x, min_y), ImVec2(left_x + thickness, max_y), col); - } - else - { - // Replace stroke pos with the already calculated one, as AddPolyline() default is different. - flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; - - // For generic case use line, since it needs less triangles than AA rectangle. - // Drawing for bottom to top, so that the inside stroke pos expands to right. - _AddLine(ImVec2(x, max_y), ImVec2(x, min_y), col, thickness, flags); - } -} - -void ImDrawList::_AddRectBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, float t, const ImVec4& tex_uvs, ImDrawFlags flags) -{ - const ImVec2 uv_tl(tex_uvs.x, tex_uvs.y); - const ImVec2 uv_tr(tex_uvs.z, tex_uvs.y); - const ImVec2 uv_br(tex_uvs.z, tex_uvs.w); - const ImVec2 uv_bl(tex_uvs.x, tex_uvs.w); - - const int idx_allocated = 8 * 2 * 3; - const int vtx_allocated = 8 * 4; - PrimReserve(idx_allocated, vtx_allocated); - ImDrawVert* start_vtx_ptr = _VtxWritePtr; - ImDrawIdx* start_idx_ptr = _IdxWritePtr; - - if (flags & ImDrawFlags_RoundTopLeft) - { - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p_min.x, p_min.y, uv_tl, col); - IM_APPEND_VTX(p_min.x + r, p_min.y, uv_tr, col); - IM_APPEND_VTX(p_min.x + r, p_min.y + r, uv_br, col); - IM_APPEND_VTX(p_min.x, p_min.y + r, uv_bl, col); - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - } - - if (flags & ImDrawFlags_RoundTopRight) - { - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p_max.x - r, p_min.y, uv_tr, col); - IM_APPEND_VTX(p_max.x, p_min.y, uv_tl, col); - IM_APPEND_VTX(p_max.x, p_min.y + r, uv_bl, col); - IM_APPEND_VTX(p_max.x - r, p_min.y + r, uv_br, col); - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - } - - if (flags & ImDrawFlags_RoundBottomRight) - { - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p_max.x - r, p_max.y - r, uv_br, col); - IM_APPEND_VTX(p_max.x, p_max.y - r, uv_bl, col); - IM_APPEND_VTX(p_max.x, p_max.y, uv_tl, col); - IM_APPEND_VTX(p_max.x - r, p_max.y, uv_tr, col); - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - } - - if (flags & ImDrawFlags_RoundBottomLeft) - { - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p_min.x, p_max.y - r, uv_bl, col); - IM_APPEND_VTX(p_min.x + r, p_max.y - r, uv_br, col); - IM_APPEND_VTX(p_min.x + r, p_max.y, uv_tr, col); - IM_APPEND_VTX(p_min.x, p_max.y, uv_tl, col); - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - } - - const float r_tl = (flags & ImDrawFlags_RoundTopLeft) ? r : 0; - const float r_tr = (flags & ImDrawFlags_RoundTopRight) ? r : 0; - const float r_br = (flags & ImDrawFlags_RoundBottomRight) ? r : 0; - const float r_bl = (flags & ImDrawFlags_RoundBottomLeft) ? r : 0; - const ImVec2 opaque_uv = _Data->TexUvWhitePixel; - - { - // Top - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - const float x0 = p_min.x + r_tl; - const float x1 = p_max.x - r_tr; - IM_APPEND_VTX(x0, p_min.y, opaque_uv, col); - IM_APPEND_VTX(x1, p_min.y, opaque_uv, col); - IM_APPEND_VTX(x1, p_min.y + t, opaque_uv, col); - IM_APPEND_VTX(x0, p_min.y + t, opaque_uv, col); - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - } - { - // Left - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - const float y0 = p_min.y + ImMax(r_tl, t); - const float y1 = p_max.y - ImMax(r_bl, t); - IM_APPEND_VTX(p_min.x, y0, opaque_uv, col); - IM_APPEND_VTX(p_min.x + t, y0, opaque_uv, col); - IM_APPEND_VTX(p_min.x + t, y1, opaque_uv, col); - IM_APPEND_VTX(p_min.x, y1, opaque_uv, col); - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - } - { - // Right - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - const float y0 = p_min.y + ImMax(r_tr, t); - const float y1 = p_max.y - ImMax(r_br, t); - IM_APPEND_VTX(p_max.x - t, y0, opaque_uv, col); - IM_APPEND_VTX(p_max.x, y0, opaque_uv, col); - IM_APPEND_VTX(p_max.x, y1, opaque_uv, col); - IM_APPEND_VTX(p_max.x - t, y1, opaque_uv, col); - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - } - { - // Bottom - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - const float x0 = p_min.x + r_bl; - const float x1 = p_max.x - r_br; - IM_APPEND_VTX(x0, p_max.y - t, opaque_uv, col); - IM_APPEND_VTX(x1, p_max.y - t, opaque_uv, col); - IM_APPEND_VTX(x1, p_max.y, opaque_uv, col); - IM_APPEND_VTX(x0, p_max.y, opaque_uv, col); - IM_APPEND_TRI(idx + 0, idx + 1, idx + 2); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - } - - const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); - const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); - IM_ASSERT_PARANOID(idx_used <= idx_allocated && vtx_used <= vtx_allocated); - if (idx_used < idx_allocated || vtx_used < vtx_allocated) - PrimUnreserve(idx_allocated - idx_used, vtx_allocated - vtx_used); -} - -// Draws rounded rectangle where thickness > rounding. If rendered using the regular polyline, the stroke will fold and leave artifacts on the corners if rendered with transparency. -// The stroke is positioned inside the rectangle. -void ImDrawList::_AddRectTinyRounding(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) -{ - float screen_thickness = thickness * _InvFringeScale; - if (screen_thickness < 1.0f) IM_UNLIKELY - { - if (screen_thickness < 1.0f / 255.0f) IM_UNLIKELY - return; - col = ImAlphaMultiply(col, screen_thickness); - screen_thickness = 1.0f; - thickness = _FringeScale; - } - - flags |= Flags; - ImVec2 outer_uv, inner_uv; - float fringe; - _SelectLineTexture(screen_thickness, &outer_uv, &inner_uv, &fringe, flags); - - const int auto_seg_count = _CalcCircleAutoSegmentCount(rounding); - int arc_step, arc_step_count; - CalcCornerArcStepAndCount(auto_seg_count, arc_step, arc_step_count); - const int arc_point_count = arc_step_count + 1; - - int vtx_count = (2 + arc_point_count) * 4 + 3; - int idx_count = (4 + arc_point_count - 1) * 4 * 3; - - PrimReserve(idx_count, vtx_count); - ImDrawVert* start_vtx_ptr = _VtxWritePtr; - ImDrawIdx* start_idx_ptr = _IdxWritePtr; - - static const ImVec2 corner_offset[4] = { {1,1}, {-1,1}, {-1,-1}, {1,-1} }; - static const ImDrawFlags corner_flags[4] = { ImDrawFlags_RoundTopLeft, ImDrawFlags_RoundTopRight, ImDrawFlags_RoundBottomRight, ImDrawFlags_RoundBottomLeft }; - const float half_fringe = fringe * 0.5f; - const ImVec2 corner_pos[4] = - { - ImVec2(p_min.x - half_fringe, p_min.y - half_fringe), - ImVec2(p_max.x + half_fringe, p_min.y - half_fringe), - ImVec2(p_max.x + half_fringe, p_max.y + half_fringe), - ImVec2(p_min.x - half_fringe, p_max.y + half_fringe) - }; - thickness += fringe; - rounding += half_fringe; - - const float stem_offset = ImMin(rounding, thickness); // The function might get called with rounding slightly bigger than thickness, which is ok, but we should keep the stem inside the shape. - const float ratio = stem_offset / thickness; - const ImVec2 stem_uv(outer_uv.x + (inner_uv.x - outer_uv.x) * ratio, outer_uv.y); - - // Previous vertices, copied from the last vertices. - int base_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(0, 0, inner_uv, col); - IM_APPEND_VTX(0, 0, stem_uv, col); - IM_APPEND_VTX(0, 0, outer_uv, col); - - for (int corner = 0; corner < 4; corner++) - { - const float outer_x = corner_pos[corner].x; - const float outer_y = corner_pos[corner].y; - const float stem_x = outer_x + corner_offset[corner].x * stem_offset; - const float stem_y = outer_y + corner_offset[corner].y * stem_offset; - const float inner_x = outer_x + corner_offset[corner].x * thickness; - const float inner_y = outer_y + corner_offset[corner].y * thickness; - const bool is_rounded = (flags & corner_flags[corner]) != 0; - - const int arc_idx = (int)_VtxCurrentIdx; - if (is_rounded) - { - const float center_x = outer_x + corner_offset[corner].x * rounding; - const float center_y = outer_y + corner_offset[corner].y * rounding; - int a = (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4) * corner; - for (int i = 0; i < arc_point_count; i++) - { - IM_APPEND_VTX(center_x - _Data->ArcFastVtx[a].x * rounding, center_y - _Data->ArcFastVtx[a].y * rounding, outer_uv, col); - a = (a + arc_step) % IM_DRAWLIST_ARCFAST_TABLE_SIZE; - } - } - else - { - IM_APPEND_VTX(outer_x, outer_y, outer_uv, col); - } - - const int stem_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(stem_x, stem_y, stem_uv, col); - const int inner_idx = (int)_VtxCurrentIdx; - IM_APPEND_VTX(inner_x, inner_y, inner_uv, col); - - // Arc - if (is_rounded) - for (int i = 0; i < arc_point_count - 1; i++) - { - IM_APPEND_TRI(stem_idx, arc_idx + i, arc_idx + i + 1); - } - - // Connect with previous - IM_APPEND_TRI(base_idx + 0, arc_idx, stem_idx); - IM_APPEND_TRI(base_idx + 0, stem_idx, base_idx + 1); - IM_APPEND_TRI(base_idx + 1, stem_idx, inner_idx); - IM_APPEND_TRI(base_idx + 1, inner_idx, base_idx + 2); - - base_idx = stem_idx - 1; - } - - // Close - start_vtx_ptr[0] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 0]; - start_vtx_ptr[1] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 1]; - start_vtx_ptr[2] = VtxBuffer.Data[_CmdHeader.VtxOffset + base_idx + 2]; - - const int idx_used = (int)(_IdxWritePtr - start_idx_ptr); - const int vtx_used = (int)(_VtxWritePtr - start_vtx_ptr); - IM_ASSERT_PARANOID(idx_used <= idx_count && vtx_used <= vtx_count); - if (idx_used < idx_count || vtx_used < vtx_count) - PrimUnreserve(idx_count - idx_used, vtx_count - vtx_used); + const ImVec2 points[2] = { ImVec2(x + 0.5f, min_y + 0.5f), ImVec2(x + 0.5f, max_y + 0.5f) }; // Same as AddLine() above. + AddPolyline(points, 2, col, thickness); } // p_min = upper-left, p_max = lower-right +// Note we don't render 1 pixels sized rectangles properly. void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, float thickness, ImDrawFlags flags) { // If this assert triggers on legacy code: // - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. // - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. - // - 1.82.0 (2021/03): changed ImDrawCornerFlags to ImDrawFlags_RoundXXX values. + // - 1.82.0 (2021/03): changed ImDrawCornerFlags to ImDrawFlags_RoundCornersXXX values. // If you used hard-coded 1 to 15 or ~0 in flags to configure corner rounding use the new flags! - // - Hard coded support for ~0 == ImDrawFlags_RoundAll. + // - Hard coded support for ~0 == ImDrawFlags_RoundCornersAll. // - Hard coded support for values 0x01 to 0x0F (matching 15 out of 16 old flags combinations) --> see FixRectCornerFlags() in <1.90 code. - // - Hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundNone or use 'float rounding = 0.0f'. + // - Hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundCornersNone or use 'float rounding = 0.0f'. // See "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. IM_ASSERT_USER_ERROR_RET((flags & ImDrawFlags_InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?"); // Or misuse of legacy hard-coded ImDrawCornerFlags values if ((col & IM_COL32_A_MASK) == 0) return; - - flags |= Flags; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY - { - if (flags & ImDrawFlags_AALines) - PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.50f, p_max.y - 0.50f), rounding, flags); - else - PathRect(ImVec2(p_min.x + 0.50f, p_min.y + 0.50f), ImVec2(p_max.x - 0.49f, p_max.y - 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. - PathStroke(col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | ImDrawFlags_StrokeCenter | (flags & ~ImDrawFlags_StrokeMask_)); - return; - } - - const bool has_rounding = IM_HAS_ROUNDING(rounding); - - // Calculate the outer boundary of the rectangle based on the stroke position. - ImVec2 outer_min = p_min; - ImVec2 outer_max = p_max; - float outer_rounding = rounding; - - float offset = 0.0f; // Inside - if (stroke_pos == ImDrawFlags_StrokeCenter) - offset = thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - offset = _CalculateCenterBiasedOffset(thickness); - else if (stroke_pos == ImDrawFlags_StrokeOutside) - offset = thickness; - outer_min.x -= offset; - outer_min.y -= offset; - outer_max.x += offset; - outer_max.y += offset; - outer_rounding += has_rounding ? offset : 0.0f; - - const float width = outer_max.x - outer_min.x; - const float height = outer_max.y - outer_min.y; - const float half_min_dim = ImMin(width, height) * 0.5f; - if (half_min_dim <= thickness) IM_UNLIKELY - { - // Rectangle has collapsed into filled rectangle. - AddRectFilled(outer_min, outer_max, col, outer_rounding, flags); - return; - } - - if ((flags & ImDrawFlags_RoundMask_) == 0) - flags |= ImDrawFlags_RoundAll; - if (has_rounding) - { - // Constrain rounding to rect dimensions - outer_rounding = ImMin(outer_rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundTop) == ImDrawFlags_RoundTop) || ((flags & ImDrawFlags_RoundBottom) == ImDrawFlags_RoundBottom) ? 0.5f : 1.0f) - 1.0f); - outer_rounding = ImMin(outer_rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundLeft) == ImDrawFlags_RoundLeft) || ((flags & ImDrawFlags_RoundRight) == ImDrawFlags_RoundRight) ? 0.5f : 1.0f) - 1.0f); - } - - const bool is_truncated = IM_IS_TRUNCATED4(outer_min.x, outer_min.y, outer_max.x, outer_max.y) && IM_IS_TRUNCATED4(outer_rounding, thickness, 0.0f, 0.0f); //-V501 - if (_FringeScaleIsInteger && is_truncated) - { - int s_rounding = (int)(outer_rounding * _InvFringeScale); - int s_thickness = (int)(thickness * _InvFringeScale); - if (s_thickness <= 0) - return; - - if (s_rounding <= 0 || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) - { - // Pixel aligned non-rounded rect. - const ImVec2 opaque_uv = _Data->TexUvWhitePixel; - const float t = (float)s_thickness * _FringeScale; - - PrimReserve(8*3, 8); - const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(outer_min.x, outer_min.y, opaque_uv, col); - IM_APPEND_VTX(outer_min.x + t, outer_min.y + t, opaque_uv, col); - IM_APPEND_VTX(outer_max.x, outer_min.y, opaque_uv, col); - IM_APPEND_VTX(outer_max.x - t, outer_min.y + t, opaque_uv, col); - IM_APPEND_VTX(outer_max.x, outer_max.y, opaque_uv, col); - IM_APPEND_VTX(outer_max.x - t, outer_max.y - t, opaque_uv, col); - IM_APPEND_VTX(outer_min.x, outer_max.y, opaque_uv, col); - IM_APPEND_VTX(outer_min.x + t, outer_max.y - t, opaque_uv, col); - - IM_APPEND_TRI(idx + 0, idx + 3, idx + 1); - IM_APPEND_TRI(idx + 0, idx + 2, idx + 3); - - IM_APPEND_TRI(idx + 2, idx + 5, idx + 3); - IM_APPEND_TRI(idx + 2, idx + 4, idx + 5); - - IM_APPEND_TRI(idx + 4, idx + 7, idx + 5); - IM_APPEND_TRI(idx + 4, idx + 6, idx + 7); - - IM_APPEND_TRI(idx + 6, idx + 1, idx + 7); - IM_APPEND_TRI(idx + 6, idx + 0, idx + 1); - - return; - } - // Textured corners are baked with AA, do not use them if no-AA is requested. - const bool allow_tex_corners = (flags & (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_)) == (ImDrawFlags_AALines | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_); - if (allow_tex_corners && s_thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) - { - // Pixel aligned rect with round corners rendered using baked textures. - IM_ASSERT_PARANOID(s_thickness > 0 && s_rounding > 0); - const int size = ImMax(s_rounding, s_thickness); // This is matching the baking calculations. - const int idx = (s_thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) + s_rounding - 1; - IM_ASSERT_PARANOID((_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners) == 0); - IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX); - _AddRectBaked(outer_min, outer_max, col, (float)size * _FringeScale, (float)thickness, _Data->TexUvCorners[idx], flags); - return; - } - } - - if (!has_rounding || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) - { - const ImVec2 points[4] = { outer_min, ImVec2(outer_max.x, outer_min.y), outer_max, ImVec2(outer_min.x, outer_max.y) }; - _AddPolyline(points, 4, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | ImDrawFlags_StrokeInside, half_min_dim); - _Path.Size = 0; - } + if (Flags & ImDrawListFlags_AntiAliasedLines) + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags); else - { - // Switch to specialized rendering a bit early to avoid overdraw visible in transparent shapes. - if (thickness + (0.75f * _FringeScale) > outer_rounding) - { - // Special case rendering to avoid rendering artifacts at the corners. - // If rendered using the regular polyline, the stroke will fold and leave artifacts on the corners if rendered with transparency. - _AddRectTinyRounding(outer_min, outer_max, col, outer_rounding, thickness, flags); - return; - } - const float rounding_tl = (flags & ImDrawFlags_RoundTopLeft) ? outer_rounding : 0.0f; - const float rounding_tr = (flags & ImDrawFlags_RoundTopRight) ? outer_rounding : 0.0f; - const float rounding_br = (flags & ImDrawFlags_RoundBottomRight) ? outer_rounding : 0.0f; - const float rounding_bl = (flags & ImDrawFlags_RoundBottomLeft) ? outer_rounding : 0.0f; - PathArcToFast(ImVec2(outer_min.x + rounding_tl, outer_min.y + rounding_tl), rounding_tl, 6, 9); - PathArcToFast(ImVec2(outer_max.x - rounding_tr, outer_min.y + rounding_tr), rounding_tr, 9, 12); - PathArcToFast(ImVec2(outer_max.x - rounding_br, outer_max.y - rounding_br), rounding_br, 0, 3); - PathArcToFast(ImVec2(outer_min.x + rounding_bl, outer_max.y - rounding_bl), rounding_bl, 3, 6); - - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | ImDrawFlags_StrokeInside | (flags & ~ImDrawFlags_StrokeMask_), half_min_dim); - _Path.Size = 0; - } -} - -void ImDrawList::_AddRectFilledBaked(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float r, const ImVec4& tex_uvs, ImDrawFlags flags) -{ - // 9-slice with corner mirroring - const ImVec2 uv_tl(tex_uvs.x, tex_uvs.y); - const ImVec2 uv_tr(tex_uvs.z, tex_uvs.y); - const ImVec2 uv_br(tex_uvs.z, tex_uvs.w); - const ImVec2 uv_bl(tex_uvs.x, tex_uvs.w); - - PrimReserve(9 * 2 * 3, 4 * 4); - - const float r_tl = (flags & ImDrawFlags_RoundTopLeft) ? r : 0.0f; - const float r_tr = (flags & ImDrawFlags_RoundTopRight) ? r : 0.0f; - const float r_br = (flags & ImDrawFlags_RoundBottomRight) ? r : 0.0f; - const float r_bl = (flags & ImDrawFlags_RoundBottomLeft) ? r : 0.0f; - - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; - IM_APPEND_VTX(p_min.x, p_min.y, uv_tl, col); - IM_APPEND_VTX(p_min.x + r_tl, p_min.y, uv_tr, col); - IM_APPEND_VTX(p_max.x - r_tr, p_min.y, uv_tr, col); - IM_APPEND_VTX(p_max.x, p_min.y, uv_tl, col); - - IM_APPEND_VTX(p_min.x, p_min.y + r_tl, uv_bl, col); - IM_APPEND_VTX(p_min.x + r_tl, p_min.y + r_tl, uv_br, col); - IM_APPEND_VTX(p_max.x - r_tr, p_min.y + r_tr, uv_br, col); - IM_APPEND_VTX(p_max.x, p_min.y + r_tr, uv_bl, col); - - IM_APPEND_VTX(p_min.x, p_max.y - r_bl, uv_bl, col); - IM_APPEND_VTX(p_min.x + r_bl, p_max.y - r_bl, uv_br, col); - IM_APPEND_VTX(p_max.x - r_br, p_max.y - r_br, uv_br, col); - IM_APPEND_VTX(p_max.x, p_max.y - r_br, uv_bl, col); - - IM_APPEND_VTX(p_min.x, p_max.y, uv_tl, col); - IM_APPEND_VTX(p_min.x + r_bl, p_max.y, uv_tr, col); - IM_APPEND_VTX(p_max.x - r_br, p_max.y, uv_tr, col); - IM_APPEND_VTX(p_max.x, p_max.y, uv_tl, col); - - for (int i = 0; i < 3; i++) - { - for (int j = 0; j < 3; j++) - { - IM_APPEND_TRI(idx + 4, idx + 0, idx + 1); - IM_APPEND_TRI(idx + 4, idx + 1, idx + 5); - idx++; - } - idx++; - } + PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes. + PathStroke(col, thickness, ImDrawFlags_Closed); } void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags) { if ((col & IM_COL32_A_MASK) == 0) return; - - float width = p_max.x - p_min.x; - float height = p_max.y - p_min.y; - const float min_dim = ImMin(width, height); - flags |= Flags; - - if ((flags & ImDrawFlags_StrokeMask_) == ImDrawFlags_StrokeLegacy && rounding < 0.5f) IM_UNLIKELY + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { PrimReserve(6, 4); PrimRect(p_min, p_max, col); - return; - } - - // The rect is smaller than pixel in one dimension. - if (min_dim < _FringeScale) IM_UNLIKELY - { - if (min_dim < (1.0f / 255.0f) * _FringeScale) IM_UNLIKELY - return; - if (width < _FringeScale) - { - col = ImAlphaMultiply(col, width * _InvFringeScale); - width = _FringeScale; - } - if (height < _FringeScale) - { - col = ImAlphaMultiply(col, height * _InvFringeScale); - height = _FringeScale; - } - const ImVec2 points[4] = { p_min, ImVec2(p_min.x + width, p_min.y), ImVec2(p_min.x + width, p_min.y + height), ImVec2(p_min.x, p_min.y + height) }; - AddConvexPolyFilled(points, 4, col, ImDrawFlags_JoinMiter); - return; - } - - // When rounding non-integer and under threshold, has_rounding may be false but still affect is_truncated. Likely not worth catering for. - const bool has_rounding = (flags & ImDrawFlags_RoundMask_) != ImDrawFlags_RoundNone && IM_HAS_ROUNDING(rounding); - const bool is_truncated = IM_IS_TRUNCATED4(p_min.x, p_min.y, p_max.x, p_max.y) && IM_IS_TRUNCATED(rounding); - - if (_FringeScaleIsInteger && is_truncated) - { - // Fast path for the non-AA non-rounded rect. - if (!has_rounding) - { - PrimReserve(6, 4); - PrimRect(p_min, p_max, col); - return; - } - - if ((flags & ImDrawFlags_RoundMask_) == 0) - flags |= ImDrawFlags_RoundAll; - - rounding = ImMin(rounding, ImFabs(width) * (((flags & ImDrawFlags_RoundTop) == ImDrawFlags_RoundTop) || ((flags & ImDrawFlags_RoundBottom) == ImDrawFlags_RoundBottom) ? 0.5f : 1.0f) - 1.0f); - rounding = ImMin(rounding, ImFabs(height) * (((flags & ImDrawFlags_RoundLeft) == ImDrawFlags_RoundLeft) || ((flags & ImDrawFlags_RoundRight) == ImDrawFlags_RoundRight) ? 0.5f : 1.0f) - 1.0f); - - const int s_rounding = (int)(rounding * _InvFringeScale); - if (s_rounding <= 0) - { - PrimReserve(6, 4); - PrimRect(p_min, p_max, col); - return; - } - // Textured corners are baked with AA, do not use them if no-AA is requested. - const bool allow_tex_corners = (flags & (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_)) == (ImDrawFlags_AAFill | ImDrawFlags_UseTexForRoundCorners | ImDrawFlags_AllowTexForRoundCorners_); - if (allow_tex_corners && s_rounding <= IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX) - { - IM_ASSERT_PARANOID(!(_Data->Font->OwnerAtlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners)); - // This is matching the baking calculations. The rounding clamping above makes sure that there's enough space for the extra pixel. - const int corner_size = s_rounding + 1; - // Check that the baked corners do not overlap (this could be made more accurate if tested for x and y separately). - if ((float)corner_size * 2.0f * _FringeScale < min_dim) - { - const int idx = (s_rounding - 1); - IM_ASSERT_PARANOID(idx >= 0 && idx < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX); - _AddRectFilledBaked(p_min, p_max, col, (float)corner_size * _FringeScale, _Data->TexUvCorners[idx], flags); - return; - } - } - } - - if (!has_rounding) - { - const ImVec2 points[4] = { p_min, ImVec2(p_max.x, p_min.y), p_max, ImVec2(p_min.x, p_max.y) }; - AddConvexPolyFilled(points, 4, col, ImDrawFlags_JoinMiter); } else { PathRect(p_min, p_max, rounding, flags); - PathFillConvex(col, ImDrawFlags_JoinMiter); + PathFillConvex(col); } } // p_min = upper-left, p_max = lower-right -// Note: this does not support anti-aliasing when provided non-integer vertices. void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) { if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0) @@ -2643,17 +1593,16 @@ void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_ma PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left); } -void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, ImDrawFlags flags) +void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - //flags |= Flags; // Not needed. - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // As AddPolyline() default is different - - const ImVec2 points[4] = { p1, p2, p3, p4 }; - _AddPolyline(points, 4, col, thickness, flags | ImDrawFlags_Closed, FLT_MAX); + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathLineTo(p4); + PathStroke(col, thickness, ImDrawFlags_Closed); } void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col) @@ -2661,21 +1610,22 @@ void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& if ((col & IM_COL32_A_MASK) == 0) return; - const ImVec2 points[4] = { p1, p2, p3, p4 }; - AddConvexPolyFilled(points, 4, col); + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathLineTo(p4); + PathFillConvex(col); } -void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, ImDrawFlags flags) +void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - //flags |= Flags; // Not needed. - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - flags = (flags & ~ImDrawFlags_StrokeMask_) | stroke_pos; // As AddPolyline() default is different - - const ImVec2 points[3] = { p1, p2, p3 }; - _AddPolyline(points, 3, col, thickness, flags | ImDrawFlags_Closed, FLT_MAX); + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathStroke(col, thickness, ImDrawFlags_Closed); } void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col) @@ -2683,95 +1633,42 @@ void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImV if ((col & IM_COL32_A_MASK) == 0) return; - const ImVec2 points[3] = { p1, p2, p3 }; - AddConvexPolyFilled(points, 3, col); + PathLineTo(p1); + PathLineTo(p2); + PathLineTo(p3); + PathFillConvex(col); } -static float ApproxApothem(int num_segments) +void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) { - // Calculates approximation (within 0.001%) distance from the center of the circumscribed circle to the edge of the polygon, cos(pi / n) - IM_ASSERT_PARANOID(num_segments >= 3); - const float u = 1.0f / num_segments; - return ((4.058712f * u * u) - 4.934802f) * u * u + 1.0f; -} - -void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, ImDrawFlags flags) -{ - if ((col & IM_COL32_A_MASK) == 0) + if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) return; - flags |= Flags; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY - { - radius -= 0.5f; - stroke_pos = ImDrawFlags_StrokeCenter; - } - radius = ImMax(0.01f, radius); - - float outer_radius = radius; - if (stroke_pos == ImDrawFlags_StrokeCenter) - outer_radius = radius + thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - outer_radius = radius + _CalculateCenterBiasedOffset(thickness); - else if (stroke_pos == ImDrawFlags_StrokeInside) - outer_radius = radius; - else if (stroke_pos == ImDrawFlags_StrokeOutside) - outer_radius = radius + thickness; - - if (outer_radius <= thickness) IM_UNLIKELY - { - // The circle has collapsed into a filled circle. - AddCircleFilled(center, outer_radius, col, num_segments); - return; - } - - if (num_segments <= 0 && outer_radius <= _Data->ArcFastRadiusCutoff) + if (num_segments <= 0) { // Use arc with automatic segment count - const int a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(outer_radius); // Use outer_radius for segment count to be consistent with rounded rect. - _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, a_step); + _PathArcToFastEx(center, radius - 0.5f, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); _Path.Size--; } else { - // Explicit segment count or above fast arc cutoff (still clamp to avoid drawing insanely tessellated shapes) - if (num_segments <= 0) - num_segments = _CalcCircleAutoSegmentCount(outer_radius); + // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; - PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); + PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); } - if (_Path.Size >= 3) - { - // Calculate distance to the edge of the polygon describing the circle. - // This will be used by _AddPolyline() to clamp the inner stroke expansion, to avoid creating rendering artifacts. - const float unit_apothem = ApproxApothem(_Path.Size); - const float edge_dist = radius * unit_apothem; - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | stroke_pos, edge_dist); - } - _Path.Size = 0; + PathStroke(col, thickness, ImDrawFlags_Closed); } void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments) { - if ((col & IM_COL32_A_MASK) == 0) + if ((col & IM_COL32_A_MASK) == 0 || radius < 0.5f) return; - // Minimum radius, before the edge-AA will overlap. - const float min_radius = _FringeScale * 1.41421356f * 0.5f; - if (radius < min_radius) IM_UNLIKELY - { - if (radius < (1.0f / 255.0f) * min_radius) - return; - col = ImAlphaMultiply(col, radius / min_radius); - radius = min_radius; - } - - if (num_segments <= 0 && radius <= _Data->ArcFastRadiusCutoff) + if (num_segments <= 0) { // Use arc with automatic segment count _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0); @@ -2779,9 +1676,7 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, } else { - // Explicit segment count or above cutoff (still clamp to avoid drawing insanely tessellated shapes) - if (num_segments <= 0) - num_segments = _CalcCircleAutoSegmentCount(radius); + // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); // Because we are filling a closed shape we remove 1 from the count of segments/points @@ -2789,54 +1684,19 @@ void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); } - PathFillConvex(col, ImDrawFlags_JoinMiter); + PathFillConvex(col); } // Guaranteed to honor 'num_segments' -void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness, ImDrawFlags flags) +void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness) { if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; - flags |= Flags; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (stroke_pos == ImDrawFlags_StrokeLegacy) IM_UNLIKELY - { - radius -= 0.5f; - stroke_pos = ImDrawFlags_StrokeCenter; - } - radius = ImMax(0.01f, radius); - - // Calculate distance to the edge of the polygon describing the circle. - // This will be used by _AddPolyline() to clamp the inner stroke expansion, to avoid creating rendering artifacts. - const float unit_apothem = ApproxApothem(num_segments); - const float edge_dist = radius * unit_apothem; - - // Check overestimate first before testing details. - if (radius < thickness * 2.0f) - { - float outer_radius = radius; - if (stroke_pos == ImDrawFlags_StrokeCenter) - outer_radius = radius + thickness * 0.5f; - else if (stroke_pos == ImDrawFlags_StrokeCenterBiased) - outer_radius = radius + _CalculateCenterBiasedOffset(thickness); - else if (stroke_pos == ImDrawFlags_StrokeInside) - outer_radius = radius; - else if (stroke_pos == ImDrawFlags_StrokeOutside) - outer_radius = radius + thickness; - if (outer_radius * unit_apothem <= thickness) IM_UNLIKELY - { - // The polygon has collapsed into a filled polygon. - AddNgonFilled(center, outer_radius, col, num_segments); - return; - } - } - - // Because we are filling a closed shape we remove 1 from the count of segments/points + // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; - PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | stroke_pos, edge_dist); - _Path.Size = 0; + PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1); + PathStroke(col, thickness, ImDrawFlags_Closed); } // Guaranteed to honor 'num_segments' @@ -2845,48 +1705,25 @@ void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, in if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2) return; - const float diameter = radius * 2.0f; - if (diameter < _FringeScale) IM_UNLIKELY - { - if (diameter < (1.0f / 255.0f) * _FringeScale) IM_UNLIKELY - return; - col = ImAlphaMultiply(col, diameter * _InvFringeScale); - radius = _FringeScale * 0.5f; - } - // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; PathArcTo(center, radius, 0.0f, a_max, num_segments - 1); - PathFillConvex(col, ImDrawFlags_JoinMiter); + PathFillConvex(col); } // Ellipse -void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments, float thickness, ImDrawFlags flags) +void ImDrawList::AddEllipse(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments, float thickness) { if ((col & IM_COL32_A_MASK) == 0) return; - ImDrawFlags stroke_pos = _GetStrokePos(flags, ImDrawFlags_StrokeInside); - if (stroke_pos == ImDrawFlags_StrokeLegacy) - stroke_pos = ImDrawFlags_StrokeCenter; - - ImVec2 rad = radius; - rad.x = ImMax(0.01f, rad.x); - rad.y = ImMax(0.01f, rad.y); - if (num_segments <= 0) - num_segments = _CalcCircleAutoSegmentCount(ImMax(rad.x, rad.y)); // A bit pessimistic, maybe there's a better computation to do here. - - _Path.reserve(_Path.Size + (num_segments + 1)); + num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. // Because we are filling a closed shape we remove 1 from the count of segments/points const float a_max = IM_PI * 2.0f * ((float)num_segments - 1.0f) / (float)num_segments; - PathEllipticalArcTo(center, rad, rot, 0.0f, a_max, num_segments - 1); - - // Prevent the inside part of the stroke to be expanded too much to prevent some rendering artifacts. - const float max_inner_offset = ImMin(rad.x, rad.y); - _AddPolyline(_Path.Data, _Path.Size, col, thickness, ImDrawFlags_Closed | ImDrawFlags_JoinMiter | stroke_pos, max_inner_offset); - _Path.Size = 0; + PathEllipticalArcTo(center, radius, rot, 0.0f, a_max, num_segments - 1); + PathStroke(col, thickness, ImDrawFlags_Closed); } void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, ImU32 col, float rot, int num_segments) @@ -2894,28 +1731,6 @@ void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, Im if ((col & IM_COL32_A_MASK) == 0) return; - ImVec2 rad = radius; - float diameter_x = rad.x * 2.0f; - float diameter_y = rad.y * 2.0f; - const float min_dim = ImMin(diameter_x, diameter_y); - - // The ellipse is smaller than pixel in one dimension. - if (min_dim < _FringeScale) IM_UNLIKELY - { - if (min_dim < (1.0f / 255.0f) * _FringeScale) IM_UNLIKELY - return; - if (diameter_x < _FringeScale) - { - col = ImAlphaMultiply(col, diameter_x * _InvFringeScale); - rad.x = _FringeScale * 0.5f; - } - if (diameter_y < _FringeScale) - { - col = ImAlphaMultiply(col, diameter_y * _InvFringeScale); - rad.y = _FringeScale * 0.5f; - } - } - if (num_segments <= 0) num_segments = _CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)); // A bit pessimistic, maybe there's a better computation to do here. @@ -2926,25 +1741,25 @@ void ImDrawList::AddEllipseFilled(const ImVec2& center, const ImVec2& radius, Im } // Cubic Bezier takes 4 controls points -void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments, ImDrawFlags flags) +void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(p1); PathBezierCubicCurveTo(p2, p3, p4, num_segments); - PathStroke(col, thickness, flags); + PathStroke(col, thickness); } // Quadratic Bezier takes 3 controls points -void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments, ImDrawFlags flags) +void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments) { if ((col & IM_COL32_A_MASK) == 0) return; PathLineTo(p1); PathBezierQuadraticCurveTo(p2, p3, num_segments); - PathStroke(col, thickness, flags); + PathStroke(col, thickness); } void ImDrawList::AddText(ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) @@ -3017,10 +1832,10 @@ void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, cons return; IM_ASSERT((flags & 0x0F) == 0 && "Misuse of legacy hardcoded ImDrawCornerFlags values!"); // If this assert triggers on legacy code: see comments in ImDrawList::PathRect(). - if ((flags & ImDrawFlags_RoundMask_) == 0) - flags |= ImDrawFlags_RoundAll; + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags |= ImDrawFlags_RoundCornersAll; - if (rounding < 0.5f || (flags & ImDrawFlags_RoundMask_) == ImDrawFlags_RoundNone) + if (rounding < 0.5f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone) { AddImage(tex_ref, p_min, p_max, uv_min, uv_max, col); return; @@ -3032,7 +1847,7 @@ void ImDrawList::AddImageRounded(ImTextureRef tex_ref, const ImVec2& p_min, cons int vert_start_idx = VtxBuffer.Size; PathRect(p_min, p_max, rounding, flags); - PathFillConvex(col, ImDrawFlags_JoinMiter); + PathFillConvex(col); int vert_end_idx = VtxBuffer.Size; ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); @@ -3269,7 +2084,7 @@ void ImDrawList::AddConcavePolyFilled(const ImVec2* points, const int points_cou const ImVec2 uv = _Data->TexUvWhitePixel; ImTriangulator triangulator; unsigned int triangle[3]; - if (Flags & ImDrawFlags_AAFill) + if (Flags & ImDrawListFlags_AntiAliasedFill) { // Anti-aliased Fill const float AA_SIZE = _FringeScale; @@ -3351,6 +2166,724 @@ void ImDrawList::AddConcavePolyFilled(const ImVec2* points, const int points_cou } } +//----------------------------------------------------------------------------- +// [SECTION] ImDrawList Shadow Primitives +//----------------------------------------------------------------------------- +// - AddSubtractedRect() [Internal] +// - ClipPolygonShape() [Internal] +// - AddSubtractedRect() [Internal] +// - AddRectShadow() +//----------------------------------------------------------------------------- + +// Adds a rectangle (A) with another rectangle (B) subtracted from it (i.e. the portion of A covered by B is not drawn). Does not handle rounded corners (use the version that takes a convex polygon for that). +static void AddSubtractedRect(ImDrawList* draw_list, const ImVec2& a_min, const ImVec2& a_max, const ImVec2& a_min_uv, const ImVec2& a_max_uv, ImVec2 b_min, ImVec2 b_max, ImU32 col) +{ + // Early out without drawing anything if A is zero-size + if (a_min.x >= a_max.x || a_min.y >= a_max.y) + return; + + // Early out without drawing anything if B covers A entirely + if (a_min.x >= b_min.x && a_max.x <= b_max.x && a_min.y >= b_min.y && a_max.y <= b_max.y) + return; + + // First clip the extents of B to A + b_min = ImMax(b_min, a_min); + b_max = ImMin(b_max, a_max); + if (b_min.x >= b_max.x || b_min.y >= b_max.y) + { + // B is entirely outside A, so just draw A as-is + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(a_min, a_max, a_min_uv, a_max_uv, col); + return; + } + + // Otherwise we need to emit (up to) four quads to cover the visible area... + // Our layout looks like this (numbers are vertex indices, letters are quads): + // + // 0---8------9-----1 + // | | B | | + // + 4------5 + + // | A |xxxxxx| C | + // | |xxxxxx| | + // + 7------6 + + // | | D | | + // 3---11-----10----2 + + const int max_verts = 12; + const int max_indices = 6 * 4; // At most four quads + draw_list->PrimReserve(max_indices, max_verts); + + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx idx = (ImDrawIdx)draw_list->_VtxCurrentIdx; + + // Write vertices + vtx_write[0].pos = ImVec2(a_min.x, a_min.y); vtx_write[0].uv = ImVec2(a_min_uv.x, a_min_uv.y); vtx_write[0].col = col; + vtx_write[1].pos = ImVec2(a_max.x, a_min.y); vtx_write[1].uv = ImVec2(a_max_uv.x, a_min_uv.y); vtx_write[1].col = col; + vtx_write[2].pos = ImVec2(a_max.x, a_max.y); vtx_write[2].uv = ImVec2(a_max_uv.x, a_max_uv.y); vtx_write[2].col = col; + vtx_write[3].pos = ImVec2(a_min.x, a_max.y); vtx_write[3].uv = ImVec2(a_min_uv.x, a_max_uv.y); vtx_write[3].col = col; + + const ImVec2 pos_to_uv_scale = (a_max_uv - a_min_uv) / (a_max - a_min); // Guaranteed never to be a /0 because we check for zero-size A above + const ImVec2 pos_to_uv_offset = (a_min_uv / pos_to_uv_scale) - a_min; + + // Helper that generates an interpolated UV based on position +#define LERP_UV(x_pos, y_pos) (ImVec2(((x_pos) + pos_to_uv_offset.x) * pos_to_uv_scale.x, ((y_pos) + pos_to_uv_offset.y) * pos_to_uv_scale.y)) + vtx_write[4].pos = ImVec2(b_min.x, b_min.y); vtx_write[4].uv = LERP_UV(b_min.x, b_min.y); vtx_write[4].col = col; + vtx_write[5].pos = ImVec2(b_max.x, b_min.y); vtx_write[5].uv = LERP_UV(b_max.x, b_min.y); vtx_write[5].col = col; + vtx_write[6].pos = ImVec2(b_max.x, b_max.y); vtx_write[6].uv = LERP_UV(b_max.x, b_max.y); vtx_write[6].col = col; + vtx_write[7].pos = ImVec2(b_min.x, b_max.y); vtx_write[7].uv = LERP_UV(b_min.x, b_max.y); vtx_write[7].col = col; + vtx_write[8].pos = ImVec2(b_min.x, a_min.y); vtx_write[8].uv = LERP_UV(b_min.x, a_min.y); vtx_write[8].col = col; + vtx_write[9].pos = ImVec2(b_max.x, a_min.y); vtx_write[9].uv = LERP_UV(b_max.x, a_min.y); vtx_write[9].col = col; + vtx_write[10].pos = ImVec2(b_max.x, a_max.y); vtx_write[10].uv = LERP_UV(b_max.x, a_max.y); vtx_write[10].col = col; + vtx_write[11].pos = ImVec2(b_min.x, a_max.y); vtx_write[11].uv = LERP_UV(b_min.x, a_max.y); vtx_write[11].col = col; +#undef LERP_UV + draw_list->_VtxWritePtr += 12; + draw_list->_VtxCurrentIdx += 12; + + // Write indices for each quad (if it is visible) + if (b_min.x > a_min.x) // A + { + idx_write[0] = (ImDrawIdx)(idx + 0); idx_write[1] = (ImDrawIdx)(idx + 8); idx_write[2] = (ImDrawIdx)(idx + 11); + idx_write[3] = (ImDrawIdx)(idx + 0); idx_write[4] = (ImDrawIdx)(idx + 11); idx_write[5] = (ImDrawIdx)(idx + 3); + idx_write += 6; + } + if (b_min.y > a_min.y) // B + { + idx_write[0] = (ImDrawIdx)(idx + 8); idx_write[1] = (ImDrawIdx)(idx + 9); idx_write[2] = (ImDrawIdx)(idx + 5); + idx_write[3] = (ImDrawIdx)(idx + 8); idx_write[4] = (ImDrawIdx)(idx + 5); idx_write[5] = (ImDrawIdx)(idx + 4); + idx_write += 6; + } + if (a_max.x > b_max.x) // C + { + idx_write[0] = (ImDrawIdx)(idx + 9); idx_write[1] = (ImDrawIdx)(idx + 1); idx_write[2] = (ImDrawIdx)(idx + 2); + idx_write[3] = (ImDrawIdx)(idx + 9); idx_write[4] = (ImDrawIdx)(idx + 2); idx_write[5] = (ImDrawIdx)(idx + 10); + idx_write += 6; + } + if (a_max.y > b_max.y) // D + { + idx_write[0] = (ImDrawIdx)(idx + 7); idx_write[1] = (ImDrawIdx)(idx + 6); idx_write[2] = (ImDrawIdx)(idx + 10); + idx_write[3] = (ImDrawIdx)(idx + 7); idx_write[4] = (ImDrawIdx)(idx + 10); idx_write[5] = (ImDrawIdx)(idx + 11); + idx_write += 6; + } + + const int used_indices = (int)(idx_write - draw_list->_IdxWritePtr); + draw_list->_IdxWritePtr = idx_write; + draw_list->PrimUnreserve(max_indices - used_indices, 0); +} + +// Clip a polygonal shape to a rectangle, writing the results into dest_points. The number of points emitted is returned (may be zero if the polygon was entirely outside the rectangle, or the source polygon was not valid). dest_points may still be written to even if zero was returned. +// allocated_dest_points should contain the number of allocated points in dest_points - in general this should be the number of source points + 4 to accommodate the worst case. If this is exceeded data will be truncated and -1 returned. Stack space work area is allocated based on this value so it shouldn't be too large. +static int ClipPolygonShape(ImVec2* src_points, int num_src_points, ImVec2* dest_points, int allocated_dest_points, ImVec2 clip_rect_min, ImVec2 clip_rect_max) +{ + // Early-out with an empty result if clipping region is zero-sized + if (clip_rect_max.x <= clip_rect_min.x || clip_rect_max.y <= clip_rect_min.y) + return 0; + + // Early-out if there is no source geometry + if (num_src_points < 3) + return 0; + + // The four clip planes here are indexed as: + // 0 = X-, 1 = X+, 2 = Y-, 3 = Y+ + ImU8* outflags[2]; // Double-buffered flags for each vertex indicating which of the four clip planes it is outside of + outflags[0] = (ImU8*)alloca(2 * allocated_dest_points * sizeof(ImU8)); + outflags[1] = outflags[0] + allocated_dest_points; + + // Calculate initial outflags + ImU8 outflags_anded = 0xFF; + ImU8 outflags_ored = 0; + for (int point_idx = 0; point_idx < num_src_points; point_idx++) + { + const ImVec2 pos = src_points[point_idx]; + const ImU8 point_outflags = (pos.x < clip_rect_min.x ? 1 : 0) | (pos.x > clip_rect_max.x ? 2 : 0) | (pos.y < clip_rect_min.y ? 4 : 0) | (pos.y > clip_rect_max.y ? 8 : 0); + outflags[0][point_idx] = point_outflags; // Writing to buffer 0 + outflags_anded &= point_outflags; + outflags_ored |= point_outflags; + } + if (outflags_anded != 0) // Entirely clipped by any one plane, so nothing remains + return 0; + + if (outflags_ored == 0) // Entirely within bounds, so trivial accept + { + if (allocated_dest_points < num_src_points) + return -1; // Not sure what the caller was thinking if this happens, but we should handle it gracefully + + memcpy(dest_points, src_points, num_src_points * sizeof(ImVec2)); + return num_src_points; + } + + // Shape needs clipping + ImVec2* clip_buf[2]; // Double-buffered work area + clip_buf[0] = (ImVec2*)alloca(2 * allocated_dest_points * sizeof(ImVec2)); //-V630 + clip_buf[1] = clip_buf[0] + allocated_dest_points; + + memcpy(clip_buf[0], src_points, num_src_points * sizeof(ImVec2)); + int clip_buf_size = num_src_points; // Number of vertices currently in the clip buffer + + int read_buffer_idx = 0; // The index of the clip buffer/out-flags we are reading (0 or 1) + + for (int clip_plane = 0; clip_plane < 4; clip_plane++) // 0 = X-, 1 = X+, 2 = Y-, 3 = Y+ + { + const int clip_plane_bit = 1 << clip_plane; // Bit mask for our current plane in out-flags + if ((outflags_ored & clip_plane_bit) == 0) + continue; // All vertices are inside this plane, so no need to clip + + ImVec2* read_vert = &clip_buf[read_buffer_idx][0]; // Clip buffer vertex we are currently reading + ImVec2* write_vert = &clip_buf[1 - read_buffer_idx][0]; // Clip buffer vertex we are currently writing + ImVec2* write_vert_end = write_vert + allocated_dest_points; // End of the write buffer + ImU8* read_outflags = &outflags[read_buffer_idx][0]; // Out-flag we are currently reading + ImU8* write_outflags = &outflags[1 - read_buffer_idx][0]; // Out-flag we are currently writing + + // Keep track of the last vertex visited, initially the last in the list + ImVec2* last_vert = &read_vert[clip_buf_size - 1]; + ImU8 last_outflags = read_outflags[clip_buf_size - 1]; + + for (int vert = 0; vert < clip_buf_size; vert++) + { + ImU8 current_outflags = *(read_outflags++); + bool out = (current_outflags & clip_plane_bit) != 0; + if (((current_outflags ^ last_outflags) & clip_plane_bit) == 0) // We haven't crossed the clip plane + { + if (!out) + { + // Emit vertex as-is + if (write_vert >= write_vert_end) + return -1; // Ran out of buffer space, so abort + *(write_vert++) = *read_vert; + *(write_outflags++) = current_outflags; + } + } + else + { + // Emit a vertex at the intersection point + float t = 0.0f; + ImVec2 pos0 = *last_vert; + ImVec2 pos1 = *read_vert; + ImVec2 intersect_pos; + switch (clip_plane) + { + case 0: t = (clip_rect_min.x - pos0.x) / (pos1.x - pos0.x); intersect_pos = ImVec2(clip_rect_min.x, pos0.y + ((pos1.y - pos0.y) * t)); break; // X- + case 1: t = (clip_rect_max.x - pos0.x) / (pos1.x - pos0.x); intersect_pos = ImVec2(clip_rect_max.x, pos0.y + ((pos1.y - pos0.y) * t)); break; // X+ + case 2: t = (clip_rect_min.y - pos0.y) / (pos1.y - pos0.y); intersect_pos = ImVec2(pos0.x + ((pos1.x - pos0.x) * t), clip_rect_min.y); break; // Y- + case 3: t = (clip_rect_max.y - pos0.y) / (pos1.y - pos0.y); intersect_pos = ImVec2(pos0.x + ((pos1.x - pos0.x) * t), clip_rect_max.y); break; // Y+ + } + + if (write_vert >= write_vert_end) + return -1; // Ran out of buffer space, so abort + + // Write new out-flags for the vertex we just emitted + *(write_vert++) = intersect_pos; + *(write_outflags++) = (intersect_pos.x < clip_rect_min.x ? 1 : 0) | (intersect_pos.x > clip_rect_max.x ? 2 : 0) | (intersect_pos.y < clip_rect_min.y ? 4 : 0) | (intersect_pos.y > clip_rect_max.y ? 8 : 0); + + if (!out) + { + // When coming back in, also emit the actual vertex + if (write_vert >= write_vert_end) + return -1; // Ran out of buffer space, so abort + *(write_vert++) = *read_vert; + *(write_outflags++) = current_outflags; + } + + last_outflags = current_outflags; + } + + last_vert = read_vert; + read_vert++; // Advance to next vertex + } + + clip_buf_size = (int)(write_vert - &clip_buf[1 - read_buffer_idx][0]); // Update buffer size + read_buffer_idx = 1 - read_buffer_idx; // Swap buffers + } + + if (clip_buf_size < 3) + return 0; // Nothing to return + + // Copy results to output buffer, removing any redundant vertices + int num_out_verts = 0; + ImVec2 last_vert = clip_buf[read_buffer_idx][clip_buf_size - 1]; + for (int i = 0; i < clip_buf_size; i++) + { + ImVec2 vert = clip_buf[read_buffer_idx][i]; + if (ImLengthSqr(vert - last_vert) <= 0.00001f) + continue; + dest_points[num_out_verts++] = vert; + last_vert = vert; + } + + // Return size (IF this is still a valid shape) + return (num_out_verts > 2) ? num_out_verts : 0; +} + +// Adds a rectangle (A) with a convex shape (B) subtracted from it (i.e. the portion of A covered by B is not drawn). +static void AddSubtractedRect(ImDrawList* draw_list, const ImVec2& a_min, const ImVec2& a_max, const ImVec2& a_min_uv, const ImVec2& a_max_uv, ImVec2* b_points, int num_b_points, ImU32 col) +{ + // Early out without drawing anything if A is zero-size + if (a_min.x >= a_max.x || a_min.y >= a_max.y) + return; + + // First clip B to A + const int max_clipped_points = num_b_points + 4; + ImVec2* clipped_b_points = (ImVec2*)alloca(max_clipped_points * sizeof(ImVec2)); //-V630 + const int num_clipped_points = ClipPolygonShape(b_points, num_b_points, clipped_b_points, max_clipped_points, a_min, a_max); + IM_ASSERT(num_clipped_points >= 0); // -1 would indicate max_clipped_points was too small, which shouldn't happen + + b_points = clipped_b_points; + num_b_points = num_clipped_points; + + if (num_clipped_points == 0) + { + // B is entirely outside A, so just draw A as-is + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(a_min, a_max, a_min_uv, a_max_uv, col); + } + else + { + // We need to generate clipped geometry + // To do this we walk the inner polygon and connect each edge to one of the four corners of our rectangle based on the quadrant their normal points at + const int max_verts = num_b_points + 4; // Inner points plus the four corners + const int max_indices = (num_b_points * 3) + (4 * 3); // Worst case is one triangle per inner edge and then four filler triangles + draw_list->PrimReserve(max_indices, max_verts); + + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx inner_idx = (ImDrawIdx)draw_list->_VtxCurrentIdx; // Starting index for inner vertices + + // Write inner vertices + const ImVec2 pos_to_uv_scale = (a_max_uv - a_min_uv) / (a_max - a_min); // Guaranteed never to be a /0 because we check for zero-size A above + const ImVec2 pos_to_uv_offset = (a_min_uv / pos_to_uv_scale) - a_min; + + // Helper that generates an interpolated UV based on position +#define LERP_UV(x_pos, y_pos) (ImVec2(((x_pos) + pos_to_uv_offset.x) * pos_to_uv_scale.x, ((y_pos) + pos_to_uv_offset.y) * pos_to_uv_scale.y)) + for (int i = 0; i < num_b_points; i++) + { + vtx_write[i].pos = b_points[i]; + vtx_write[i].uv = LERP_UV(b_points[i].x, b_points[i].y); + vtx_write[i].col = col; + } +#undef LERP_UV + + vtx_write += num_b_points; + + // Write outer vertices + ImDrawIdx outer_idx = (ImDrawIdx)(inner_idx + num_b_points); // Starting index for outer vertices + + ImVec2 outer_verts[4]; + outer_verts[0] = ImVec2(a_min.x, a_min.y); // X- Y- (quadrant 0, top left) + outer_verts[1] = ImVec2(a_max.x, a_min.y); // X+ Y- (quadrant 1, top right) + outer_verts[2] = ImVec2(a_max.x, a_max.y); // X+ Y+ (quadrant 2, bottom right) + outer_verts[3] = ImVec2(a_min.x, a_max.y); // X- Y+ (quadrant 3, bottom left) + + vtx_write[0].pos = outer_verts[0]; vtx_write[0].uv = ImVec2(a_min_uv.x, a_min_uv.y); vtx_write[0].col = col; + vtx_write[1].pos = outer_verts[1]; vtx_write[1].uv = ImVec2(a_max_uv.x, a_min_uv.y); vtx_write[1].col = col; + vtx_write[2].pos = outer_verts[2]; vtx_write[2].uv = ImVec2(a_max_uv.x, a_max_uv.y); vtx_write[2].col = col; + vtx_write[3].pos = outer_verts[3]; vtx_write[3].uv = ImVec2(a_min_uv.x, a_max_uv.y); vtx_write[3].col = col; + + draw_list->_VtxCurrentIdx += num_b_points + 4; + draw_list->_VtxWritePtr += num_b_points + 4; + + // Now walk the inner vertices in order + ImVec2 last_inner_vert = b_points[num_b_points - 1]; + int last_inner_vert_idx = num_b_points - 1; + int last_outer_vert_idx = -1; + int first_outer_vert_idx = -1; + + // Triangle-area based check for degenerate triangles + // Min area (0.1f) is doubled (* 2.0f) because we're calculating (area * 2) here +#define IS_DEGENERATE(a, b, c) (ImFabs((((a).x * ((b).y - (c).y)) + ((b).x * ((c).y - (a).y)) + ((c).x * ((a).y - (b).y)))) < (0.1f * 2.0f)) + + // Check the winding order of the inner vertices using the sign of the triangle area, and set the outer vertex winding to match + int outer_vertex_winding = (((b_points[0].x * (b_points[1].y - b_points[2].y)) + (b_points[1].x * (b_points[2].y - b_points[0].y)) + (b_points[2].x * (b_points[0].y - b_points[1].y))) < 0.0f) ? -1 : 1; + for (int inner_vert_idx = 0; inner_vert_idx < num_b_points; inner_vert_idx++) + { + ImVec2 current_inner_vert = b_points[inner_vert_idx]; + + // Calculate normal (not actually normalized, as for our purposes here it doesn't need to be) + ImVec2 normal(current_inner_vert.y - last_inner_vert.y, -(current_inner_vert.x - last_inner_vert.x)); + + // Calculate the outer vertex index based on the quadrant the normal points at (0=top left, 1=top right, 2=bottom right, 3=bottom left) + int outer_vert_idx = (ImFabs(normal.x) > ImFabs(normal.y)) ? ((normal.x >= 0.0f) ? ((normal.y > 0.0f) ? 2 : 1) : ((normal.y > 0.0f) ? 3 : 0)) : ((normal.y >= 0.0f) ? ((normal.x > 0.0f) ? 2 : 3) : ((normal.x > 0.0f) ? 1 : 0)); + ImVec2 outer_vert = outer_verts[outer_vert_idx]; + + // Write the main triangle (connecting the inner edge to the corner) + if (!IS_DEGENERATE(last_inner_vert, current_inner_vert, outer_vert)) + { + idx_write[0] = (ImDrawIdx)(inner_idx + last_inner_vert_idx); + idx_write[1] = (ImDrawIdx)(inner_idx + inner_vert_idx); + idx_write[2] = (ImDrawIdx)(outer_idx + outer_vert_idx); + idx_write += 3; + } + + // We don't initially know which outer vertex we are going to start from, so set that here when processing the first inner vertex + if (first_outer_vert_idx == -1) + { + first_outer_vert_idx = outer_vert_idx; + last_outer_vert_idx = outer_vert_idx; + } + + // Now walk the outer edge and write any filler triangles needed (connecting outer edges to the inner vertex) + while (outer_vert_idx != last_outer_vert_idx) + { + int next_outer_vert_idx = (last_outer_vert_idx + outer_vertex_winding) & 3; + if (!IS_DEGENERATE(outer_verts[last_outer_vert_idx], outer_verts[next_outer_vert_idx], last_inner_vert)) + { + idx_write[0] = (ImDrawIdx)(outer_idx + last_outer_vert_idx); + idx_write[1] = (ImDrawIdx)(outer_idx + next_outer_vert_idx); + idx_write[2] = (ImDrawIdx)(inner_idx + last_inner_vert_idx); + idx_write += 3; + } + last_outer_vert_idx = next_outer_vert_idx; + } + + last_inner_vert = current_inner_vert; + last_inner_vert_idx = inner_vert_idx; + } + + // Write remaining filler triangles for any un-traversed outer edges + if (first_outer_vert_idx != -1) + { + while (first_outer_vert_idx != last_outer_vert_idx) + { + int next_outer_vert_idx = (last_outer_vert_idx + outer_vertex_winding) & 3; + if (!IS_DEGENERATE(outer_verts[last_outer_vert_idx], outer_verts[next_outer_vert_idx], last_inner_vert)) + { + idx_write[0] = (ImDrawIdx)(outer_idx + last_outer_vert_idx); + idx_write[1] = (ImDrawIdx)(outer_idx + next_outer_vert_idx); + idx_write[2] = (ImDrawIdx)(inner_idx + last_inner_vert_idx); + idx_write += 3; + } + last_outer_vert_idx = next_outer_vert_idx; + } + } +#undef IS_DEGENERATE + + int used_indices = (int)(idx_write - draw_list->_IdxWritePtr); + draw_list->_IdxWritePtr = idx_write; + draw_list->PrimUnreserve(max_indices - used_indices, 0); + } +} + +void ImDrawList::AddShadowRect(const ImVec2& obj_min, const ImVec2& obj_max, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags, float obj_rounding) +{ + if ((shadow_col & IM_COL32_A_MASK) == 0) + return; + + ImVec2* inner_rect_points = NULL; // Points that make up the shape of the inner rectangle (used when it has rounded corners) + int inner_rect_points_count = 0; + + // Generate a path describing the inner rectangle and copy it to our buffer + const bool is_filled = (flags & ImDrawFlags_ShadowCutOutShapeBackground) == 0; + const bool is_rounded = (obj_rounding > 0.0f) && ((flags & ImDrawFlags_RoundCornersMask_) != ImDrawFlags_RoundCornersNone); // Do we have rounded corners? + if (is_rounded && !is_filled) + { + IM_ASSERT(_Path.Size == 0); + PathRect(obj_min, obj_max, obj_rounding, flags); + inner_rect_points_count = _Path.Size; + inner_rect_points = (ImVec2*)alloca(inner_rect_points_count * sizeof(ImVec2)); //-V630 + memcpy(inner_rect_points, _Path.Data, inner_rect_points_count * sizeof(ImVec2)); + _Path.Size = 0; + } + + if (is_filled) + PrimReserve(6 * 9, 4 * 9); // Reserve space for adding unclipped chunks + + // Draw the relevant chunks of the texture (the texture is split into a 3x3 grid) + // FIXME-OPT: Might make sense to optimize/unroll for the fast paths (filled or not rounded) + for (int x = 0; x < 3; x++) + { + for (int y = 0; y < 3; y++) + { + const int uv_index = x + (y + y + y); // y*3 formatted so as to ensure the compiler avoids an actual multiply + const ImVec4 uvs = _Data->ShadowRectUvs[uv_index]; + + ImVec2 draw_min, draw_max; + switch (x) + { + case 0: draw_min.x = obj_min.x - shadow_thickness; draw_max.x = obj_min.x; break; + case 1: draw_min.x = obj_min.x; draw_max.x = obj_max.x; break; + case 2: draw_min.x = obj_max.x; draw_max.x = obj_max.x + shadow_thickness; break; + } + switch (y) + { + case 0: draw_min.y = obj_min.y - shadow_thickness; draw_max.y = obj_min.y; break; + case 1: draw_min.y = obj_min.y; draw_max.y = obj_max.y; break; + case 2: draw_min.y = obj_max.y; draw_max.y = obj_max.y + shadow_thickness; break; + } + + ImVec2 uv_min(uvs.x, uvs.y); + ImVec2 uv_max(uvs.z, uvs.w); + if (is_filled) + PrimRectUV(draw_min + shadow_offset, draw_max + shadow_offset, uv_min, uv_max, shadow_col); // No clipping path (draw entire shadow) + else if (is_rounded) + AddSubtractedRect(this, draw_min + shadow_offset, draw_max + shadow_offset, uv_min, uv_max, inner_rect_points, inner_rect_points_count, shadow_col); // Complex path for rounded rectangles + else + AddSubtractedRect(this, draw_min + shadow_offset, draw_max + shadow_offset, uv_min, uv_max, obj_min, obj_max, shadow_col); // Simple fast path for non-rounded rectangles + } + } +} + +// Add a shadow for a convex shape described by points and num_points +void ImDrawList::AddShadowConvexPoly(const ImVec2* points, int points_count, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags) +{ + const bool is_filled = (flags & ImDrawFlags_ShadowCutOutShapeBackground) == 0; + IM_ASSERT((is_filled || (ImLengthSqr(shadow_offset) < 0.00001f)) && "Drawing circle/convex shape shadows with no center fill and an offset is not currently supported"); + IM_ASSERT(points_count >= 3); + + // Calculate poly vertex order + const int vertex_winding = (((points[0].x * (points[1].y - points[2].y)) + (points[1].x * (points[2].y - points[0].y)) + (points[2].x * (points[0].y - points[1].y))) < 0.0f) ? -1 : 1; + + // If we're using anti-aliasing, then inset the shadow by 0.5 pixels to avoid unpleasant fringing artifacts + const bool use_inset_distance = (Flags & ImDrawListFlags_AntiAliasedFill) && (!is_filled); + const float inset_distance = 0.5f; + + const ImVec4 uvs = _Data->ShadowRectUvs[9]; + + int tex_width = _Data->Font->OwnerAtlas->TexData->Width; + int tex_height = _Data->Font->OwnerAtlas->TexData->Height; + float inv_tex_width = 1.0f / (float)tex_width; + float inv_tex_height = 1.0f / (float)tex_height; + + ImVec2 solid_uv = ImVec2(uvs.z, uvs.w); // UV at the inside of an edge + ImVec2 edge_uv = ImVec2(uvs.x, uvs.w); // UV at the outside of an edge + + ImVec2 solid_to_edge_delta_texels = edge_uv - solid_uv; // Delta between the solid/edge points in texel-space (we need this in pixels - or, to be more precise, to be at a 1:1 aspect ratio - for the rotation to work) + solid_to_edge_delta_texels.x *= (float)tex_width; + solid_to_edge_delta_texels.y *= (float)tex_height; + + // Our basic algorithm here is that we generate a straight section along each edge, and then either one or two curved corner triangles at the corners, + // which use an appropriate chunk of the texture to generate a smooth curve. + const int num_edges = points_count; + + // Normalize a vector +#define NORMALIZE(vec) ((vec) / ImLength((vec), 0.001f)) + + const int required_stack_mem = (num_edges * sizeof(ImVec2)) + (num_edges * sizeof(float)); + ImU8* base_mem_for_normals_and_edges = (ImU8*)alloca(required_stack_mem); + ImU8* mem_for_normals_and_edges = (ImU8*)base_mem_for_normals_and_edges; + + // Calculate edge normals + ImVec2* edge_normals = (ImVec2*)(void*)mem_for_normals_and_edges; + mem_for_normals_and_edges += num_edges * sizeof(ImVec2); + + for (int edge_index = 0; edge_index < num_edges; edge_index++) + { + ImVec2 edge_start = points[edge_index]; // No need to apply offset here because the normal is unaffected + ImVec2 edge_end = points[(edge_index + 1) % num_edges]; + ImVec2 edge_normal = NORMALIZE(ImVec2(edge_end.y - edge_start.y, -(edge_end.x - edge_start.x))); + edge_normals[edge_index] = edge_normal * (float)vertex_winding; // Flip normals for reverse winding + } + + // Pre-calculate edge scales + // We need to do this because we need the edge strips to have widths that match up with the corner sections, otherwise pixel cracking can occur along the boundaries + float* edge_size_scales = (float*)(void*)mem_for_normals_and_edges; + mem_for_normals_and_edges += num_edges * sizeof(float); + IM_ASSERT_PARANOID(mem_for_normals_and_edges == (base_mem_for_normals_and_edges + required_stack_mem)); // Check we used exactly what we allocated + + { + ImVec2 prev_edge_normal = edge_normals[num_edges - 1]; + for (int edge_index = 0; edge_index < num_edges; edge_index++) + { + ImVec2 edge_normal = edge_normals[edge_index]; + float cos_angle_coverage = ImDot(edge_normal, prev_edge_normal); + + if (cos_angle_coverage < 0.999999f) + { + // If we are covering more than 90 degrees we need an intermediate vertex to stop the required expansion tending towards infinity. + // And thus the effective angle will be halved (matches the similar code in loop below) + float angle_coverage = ImAcos(cos_angle_coverage); + if (cos_angle_coverage <= 0.0f) // -V1051 + angle_coverage *= 0.5f; + edge_size_scales[edge_index] = 1.0f / ImCos(angle_coverage * 0.5f); // How much we need to expand our size by to avoid clipping the corner of the texture off + } + else + { + edge_size_scales[edge_index] = 1.0f; // No corner, thus default scale + } + + prev_edge_normal = edge_normal; + } + } + + const int max_vertices = (4 + (3 * 2) + (is_filled ? 1 : 0)) * num_edges; // 4 vertices per edge plus 3*2 for potentially two corner triangles, plus one per vertex for fill + const int max_indices = ((6 + (3 * 2)) * num_edges) + (is_filled ? ((num_edges - 2) * 3) : 0); // 2 tris per edge plus up to two corner triangles, plus fill triangles + PrimReserve(max_indices, max_vertices); + ImDrawIdx* idx_write = _IdxWritePtr; + ImDrawVert* vtx_write = _VtxWritePtr; + ImDrawIdx current_idx = (ImDrawIdx)_VtxCurrentIdx; + + //ImVec2 previous_edge_start = points[0] + offset; + ImVec2 prev_edge_normal = edge_normals[num_edges - 1]; + ImVec2 edge_start = points[0] + shadow_offset; + + if (use_inset_distance) + edge_start -= NORMALIZE(edge_normals[0] + prev_edge_normal) * inset_distance; + + for (int edge_index = 0; edge_index < num_edges; edge_index++) + { + ImVec2 edge_end = points[(edge_index + 1) % num_edges] + shadow_offset; + ImVec2 edge_normal = edge_normals[edge_index]; + const float size_scale_start = edge_size_scales[edge_index]; + const float size_scale_end = edge_size_scales[(edge_index + 1) % num_edges]; + + if (use_inset_distance) + edge_end -= NORMALIZE(edge_normals[(edge_index + 1) % num_edges] + edge_normal) * inset_distance; + + // Add corner section + float cos_angle_coverage = ImDot(edge_normal, prev_edge_normal); + if (cos_angle_coverage < 0.999999f) // Don't fill if the corner is actually straight + { + // If we are covering more than 90 degrees we need an intermediate vertex to stop the required expansion tending towards infinity. + // And thus the effective angle has been halved (matches the similar code in loop above) + int num_steps = (cos_angle_coverage <= 0.0f) ? 2 : 1; + + for (int step = 0; step < num_steps; step++) + { + if (num_steps > 1) + { + if (step == 0) + edge_normal = NORMALIZE(edge_normal + prev_edge_normal); // Use half-way normal for first step + else + edge_normal = edge_normals[edge_index]; // Then use the "real" next edge normal for the second + + cos_angle_coverage = ImDot(edge_normal, prev_edge_normal); // Recalculate angle + } + + // Calculate UV for the section of the curved texture + + const float angle_coverage = ImAcos(cos_angle_coverage); + const float sin_angle_coverage = ImSin(angle_coverage); + + ImVec2 edge_delta = solid_to_edge_delta_texels; + edge_delta *= size_scale_start; + + ImVec2 rotated_edge_delta = ImVec2((edge_delta.x * cos_angle_coverage) + (edge_delta.y * sin_angle_coverage), (edge_delta.x * sin_angle_coverage) + (edge_delta.y * cos_angle_coverage)); + + // Convert from texels back into UV space + edge_delta.x *= inv_tex_width; + edge_delta.y *= inv_tex_height; + rotated_edge_delta.x *= inv_tex_width; + rotated_edge_delta.y *= inv_tex_height; + + ImVec2 expanded_edge_uv = solid_uv + edge_delta; + ImVec2 other_edge_uv = solid_uv + rotated_edge_delta; // Rotated UV to encompass the necessary section of the curve + + float expanded_thickness = shadow_thickness * size_scale_start; + + // Add a triangle to fill the corner + ImVec2 outer_edge_start = edge_start + (prev_edge_normal * expanded_thickness); + ImVec2 outer_edge_end = edge_start + (edge_normal * expanded_thickness); + + vtx_write->pos = edge_start; vtx_write->col = shadow_col; vtx_write->uv = solid_uv; vtx_write++; + vtx_write->pos = outer_edge_end; vtx_write->col = shadow_col; vtx_write->uv = expanded_edge_uv; vtx_write++; + vtx_write->pos = outer_edge_start; vtx_write->col = shadow_col; vtx_write->uv = other_edge_uv; vtx_write++; + + *(idx_write++) = current_idx; + *(idx_write++) = current_idx + 1; + *(idx_write++) = current_idx + 2; + current_idx += 3; + + prev_edge_normal = edge_normal; + } + } + + // Add section along edge + const float edge_length = ImLength(edge_end - edge_start, 0.0f); + if (edge_length > 0.00001f) // Don't try and process degenerate edges + { + ImVec2 outer_edge_start = edge_start + (edge_normal * shadow_thickness * size_scale_start); + ImVec2 outer_edge_end = edge_end + (edge_normal * shadow_thickness * size_scale_end); + ImVec2 scaled_edge_uv_start = solid_uv + ((edge_uv - solid_uv) * size_scale_start); + ImVec2 scaled_edge_uv_end = solid_uv + ((edge_uv - solid_uv) * size_scale_end); + + // Write vertices, inner first, then outer + vtx_write->pos = edge_start; vtx_write->col = shadow_col; vtx_write->uv = solid_uv; vtx_write++; + vtx_write->pos = edge_end; vtx_write->col = shadow_col; vtx_write->uv = solid_uv; vtx_write++; + vtx_write->pos = outer_edge_end; vtx_write->col = shadow_col; vtx_write->uv = scaled_edge_uv_end; vtx_write++; + vtx_write->pos = outer_edge_start; vtx_write->col = shadow_col; vtx_write->uv = scaled_edge_uv_start; vtx_write++; + + *(idx_write++) = current_idx; + *(idx_write++) = current_idx + 1; + *(idx_write++) = current_idx + 2; + *(idx_write++) = current_idx; + *(idx_write++) = current_idx + 2; + *(idx_write++) = current_idx + 3; + current_idx += 4; + } + + edge_start = edge_end; + } + + // Fill if requested + if (is_filled) + { + // Add vertices + for (int edge_index = 0; edge_index < num_edges; edge_index++) + { + vtx_write->pos = points[edge_index] + shadow_offset; + vtx_write->col = shadow_col; + vtx_write->uv = solid_uv; + vtx_write++; + } + + // Add triangles + for (int edge_index = 2; edge_index < num_edges; edge_index++) + { + *(idx_write++) = current_idx; + *(idx_write++) = (ImDrawIdx)(current_idx + edge_index - 1); + *(idx_write++) = (ImDrawIdx)(current_idx + edge_index); + } + + current_idx += (ImDrawIdx)num_edges; + } + + // Release any unused vertices/indices + int used_indices = (int)(idx_write - _IdxWritePtr); + int used_vertices = (int)(vtx_write - _VtxWritePtr); + _IdxWritePtr = idx_write; + _VtxWritePtr = vtx_write; + _VtxCurrentIdx = current_idx; + PrimUnreserve(max_indices - used_indices, max_vertices - used_vertices); +#undef NORMALIZE +} + +// Draw a shadow for a circular object +// Uses the draw path and so wipes any existing data there +void ImDrawList::AddShadowCircle(const ImVec2& obj_center, float obj_radius, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags, int num_segments) +{ + // Obtain segment count + if (num_segments <= 0) + { + // Automatic segment count + const int radius_idx = (int)obj_radius - 1; + if (radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts)) + num_segments = _Data->CircleSegmentCounts[radius_idx]; // Use cached value + else + num_segments = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(obj_radius, _Data->CircleTessellationMaxError); + } + else + { + // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes) + num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX); + } + + // Generate a path describing the inner circle and copy it to our buffer + IM_ASSERT(_Path.Size == 0); + const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments; + if (num_segments == 12) + PathArcToFast(obj_center, obj_radius, 0, 12 - 1); + else + PathArcTo(obj_center, obj_radius, 0.0f, a_max, num_segments - 1); + + // Draw the shadow using the convex shape code + AddShadowConvexPoly(_Path.Data, _Path.Size, shadow_col, shadow_thickness, shadow_offset, flags); + _Path.Size = 0; +} + +void ImDrawList::AddShadowNGon(const ImVec2& obj_center, float obj_radius, ImU32 shadow_col, float shadow_thickness, const ImVec2& shadow_offset, ImDrawFlags flags, int num_segments) +{ + IM_ASSERT(num_segments != 0); + AddShadowCircle(obj_center, obj_radius, shadow_col, shadow_thickness, shadow_offset, flags, num_segments); +} + //----------------------------------------------------------------------------- // [SECTION] ImDrawListSplitter //----------------------------------------------------------------------------- @@ -3526,7 +3059,7 @@ void ImGui::AddDrawListToDrawDataEx(ImDrawData* draw_data, ImVector // May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); - if (!(draw_list->Flags & ImDrawFlags_UseVtxOffset)) + if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset)) IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) @@ -3897,6 +3430,10 @@ ImFontAtlas::ImFontAtlas() TexNextUniqueID = 1; FontNextUniqueID = 1; Builder = NULL; + + // FIXME-SHADOWS: move elsewhere? + ShadowRectIds[0] = ShadowRectIds[1] = -1; + ShadowTexConfig.SetupDefaults(); } ImFontAtlas::~ImFontAtlas() @@ -3955,6 +3492,9 @@ void ImFontAtlas::ClearInputData() font->Flags |= ImFontFlags_NoLoadGlyphs; } Sources.clear(); + + // FIXME-SHADOWS: Move elsewhere? + ShadowRectIds[0] = ShadowRectIds[1] = -1; } // Clear CPU-side copy of the texture data. @@ -4337,7 +3877,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) } if (font_cfg->FontLoader != NULL) { - IM_ASSERT(font_cfg->FontLoader->FontSrcGetGlyphIndexFromCodepoint != NULL && font_cfg->FontLoader->FontBakedLoadGlyph != NULL); + IM_ASSERT(font_cfg->FontLoader->FontBakedLoadGlyph != NULL); IM_ASSERT(font_cfg->FontLoader->LoaderInit == NULL && font_cfg->FontLoader->LoaderShutdown == NULL); // FIXME-NEWATLAS: Unsupported yet. } // | Target w/ Implicit RefSize | Target w/ Explicit RefSize | @@ -4363,10 +3903,7 @@ ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg_in) ImFontAtlasFontSourceAddToFont(this, font, font_cfg); if (is_first_font) - { ImFontAtlasBuildNotifySetFont(this, NULL, font); - Builder->LoadedFontDefaultAsVector = -1; - } return font; } @@ -4392,17 +3929,13 @@ const char* ImGui_GetDefaultCompressedFontDataProggyForever(int* out_size); #endif // This duplicates some of the logic in UpdateFontsNewFrame() which is a bit chicken-and-eggy/tricky to extract due to variety of codepaths and possible initialization ordering. -bool ImFontAtlasHeuristicShouldUseDefaultVectorFont(ImFontAtlas* atlas) +static float GetExpectedContextFontSize(ImGuiContext* ctx) { - ImGuiContext* ctx = atlas->OwnerContext; - if (ctx == NULL) - return true; float fb_scale = (ctx->IO.DisplayFramebufferScale.x != 0.0f) ? ctx->IO.DisplayFramebufferScale.x : 1.0f; if (ctx->IO.DisplayFramebufferScale.x == 1.0f && ctx->IO.DisplaySize.x <= 0.0f && ctx->IO.ConfigMacOSXBehaviors) - fb_scale = 2.0f; // If called before backend had a chance to init DisplayFramebufferScale: default to expecting Retina on macOS/iOS. - const float scale = ctx->Style.FontScaleMain * ctx->Style.FontScaleDpi * fb_scale; - const float expected_font_size = ((ctx->Style.FontSizeBase > 0.0f) ? ctx->Style.FontSizeBase : 13.0f) * scale; - return expected_font_size >= 15.0f; + fb_scale = 2.0f; // If called before backend had a chance to init DisplayFramebufferScale. default to expecting Retina. + float scale = ctx->Style.FontScaleMain * ctx->Style.FontScaleDpi * fb_scale; + return ((ctx->Style.FontSizeBase > 0.0f) ? ctx->Style.FontSizeBase : 13.0f) * scale; } // Legacy function with heuristic to select Pixel or Vector font. @@ -4410,11 +3943,10 @@ bool ImFontAtlasHeuristicShouldUseDefaultVectorFont(ImFontAtlas* atlas) // Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg) { - const bool use_vector_font = ImFontAtlasHeuristicShouldUseDefaultVectorFont(this); - ImFont* font = use_vector_font ? AddFontDefaultVector(font_cfg) : AddFontDefaultBitmap(font_cfg); - if (Fonts.Size == 1) - Builder->LoadedFontDefaultAsVector = use_vector_font ? 1 : 0; - return font; + if (OwnerContext == NULL || GetExpectedContextFontSize(OwnerContext) >= 15.0f) + return AddFontDefaultVector(font_cfg); + else + return AddFontDefaultBitmap(font_cfg); } // Load embedded ProggyClean.ttf. Default size 13, disable oversampling. @@ -4860,196 +4392,6 @@ static void ImFontAtlasBuildUpdateTexDataBasic(ImFontAtlas* atlas) atlas->TexUvWhitePixel = ImVec2((r.x + 0.5f) * atlas->TexUvScale.x, (r.y + 0.5f) * atlas->TexUvScale.y); } - -#define IM_DRAWLIST_CORNER_POINTS_MAX (IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4 + 3) // Max number of points in corner profiles - -static int InitCornerGeometry(float cx, float cy, float rounding, float circle_segment_max_error, ImVec2* line_normals, float* line_distances) -{ - // This tries to quite faithfully replicate how we render the corners using tessellation. - // Older code sampled a circle SDF directly, but it had clearly visible discrepancy between the baked corners - // and tessellated corners due to circle_segment_max_error. - - const int auto_seg_count = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(rounding, circle_segment_max_error); - int arc_step, arc_step_count; - CalcCornerArcStepAndCount(auto_seg_count, arc_step, arc_step_count); - const int arc_point_count = arc_step_count + 1; - - // Build arc of points, with straight segments at each end. - // . [n-2]..[n-1] - // .` - // . - // [1] x (cx,cy) - // : - // [0] - ImVec2 points[IM_DRAWLIST_CORNER_POINTS_MAX]; - int num_points = 0; - - points[num_points++] = ImVec2(cx - rounding, cy + 1.0f); - - float da = ((float)arc_step / (float)IM_DRAWLIST_ARCFAST_TABLE_SIZE) * IM_PI * 2.0f; - float a = IM_PI; - for (int i = 0; i < arc_point_count; i++) - { - float dx = cosf(a); - float dy = sinf(a); - points[num_points++] = ImVec2(cx + dx * rounding, cy + dy * rounding); - a += da; - } - - points[num_points++] = ImVec2(cx + 1.0f, cy - rounding); - - // Turn segments to half spaces. - for (int i = 0; i < num_points - 1; i++) - { - const ImVec2 diff = points[i + 1] - points[i]; - const float d2 = diff.x * diff.x + diff.y * diff.y; - const float inv_d = ImRsqrtPrecise(d2); - line_normals[i].x = diff.y * inv_d; // Normal points outwards - line_normals[i].y = -diff.x * inv_d; - line_distances[i] = -ImDot(points[i], line_normals[i]); - } - - return num_points - 1; -} - -// Returns distance to convex shape limited by lines. -static float SampleConvex(float x, float y, const ImVec2* line_normals, const float* line_distances, int num_lines) -{ - float result = -FLT_MAX; - for (int i = 0; i < num_lines; i++) - { - const float d = line_normals[i].x * x + line_normals[i].y * y + line_distances[i]; - if (d > result) - result = d; - } - return result; -} - -static ImU8 SampleCornerFillOrStroke(float x, float y, float thickness, const ImVec2* line_normals, const float* line_distances, int num_lines) -{ - const float d = SampleConvex(x, y, line_normals, line_distances, num_lines); - const float aa_width = 1.0f; - if (thickness == 0.0f) - { - // Fill - return (ImU8)(ImClamp(1.0f - (d + aa_width * 0.5f) / aa_width, 0.0f, 1.0f) * 255.0f); - } - else - { - // Stroke - const float outer = 1.0f - (d + aa_width * 0.5f) / aa_width; - const float inner = (d + thickness + aa_width * 0.5f) / aa_width; - return (ImU8)(ImClamp(ImMin(inner, outer), 0.0f, 1.0f) * 255.0f); - } -} - -#if 0 // Set to 1 to visualize coverage of textured corners -#define DEBUG_TEX_CORNER_U8(_LX, _H) ((_LX & 1) ? 255 : 0) -#define DEBUG_TEX_CORNER_U32(_LX, _H) IM_COL32((_LX & 1) ? 255: 0, 0, 0, (_LX & 1) ? 200 : 0) -#else -#define DEBUG_TEX_CORNER_U8(_LX, _H) 0xFF -#define DEBUG_TEX_CORNER_U32(_LX, _H) 0xFFFFFFFF -#endif - -static void ImFontAtlasBuildUpdateTexDataCorners(ImFontAtlas* atlas) -{ - if (atlas->Flags & ImFontAtlasFlags_NoBakedRoundCorners) - return; - - // Pack and store identifier so we can refresh UV coordinates on texture resize. - ImTextureData* tex = atlas->TexData; - ImFontAtlasBuilder* builder = atlas->Builder; - - // FIXME-TEXCORNERS: Ideally we should pick up the max error from the styles, but it does not seem be to set by the time we build the data the first time. - float circle_segment_max_error = 0.30f; // Default matching ImGuiStyle::CircleTessellationMaxError. - // if (atlas->OwnerContext) - // circle_segment_max_error = atlas->OwnerContext->DrawListSharedData.CircleSegmentMaxError; - - // Calculate size and pack - ImFontAtlasRect r; - bool add_and_draw = atlas->GetCustomRect(builder->PackIdCornersTexData, &r) == false; - if (add_and_draw) - { - // (thickness 0 for filled, thickness >0 for strokes) - ImVec2i pack_size(0, 0); - for (int thickness = 0; thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; thickness++) - { - const bool is_filled = (thickness == 0); - int row_width = 0; - int row_height = 0; - for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) - { - const int rounding = n + 1; - const int size = (is_filled ? (rounding + 1) : ImMax(rounding, thickness)); - row_width += size + 2; - row_height = ImMax(row_height, size + 2); - } - pack_size.x = ImMax(pack_size.x, row_width); - pack_size.y += row_height; - } - builder->PackIdCornersTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); - IM_ASSERT(builder->PackIdCornersTexData != ImFontAtlasRectId_Invalid); - } - - // Render - int y = r.y; - ImVec2 line_normals[IM_DRAWLIST_CORNER_POINTS_MAX]; - float line_distances[IM_DRAWLIST_CORNER_POINTS_MAX]; - for (int thickness = 0; thickness < IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX; thickness++) - { - const bool is_filled = (thickness == 0); - int x = r.x; - int row_height = 0; - for (int n = 0; n < IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX; n++) - { - // Filled: Always add 1px to the fill side of the rounded corner to prevent the corner AA to bleed into the rectangle edges. - const int rounding = n + 1; - const int size = (is_filled ? (rounding + 1) : ImMax(rounding, thickness)); - const int w = size + 2; - const int h = size + 2; - - // Corner circle - const float cx = 1.0f + (float)(n + 1); - const float cy = 1.0f + (float)(n + 1); - IM_ASSERT((x + w) <= (r.x + r.w) && (y + h) <= (r.y + r.h)); // Make sure we're inside the texture bounds - const int num_lines = InitCornerGeometry(cx, cy, (float)rounding, circle_segment_max_error, line_normals, line_distances); - - // Write each slice - if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) - { - ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(x, y); - const int pitch = tex->Width; - for (int ly = 0; ly < h; ly++) - { - for (int lx = 0; lx < w; lx++) - write_ptr[lx] = SampleCornerFillOrStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines) & DEBUG_TEX_CORNER_U8(lx, h); - write_ptr += pitch; - } - } - else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) - { - ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(x, y); - const int pitch = tex->Width; - for (int ly = 0; ly < h; ly++) - { - for (int lx = 0; lx < w; lx++) - write_ptr[lx] = IM_COL32(255, 255, 255, SampleCornerFillOrStroke((float)lx + 0.5f, (float)ly + 0.5f, (float)thickness, line_normals, line_distances, num_lines)) & DEBUG_TEX_CORNER_U32(lx, h); - write_ptr += pitch; - } - } - - // Refresh UV coordinates - ImVec2 uv0 = ImVec2((float)(x + 1), (float)(y + 1)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(x + 1 + size), (float)(y + 1 + size)) * atlas->TexUvScale; - builder->TexUvCorners[n + thickness * IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); - - x += w; - row_height = ImMax(row_height, h); - } - y += row_height; - } -} - static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) { if (atlas->Flags & ImFontAtlasFlags_NoBakedLines) @@ -5063,119 +4405,59 @@ static void ImFontAtlasBuildUpdateTexDataLines(ImFontAtlas* atlas) bool add_and_draw = atlas->GetCustomRect(builder->PackIdLinesTexData, &r) == false; if (add_and_draw) { - // Register texture region for thick lines - // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row - ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT); + ImVec2i pack_size = ImVec2i(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1); builder->PackIdLinesTexData = atlas->AddCustomRect(pack_size.x, pack_size.y, &r); IM_ASSERT(builder->PackIdLinesTexData != ImFontAtlasRectId_Invalid); } + // Register texture region for thick lines + // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row + // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them + for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row { - // FIXME: Lines 0 to IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH(4) are currently never used and could be ditched, saving DETAILED_WIDTH*WIDTH_MAX - for (int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row + // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle + const int y = n; + const int line_width = n; + const int pad_left = (r.w - line_width) / 2; + const int pad_right = r.w - (pad_left + line_width); + IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels + + // Write each slice + if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) { - // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle - const int y = n; - const int line_width = n; - const int pad_left = (r.w - line_width) / 2; - const int pad_right = r.w - (pad_left + line_width); - IM_ASSERT(pad_left + line_width + pad_right == r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels + ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = 0x00; - // Write each slice - if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) - { - ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); - for (int i = 0; i < pad_left; i++) - *(write_ptr + i) = 0x00; - for (int i = 0; i < line_width; i++) - *(write_ptr + pad_left + i) = 0xFF; - for (int i = 0; i < pad_right; i++) - *(write_ptr + pad_left + line_width + i) = 0x00; - } - else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) - { - ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); - for (int i = 0; i < pad_left; i++) - *(write_ptr + i) = IM_COL32(255, 255, 255, 0); - for (int i = 0; i < line_width; i++) - *(write_ptr + pad_left + i) = IM_COL32_WHITE; - for (int i = 0; i < pad_right; i++) - *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); - } + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = 0xFF; - // Refresh UV coordinates - ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 0.5f), (float)(r.y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 0.5f), (float)(r.y + y + 1)) * atlas->TexUvScale; - float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - // Store inverse of the line-width (thickness) to the w component so that we can avoid division when selecting texture. - float inv_line_width = (line_width > 0) ? (1.0f / (float)line_width) : 0.0f; - builder->TexUvLines[n] = ImVec4(uv0.x, uv1.x, half_v, inv_line_width); + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = 0x00; } - } - - { - // Calculate super sampled line textures for smaller line widths to make transition between sizes smoother. - - // Calculate ramp used for all the textures. - ImU8 ramp[IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT]; - for (int n = 0; n < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; n++) - ramp[n] = (ImU8)(((float)n / IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT) * 255.0f); - - for (int n = 0; n < IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT; n++) + else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) { - const int y = IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n; - // For integer thickness lines the one pixel line texture looks like this: - // [ 0 | 1 | 0 ] - // :...........: - // Since the texture samples are at the center of the texel, we only use range above. - // The result after bilinear filtering is a triangle across the used uv range. - // - // To super 2x sample that signal, we end up with following texture: - // [ 0 | .5 | 1 | .5 | 0 ] - // :.......................: - // One might think that there should be 2 opaque pixels in the middle section, but no since we're super sampling the triangle signal. - const int line_width = 1 + n; - IM_ASSERT(IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + line_width + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT <= r.w && y < r.h); // Make sure we're inside the texture bounds before we start writing pixels + ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); + for (int i = 0; i < pad_left; i++) + *(write_ptr + i) = IM_COL32(255, 255, 255, 0); - // Write each slice - if (add_and_draw && tex->Format == ImTextureFormat_Alpha8) - { - ImU8* write_ptr = (ImU8*)tex->GetPixelsAt(r.x, r.y + y); - int idx = 0; - for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; i++) - write_ptr[idx++] = ramp[i]; - for (int i = 0; i < line_width; i++) - write_ptr[idx++] = 0xFF; - for (int i = IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT - 1; i >= 0; i--) - write_ptr[idx++] = ramp[i]; - while (idx < r.w) - write_ptr[idx++] = 0x0; - } - else if (add_and_draw && tex->Format == ImTextureFormat_RGBA32) - { - ImU32* write_ptr = (ImU32*)(void*)tex->GetPixelsAt(r.x, r.y + y); - int idx = 0; - for (int i = 0; i < IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT; i++) - write_ptr[idx++] = IM_COL32(255, 255, 255, ramp[i]); - for (int i = 0; i < line_width; i++) - write_ptr[idx++] = IM_COL32(255, 255, 255, 255); - for (int i = IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT - 1; i >= 0; i--) - write_ptr[idx++] = IM_COL32(255, 255, 255, ramp[i]); - while (idx < r.w) - write_ptr[idx++] = IM_COL32(255, 255, 255, 0); - } + for (int i = 0; i < line_width; i++) + *(write_ptr + pad_left + i) = IM_COL32_WHITE; - // Refresh UV coordinates - ImVec2 uv0 = ImVec2((float)(r.x + 0.5f), (float)(r.y + y)) * atlas->TexUvScale; - ImVec2 uv1 = ImVec2((float)(r.x - 0.5f + IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT * 2 + line_width), (float)(r.y + y + 1)) * atlas->TexUvScale; - float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts - // Store inverse of the line-width (thickness) to the w component so that we can avoid division when selecting texture. - float inv_line_width = 1.0f / (1.0f + (float)n / (float)IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT); - builder->TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + n] = ImVec4(uv0.x, uv1.x, half_v, inv_line_width); + for (int i = 0; i < pad_right; i++) + *(write_ptr + pad_left + line_width + i) = IM_COL32(255, 255, 255, 0); } + + // Refresh UV coordinates + ImVec2 uv0 = ImVec2((float)(r.x + pad_left - 1), (float)(r.y + y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + pad_left + line_width + 1), (float)(r.y + y + 1)) * atlas->TexUvScale; + float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts + atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v); } } +static void ImFontAtlasBuildUpdateTexDataShadow(ImFontAtlas* atlas); // FIXME-SHADOWS: Move impl here. + //----------------------------------------------------------------------------------------------------------------------------- // Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() @@ -5546,8 +4828,7 @@ void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas) if (shared_data->FontAtlas == atlas) { shared_data->TexUvWhitePixel = atlas->TexUvWhitePixel; - shared_data->TexUvLines = atlas->Builder->TexUvLines; - shared_data->TexUvCorners = atlas->Builder->TexUvCorners; + shared_data->TexUvLines = atlas->TexUvLines; } } @@ -5566,7 +4847,7 @@ static void ImFontAtlasBuildUpdateTexData(ImFontAtlas* atlas) { ImFontAtlasBuildUpdateTexDataBasic(atlas); ImFontAtlasBuildUpdateTexDataLines(atlas); - ImFontAtlasBuildUpdateTexDataCorners(atlas); + ImFontAtlasBuildUpdateTexDataShadow(atlas); } // Create a new texture, discard previous one @@ -5800,6 +5081,259 @@ void ImFontAtlasTextureCompact(ImFontAtlas* atlas) ImFontAtlasTextureRepack(atlas, new_tex_size.x, new_tex_size.y); } +// Calculates the signed distance from sample_pos to the nearest point on the rectangle defined by rect_min->rect_max +static float DistanceFromRectangle(const ImVec2& sample_pos, const ImVec2& rect_min, const ImVec2& rect_max) +{ + ImVec2 rect_centre = (rect_min + rect_max) * 0.5f; + ImVec2 rect_half_size = (rect_max - rect_min) * 0.5f; + ImVec2 local_sample_pos = sample_pos - rect_centre; + ImVec2 axis_dist = ImVec2(ImFabs(local_sample_pos.x), ImFabs(local_sample_pos.y)) - rect_half_size; + float out_dist = ImLength(ImVec2(ImMax(axis_dist.x, 0.0f), ImMax(axis_dist.y, 0.0f)), 0.00001f); + float in_dist = ImMin(ImMax(axis_dist.x, axis_dist.y), 0.0f); + return out_dist + in_dist; +} + +// Calculates the signed distance from sample_pos to the point given +static float DistanceFromPoint(const ImVec2& sample_pos, const ImVec2& point) +{ + return ImLength(sample_pos - point, 0.0f); +} + +// Perform a single Gaussian blur pass with a fixed kernel size and sigma +static void GaussianBlurPass(float* src, float* dest, int size, bool horizontal) +{ + // See http://dev.theomader.com/gaussian-kernel-calculator/ + const float coefficients[] = { 0.0f, 0.0f, 0.000003f, 0.000229f, 0.005977f, 0.060598f, 0.24173f, 0.382925f, 0.24173f, 0.060598f, 0.005977f, 0.000229f, 0.000003f, 0.0f, 0.0f }; + const int kernel_size = IM_ARRAYSIZE(coefficients); + const int sample_step = horizontal ? 1 : size; + + float* read_ptr = src; + float* write_ptr = dest; + for (int y = 0; y < size; y++) + for (int x = 0; x < size; x++) + { + float result = 0.0f; + int current_offset = (horizontal ? x : y) - ((kernel_size - 1) >> 1); + float* sample_ptr = read_ptr - (((kernel_size - 1) >> 1) * sample_step); + for (int j = 0; j < kernel_size; j++) + { + if (current_offset >= 0 && current_offset < size) + result += (*sample_ptr) * coefficients[j]; + current_offset++; + sample_ptr += sample_step; + } + read_ptr++; + *(write_ptr++) = result; + } +} + +// Perform an in-place Gaussian blur of a square array of floats with a fixed kernel size and sigma +// Uses a stack allocation for the temporary data so potentially dangerous with large size values +static void GaussianBlur(float* data, int size) +{ + // Do two passes, one from data into temp and then the second back to data again + float* temp = (float*)alloca(size * size * sizeof(float)); + GaussianBlurPass(data, temp, size, true); + GaussianBlurPass(temp, data, size, false); +} + +// Generate the actual pixel data for rounded corners in the atlas +static void ImFontAtlasBuildUpdateTexDataShadow(ImFontAtlas* atlas) +{ + // The actual size we want to reserve, including padding + const ImFontAtlasShadowTexConfig* shadow_cfg = &atlas->ShadowTexConfig; + const unsigned int effective_size = shadow_cfg->CalcRectTexSize() + shadow_cfg->GetRectTexPadding(); + const int corner_size = shadow_cfg->TexCornerSize; + const int edge_size = shadow_cfg->TexEdgeSize; + + // Because of the blur, we have to generate the full 3x3 texture here, and then we chop that down to just the 2x2 section we need later. + // 'size' correspond to the our 3x3 size, whereas 'shadow_tex_size' correspond to our 2x2 version where duplicate mirrored corners are not stored. + + // The rectangular shadow texture + ImFontAtlasRect r; + bool add_and_draw = (atlas->GetCustomRect(atlas->ShadowRectIds[0], &r) == false); + if (add_and_draw) + { + atlas->ShadowRectIds[0] = atlas->AddCustomRect(effective_size, effective_size, &r); + IM_ASSERT(atlas->ShadowRectIds[0] != ImFontAtlasRectId_Invalid); + + const int size = shadow_cfg->TexCornerSize + shadow_cfg->TexEdgeSize + shadow_cfg->TexCornerSize; + + // The bounds of the rectangle we are generating the shadow from + const ImVec2 shadow_rect_min((float)corner_size, (float)corner_size); + const ImVec2 shadow_rect_max((float)(corner_size + edge_size), (float)(corner_size + edge_size)); + + // Remove the padding we added + const int padding = shadow_cfg->GetRectTexPadding(); + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w -= (unsigned short)padding * 2; + r.h -= (unsigned short)padding * 2; + + // Generate distance field + // We draw the actual texture content by evaluating the distance field for the inner rectangle + float* tex_data = (float*)alloca(size * size * sizeof(float)); + for (int y = 0; y < size; y++) + for (int x = 0; x < size; x++) + { + float dist = DistanceFromRectangle(ImVec2((float)x, (float)y), shadow_rect_min, shadow_rect_max); + float alpha = 1.0f - ImMin(ImMax(dist + shadow_cfg->TexDistanceFieldOffset, 0.0f) / ImMax(shadow_cfg->TexCornerSize + shadow_cfg->TexDistanceFieldOffset, 0.001f), 1.0f); + alpha = ImPow(alpha, shadow_cfg->TexFalloffPower); // Apply power curve to give a nicer falloff + tex_data[x + (y * size)] = alpha; + } + + // Blur + if (shadow_cfg->TexBlur) + GaussianBlur(tex_data, size); + + // Copy to texture, truncating to the actual required texture size (the bottom/right of the source data is chopped off, as we don't need it - see below). The truncated size is essentially the top 2x2 of our data, plus a little bit of padding for sampling. + ImTextureData* tex = atlas->TexData; + const int shadow_tex_size = shadow_cfg->CalcRectTexSize(); + for (int y = 0; y < shadow_tex_size; y++) + for (int x = 0; x < shadow_tex_size; x++) + { + const float alpha_f = tex_data[x + (y * size)]; + const unsigned char alpha_8 = (unsigned char)(0xFF * alpha_f); + + // FIXME-SHADOWS: May be optimized. + switch (atlas->TexData->Format) + { + case ImTextureFormat_Alpha8: + { + ImU8* out_p = (ImU8*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = alpha_8; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = IM_COL32(255, 255, 255, alpha_8);; + break; + } + } + } + } + + // Refresh UV coordinates + // Generate UVs for each of the nine sections, which are arranged in a 3x3 grid starting from 0 in the top-left and going across then down + if (atlas->GetCustomRect(atlas->ShadowRectIds[0], &r)) + { + // Remove the padding we added + const int padding = shadow_cfg->GetRectTexPadding(); + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w -= (unsigned short)padding * 2; + r.h -= (unsigned short)padding * 2; + + for (int i = 0; i < 9; i++) + { + // The third row/column of the 3x3 grid are generated by flipping the appropriate chunks of the upper 2x2 grid. + bool flip_h = false; // Do we need to flip the UVs horizontally? + bool flip_v = false; // Do we need to flip the UVs vertically? + + ImFontAtlasRect sub_rect = r; + switch (i % 3) + { + case 0: sub_rect.w = (unsigned short)corner_size; break; + case 1: sub_rect.x += (unsigned short)corner_size; sub_rect.w = (unsigned short)edge_size; break; + case 2: sub_rect.w = (unsigned short)corner_size; flip_h = true; break; + } + + switch (i / 3) + { + case 0: sub_rect.h = (unsigned short)corner_size; break; + case 1: sub_rect.y += (unsigned short)corner_size; sub_rect.h = (unsigned short)edge_size; break; + case 2: sub_rect.h = (unsigned short)corner_size; flip_v = true; break; + } + + // FIXME-SHADOWS: caching UV !! + ImVec2 uv0 = ImVec2((float)(sub_rect.x), (float)(sub_rect.y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(sub_rect.x + sub_rect.w), (float)(sub_rect.y + sub_rect.h)) * atlas->TexUvScale; + atlas->ShadowRectUvs[i] = ImVec4(flip_h ? uv1.x : uv0.x, flip_v ? uv1.y : uv0.y, flip_h ? uv0.x : uv1.x, flip_v ? uv0.y : uv1.y); + } + } + + // The convex shape shadow texture + add_and_draw = (atlas->GetCustomRect(atlas->ShadowRectIds[1], &r) == false); + if (add_and_draw) + { + atlas->ShadowRectIds[1] = atlas->AddCustomRect(shadow_cfg->CalcConvexTexWidth() + shadow_cfg->GetConvexTexPadding(), shadow_cfg->CalcConvexTexHeight() + shadow_cfg->GetConvexTexPadding(), &r); + IM_ASSERT(atlas->ShadowRectIds[1] != ImFontAtlasRectId_Invalid); + + const int size = shadow_cfg->TexCornerSize * 2; + const int padding = shadow_cfg->GetConvexTexPadding(); + + // Generate distance field + // We draw the actual texture content by evaluating the distance field for the distance from a center point + ImVec2 center_point(size * 0.5f, size * 0.5f); + float* tex_data = (float*)alloca(size * size * sizeof(float)); + for (int y = 0; y < size; y++) + for (int x = 0; x < size; x++) + { + float dist = DistanceFromPoint(ImVec2((float)x, (float)y), center_point); + float alpha = 1.0f - ImMin(ImMax((float)dist + shadow_cfg->TexDistanceFieldOffset, 0.0f) / ImMax((float)shadow_cfg->TexCornerSize + shadow_cfg->TexDistanceFieldOffset, 0.001f), 1.0f); + alpha = ImPow(alpha, shadow_cfg->TexFalloffPower); // Apply power curve to give a nicer falloff + tex_data[x + (y * size)] = alpha; + } + + // Blur + if (shadow_cfg->TexBlur) + GaussianBlur(tex_data, size); + + // Copy to texture, truncating to the actual required texture size (the bottom/right of the source data is chopped off, as we don't need it - see below) + // We push the data down and right by the amount we padded the top of the texture (see CalcConvexTexWidth/CalcConvexTexHeight) for details + const int padded_size = (int)(shadow_cfg->TexCornerSize / ImCos(IM_PI * 0.25f)); + const int src_x_offset = padding + (padded_size - shadow_cfg->TexCornerSize); + const int src_y_offset = padding + (padded_size - shadow_cfg->TexCornerSize); + + const int tex_width = shadow_cfg->CalcConvexTexWidth(); + const int tex_height = shadow_cfg->CalcConvexTexHeight(); + ImTextureData* tex = atlas->TexData; + for (int y = 0; y < tex_height; y++) + for (int x = 0; x < tex_width; x++) + { + const int src_x = ImClamp(x - src_x_offset, 0, size - 1); + const int src_y = ImClamp(y - src_y_offset, 0, size - 1); + const float alpha_f = tex_data[src_x + (src_y * size)]; + const unsigned char alpha_8 = (unsigned char)(0xFF * alpha_f); + + // FIXME-SHADOWS: May be optimized. + switch (atlas->TexData->Format) + { + case ImTextureFormat_Alpha8: + { + ImU8* out_p = (ImU8*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = alpha_8; + break; + } + case ImTextureFormat_RGBA32: + { + ImU32* out_p = (ImU32*)(void*)tex->GetPixelsAt(r.x + x, r.y + y); + *out_p = IM_COL32(255, 255, 255, alpha_8);; + break; + } + } + } + } + + // Refresh UV coordinates + if (atlas->GetCustomRect(atlas->ShadowRectIds[1], &r)) + { + // Remove the padding we added + const int padding = shadow_cfg->GetConvexTexPadding(); + const int tex_width = shadow_cfg->CalcConvexTexWidth(); + const int tex_height = shadow_cfg->CalcConvexTexHeight(); + r.x += (unsigned short)padding; + r.y += (unsigned short)padding; + r.w = (unsigned short)(tex_width - (padding * 2)); + r.h = (unsigned short)(tex_height - (padding * 2)); + + ImVec2 uv0 = ImVec2((float)(r.x), (float)(r.y)) * atlas->TexUvScale; + ImVec2 uv1 = ImVec2((float)(r.x + r.w), (float)(r.y + r.h)) * atlas->TexUvScale; + atlas->ShadowRectUvs[9] = ImVec4(uv0.x, uv0.y, uv1.x, uv1.y); + } +} + // Start packing over current empty texture void ImFontAtlasBuildInit(ImFontAtlas* atlas) { @@ -6038,46 +5572,11 @@ static void ImFontBaked_BuildGrowIndex(ImFontBaked* baked, int new_size) baked->IndexLookup.resize(new_size, IM_FONTGLYPH_INDEX_UNUSED); } -// Remap a codepoint to another codepoint -void ImFont::AddRemapCodepoint(ImWchar from_codepoint, ImWchar to_codepoint) -{ - ImU32 data = (ImU32)to_codepoint; - IM_ASSERT((data & (1u << 31)) == 0); - RemapPairs.SetInt((ImGuiID)from_codepoint, (int)data); -} - -static const int IMFONT_REMAPVALUE_GLYPHIDX_SHIFT = 0; -static const int IMFONT_REMAPVALUE_GLYPHIDX_MASK = 0xFFFF; -static const int IMFONT_REMAPVALUE_FONTSRCIDX_SHIFT = 16; -static const int IMFONT_REMAPVALUE_FONTSRCIDX_MASK = 0xFF0000; - -// Remap a codepoint to a raw glyph index inside the font. Allows accessing glyphs which are not mapped to codepoints. (#9559) -// font_src_idx = index in font->Sources[], or -1 for last added source. -// glyph_idx = index in TTF or OTF file. -void ImFont::AddRemapCodepointToGlyphIndex(ImWchar from_codepoint, int font_src_idx, int glyph_idx) -{ - if (font_src_idx == -1) - font_src_idx = Sources.Size - 1; - IM_ASSERT(font_src_idx >= 0 && font_src_idx < Sources.Size && ((font_src_idx << IMFONT_REMAPVALUE_FONTSRCIDX_SHIFT) & ~IMFONT_REMAPVALUE_FONTSRCIDX_MASK) == 0); - IM_ASSERT(glyph_idx >= 0 && ((glyph_idx << IMFONT_REMAPVALUE_GLYPHIDX_SHIFT) & ~IMFONT_REMAPVALUE_GLYPHIDX_MASK) == 0); - ImU32 data = ((ImU32)glyph_idx << IMFONT_REMAPVALUE_GLYPHIDX_SHIFT) | (font_src_idx << IMFONT_REMAPVALUE_FONTSRCIDX_SHIFT) | (1u << 31); - RemapPairs.SetInt((ImGuiID)from_codepoint, (int)data); -} - -static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar codepoint, ImWchar* out_codepoint, int* out_font_src_idx, int* out_glyph_idx) +static void ImFontAtlas_FontHookRemapCodepoint(ImFontAtlas* atlas, ImFont* font, ImWchar* c) { IM_UNUSED(atlas); - if (font->RemapPairs.Data.Size == 0) - return; - ImU32 data = (ImU32)font->RemapPairs.GetInt((ImGuiID)codepoint, (int)codepoint); - if (data & (1u << 31)) - { - *out_codepoint = (ImWchar)-1; - *out_font_src_idx = (data & IMFONT_REMAPVALUE_FONTSRCIDX_MASK) >> IMFONT_REMAPVALUE_FONTSRCIDX_SHIFT; - *out_glyph_idx = (data & IMFONT_REMAPVALUE_GLYPHIDX_MASK) >> IMFONT_REMAPVALUE_GLYPHIDX_SHIFT; - return; - } - *out_codepoint = (ImWchar)data; + if (font->RemapPairs.Data.Size != 0) + *c = (ImWchar)font->RemapPairs.GetInt((ImGuiID)*c, (int)*c); } static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codepoint, float* only_load_advance_x) @@ -6094,8 +5593,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep // User remapping hooks ImWchar src_codepoint = codepoint; - int src_font_idx = -1, src_glyph_idx = -1; - ImFontAtlas_FontHookRemapCodepoint(atlas, font, codepoint, &src_codepoint, &src_font_idx, &src_glyph_idx); + ImFontAtlas_FontHookRemapCodepoint(atlas, font, &codepoint); //char utf8_buf[5]; //IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)\n", (unsigned int)codepoint, ImTextCharToUtf8(utf8_buf, (unsigned int)codepoint)); @@ -6108,47 +5606,35 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep // Call backend char* loader_user_data_p = (char*)baked->FontLoaderDatas; - char* loader_user_data_p_next = NULL; - for (int src_n = 0; src_n < font->Sources.Size; src_n++, loader_user_data_p = loader_user_data_p_next) + int src_n = 0; + for (ImFontConfig* src : font->Sources) { - ImFontConfig* src = font->Sources[src_n]; const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - loader_user_data_p_next = loader_user_data_p + loader->FontBakedSrcLoaderDataSize; - - int glyph_index; - if (src_codepoint != (ImWchar)-1) + if (!src->GlyphExcludeRanges || ImFontAtlasBuildAcceptCodepointForSource(src, codepoint)) { - if (src->GlyphExcludeRanges && !ImFontAtlasBuildAcceptCodepointForSource(src, src_codepoint)) - continue; - glyph_index = loader->FontSrcGetGlyphIndexFromCodepoint(atlas, src, src_codepoint); - } - else - { - if (src_n != src_font_idx) - continue; - glyph_index = src_glyph_idx; - } - if (glyph_index == 0) - continue; - - if (only_load_advance_x == NULL) - { - ImFontGlyph glyph_buf; - glyph_buf.Codepoint = codepoint; - if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, glyph_index, &glyph_buf, NULL)) - continue; - // FIXME: Add hooks for e.g. #7962 - glyph_buf.SourceIdx = src_n; - return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); - } - else - { - // Special mode but only loading glyphs metrics. Will rasterize and pack later. - if (!loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, glyph_index, NULL, only_load_advance_x)) - continue; - ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x); - return NULL; + if (only_load_advance_x == NULL) + { + ImFontGlyph glyph_buf; + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, &glyph_buf, NULL)) + { + // FIXME: Add hooks for e.g. #7962 + glyph_buf.Codepoint = src_codepoint; + glyph_buf.SourceIdx = src_n; + return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, &glyph_buf); + } + } + else + { + // Special mode but only loading glyphs metrics. Will rasterize and pack later. + if (loader->FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, NULL, only_load_advance_x)) + { + ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, *only_load_advance_x); + return NULL; + } + } } + loader_user_data_p += loader->FontBakedSrcLoaderDataSize; + src_n++; } // Lazily load fallback glyph @@ -6164,7 +5650,7 @@ static ImFontGlyph* ImFontBaked_BuildLoadGlyph(ImFontBaked* baked, ImWchar codep return NULL; } -float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint) +static float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint) { if (baked->Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE || baked->LoadNoRenderOnLayout) { @@ -6232,8 +5718,10 @@ struct ImGui_ImplStbTrueType_FontSrcData float ScaleFactor; }; -static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas*, ImFontConfig* src) +static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src) { + IM_UNUSED(atlas); + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = IM_NEW(ImGui_ImplStbTrueType_FontSrcData); IM_ASSERT(src->FontLoaderData == NULL); @@ -6265,27 +5753,29 @@ static bool ImGui_ImplStbTrueType_FontSrcInit(ImFontAtlas*, ImFontConfig* src) return true; } -static void ImGui_ImplStbTrueType_FontSrcDestroy(ImFontAtlas*, ImFontConfig* src) +static void ImGui_ImplStbTrueType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) { + IM_UNUSED(atlas); ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; IM_DELETE(bd_font_data); src->FontLoaderData = NULL; } -static int ImGui_ImplStbTrueType_FontSrcGetGlyphIndexFromCodepoint(ImFontAtlas*, ImFontConfig* src, ImWchar codepoint) +static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) { + IM_UNUSED(atlas); + ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; - return stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + IM_ASSERT(bd_font_data != NULL); + + int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + return glyph_index != 0; } -static bool ImGui_ImplStbTrueType_FontSrcContainsGlyph(ImFontAtlas*, ImFontConfig* src, int glyph_index) +static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*) { - ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; - return glyph_index > 0 && glyph_index < bd_font_data->FontInfo.numGlyphs; -} + IM_UNUSED(atlas); -static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas*, ImFontConfig* src, ImFontBaked* baked, void*) -{ ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; if (src->MergeMode == false) { @@ -6296,17 +5786,18 @@ static bool ImGui_ImplStbTrueType_FontBakedInit(ImFontAtlas*, ImFontConfig* src, stbtt_GetFontVMetrics(&bd_font_data->FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); baked->Ascent = ImCeil(unscaled_ascent * scale_for_layout); baked->Descent = ImFloor(unscaled_descent * scale_for_layout); - // FIXME: round to rasterizer density? (#9348) } return true; } -static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, int glyph_index, ImFontGlyph* out_glyph, float* out_advance_x) +static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void*, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) { // Search for first font which has the glyph ImGui_ImplStbTrueType_FontSrcData* bd_font_data = (ImGui_ImplStbTrueType_FontSrcData*)src->FontLoaderData; IM_ASSERT(bd_font_data); - IM_ASSERT(glyph_index != 0); + int glyph_index = stbtt_FindGlyphIndex(&bd_font_data->FontInfo, (int)codepoint); + if (glyph_index == 0) + return false; // Fonts unit to pixels int oversample_h, oversample_v; @@ -6331,6 +5822,7 @@ static bool ImGui_ImplStbTrueType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontC } // Prepare glyph + out_glyph->Codepoint = codepoint; out_glyph->AdvanceX = advance * scale_for_layout; // Pack and retrieve position inside texture atlas @@ -6392,7 +5884,6 @@ const ImFontLoader* ImFontAtlasGetFontLoaderForStbTruetype() loader.Name = "stb_truetype"; loader.FontSrcInit = ImGui_ImplStbTrueType_FontSrcInit; loader.FontSrcDestroy = ImGui_ImplStbTrueType_FontSrcDestroy; - loader.FontSrcGetGlyphIndexFromCodepoint = ImGui_ImplStbTrueType_FontSrcGetGlyphIndexFromCodepoint; loader.FontSrcContainsGlyph = ImGui_ImplStbTrueType_FontSrcContainsGlyph; loader.FontBakedInit = ImGui_ImplStbTrueType_FontBakedInit; loader.FontBakedDestroy = NULL; @@ -6866,6 +6357,11 @@ void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontAtlasTextureBlockQueueUpload(atlas, tex, r->x, r->y, r->w, r->h); } +void ImFont::AddRemapChar(ImWchar from_codepoint, ImWchar to_codepoint) +{ + RemapPairs.SetInt((ImGuiID)from_codepoint, (int)to_codepoint); +} + // Find glyph, load if necessary, return fallback if missing ImFontGlyph* ImFontBaked::FindGlyph(ImWchar c) { @@ -6915,19 +6411,11 @@ bool ImFontBaked::IsGlyphLoaded(ImWchar c) bool ImFont::IsGlyphInFont(ImWchar c) { ImFontAtlas* atlas = OwnerAtlas; - ImWchar src_codepoint = c; - int src_font_idx = -1, src_glyph_idx = -1; - ImFontAtlas_FontHookRemapCodepoint(atlas, this, c, &src_codepoint, &src_font_idx, &src_glyph_idx); - if (src_font_idx != -1) - { - ImFontConfig* src = Sources[src_font_idx]; - const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - return loader->FontSrcContainsGlyph ? loader->FontSrcContainsGlyph(atlas, src, src_glyph_idx) : false; - } + ImFontAtlas_FontHookRemapCodepoint(atlas, this, &c); for (ImFontConfig* src : Sources) { const ImFontLoader* loader = src->FontLoader ? src->FontLoader : atlas->FontLoader; - if (loader->FontSrcGetGlyphIndexFromCodepoint(atlas, src, c) != 0) + if (loader->FontSrcContainsGlyph != NULL && loader->FontSrcContainsGlyph(atlas, src, c)) return true; } return false; @@ -7307,7 +6795,7 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, const ImVec2& pos, Im float scale = (size >= 0.0f) ? (size / baked->Size) : 1.0f; float x = pos.x; float y = pos.y; - if ((draw_list->Flags & ImDrawFlags_TextNoPixelSnap) == 0) + if ((draw_list->Flags & ImDrawListFlags_TextNoPixelSnap) == 0) { x = IM_TRUNC(x); y = IM_TRUNC(y); @@ -7349,8 +6837,7 @@ begin: float y = pos.y; if (y > clip_rect.w) return; - flags |= draw_list->Flags; - if ((flags & ImDrawFlags_TextNoPixelSnap) == 0) + if ((draw_list->Flags & ImDrawListFlags_TextNoPixelSnap) == 0) { x = IM_TRUNC(x); y = IM_TRUNC(y); @@ -7559,6 +7046,7 @@ begin: // - RenderArrow() // - RenderBullet() // - RenderCheckMark() +// - RenderArrowPointingAt() // - RenderRectFilledInRangeH() // - RenderRectFilledWithHole() //----------------------------------------------------------------------------- @@ -7566,47 +7054,36 @@ begin: // - RenderColorRectWithAlphaCheckerboard() //----------------------------------------------------------------------------- -static const ImVec2 g_ImGuiDirCosSin[4] = { { -1.0f, 0.0f }, { +1.0f, 0.0f }, { 0.0f, -1.0f }, { 0.0f, +1.0f } }; - -// arrow_h, arrow_w, arrow_th are normalized: 0.0f..1.0f -// arrow_th: 0.0f == fill, >0.0f == stroke weight. -void ImGui::RenderArrowEx(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float cos_a, float sin_a, float scale, ImVec2 arrow_sizes, float arrow_th) -{ - const bool is_fill = (arrow_th <= 0.0f); - const float r = draw_list->_Data->FontSize * 0.50f * scale; - const float thickness = is_fill ? 0.0f : IM_ROUND(ImClamp(r * arrow_th, 1.0f, r * 0.5f)); - - // Bias for shape to feel more centered - const float bias = is_fill ? (r * 0.05f) : (thickness * 0.8f * 0.7071f); - const ImVec2 center = ImVec2(pos.x + r + bias * cos_a, pos.y + r + bias * sin_a); - - const float arrow_h = arrow_sizes.y * r; - const float arrow_w = arrow_sizes.x * r; - ImVec2 p[3]; - p[0] = ImVec2(center.x - arrow_h * cos_a - arrow_w * -sin_a, center.y - arrow_h * sin_a - arrow_w * cos_a); - p[1] = ImVec2(center.x + arrow_h * cos_a, center.y + arrow_h * sin_a); - p[2] = ImVec2(center.x - arrow_h * cos_a + arrow_w * -sin_a, center.y - arrow_h * sin_a + arrow_w * cos_a); - - // Pixel align when at a right angle - if (is_fill && (cos_a * sin_a >= -FLT_EPSILON) && (cos_a * sin_a <= FLT_EPSILON)) - { - p[0] = ImRoundSigned(p[0]); - p[1] = ImRoundSigned(p[1]); - p[2] = ImRoundSigned(p[2]); - } - - if (is_fill) - draw_list->AddConvexPolyFilled(p, 3, col); - else - draw_list->_AddPolyline(p, 3, col, thickness, ImDrawFlags_StrokeInside | ImDrawFlags_AALineEnds, FLT_MAX); // FIXME-OPT: baked filled shape? -} - -// Render an arrow aimed to be aligned with text. +// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale) { - ImGuiContext& g = *GImGui; - ImVec2 cos_sin = g_ImGuiDirCosSin[dir]; - RenderArrowEx(draw_list, pos, col, cos_sin.x, cos_sin.y, scale, g.Style.SymbolArrowSizeFactor, g.Style.SymbolArrowThicknessFactor); + const float h = draw_list->_Data->FontSize * 1.00f; + float r = h * 0.40f * scale; + ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); + + ImVec2 a, b, c; + switch (dir) + { + case ImGuiDir_Up: + case ImGuiDir_Down: + if (dir == ImGuiDir_Up) r = -r; + a = ImVec2(+0.000f, +0.750f) * r; + b = ImVec2(-0.866f, -0.750f) * r; + c = ImVec2(+0.866f, -0.750f) * r; + break; + case ImGuiDir_Left: + case ImGuiDir_Right: + if (dir == ImGuiDir_Left) r = -r; + a = ImVec2(+0.750f, +0.000f) * r; + b = ImVec2(-0.750f, +0.866f) * r; + c = ImVec2(-0.750f, -0.866f) * r; + break; + case ImGuiDir_None: + case ImGuiDir_COUNT: + IM_ASSERT(0); + break; + } + draw_list->AddTriangleFilled(center + a, center + b, center + c, col); } void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col) @@ -7628,7 +7105,20 @@ void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float draw_list->PathLineTo(ImVec2(bx - third, by - third)); draw_list->PathLineTo(ImVec2(bx, by)); draw_list->PathLineTo(ImVec2(bx + third * 2.0f, by - third * 2.0f)); - draw_list->PathStroke(col, thickness, ImDrawFlags_AALineEnds); + draw_list->PathStroke(col, thickness); +} + +// Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. +void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col) +{ + switch (direction) + { + case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return; + case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return; + case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return; + case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return; + case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings + } } static inline float ImAcos01(float x) @@ -7697,7 +7187,7 @@ void ImGui::RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e); // BR } } - draw_list->PathFillConvex(col, ImDrawFlags_JoinMiter); + draw_list->PathFillConvex(col); } void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding) @@ -7706,14 +7196,14 @@ void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const bool fill_R = (inner.Max.x < outer.Max.x); const bool fill_U = (inner.Min.y > outer.Min.y); const bool fill_D = (inner.Max.y < outer.Max.y); - if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, ImDrawFlags_RoundNone | (fill_U ? 0 : ImDrawFlags_RoundTopLeft) | (fill_D ? 0 : ImDrawFlags_RoundBottomLeft)); - if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, ImDrawFlags_RoundNone | (fill_U ? 0 : ImDrawFlags_RoundTopRight) | (fill_D ? 0 : ImDrawFlags_RoundBottomRight)); - if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundNone | (fill_L ? 0 : ImDrawFlags_RoundTopLeft) | (fill_R ? 0 : ImDrawFlags_RoundTopRight)); - if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundNone | (fill_L ? 0 : ImDrawFlags_RoundBottomLeft) | (fill_R ? 0 : ImDrawFlags_RoundBottomRight)); - if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawFlags_RoundTopLeft); - if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundTopRight); - if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawFlags_RoundBottomLeft); - if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundBottomRight); + if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomLeft)); + if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopRight) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomRight)); + if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersTopRight)); + if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersBottomLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersBottomRight)); + if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopLeft); + if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopRight); + if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomLeft); + if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomRight); } ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold) @@ -7722,9 +7212,9 @@ ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRe bool round_r = r_in.Max.x >= r_outer.Max.x - threshold; bool round_t = r_in.Min.y <= r_outer.Min.y + threshold; bool round_b = r_in.Max.y >= r_outer.Max.y - threshold; - return ImDrawFlags_RoundNone - | ((round_t && round_l) ? ImDrawFlags_RoundTopLeft : 0) | ((round_t && round_r) ? ImDrawFlags_RoundTopRight : 0) - | ((round_b && round_l) ? ImDrawFlags_RoundBottomLeft : 0) | ((round_b && round_r) ? ImDrawFlags_RoundBottomRight : 0); + return ImDrawFlags_RoundCornersNone + | ((round_t && round_l) ? ImDrawFlags_RoundCornersTopLeft : 0) | ((round_t && round_r) ? ImDrawFlags_RoundCornersTopRight : 0) + | ((round_b && round_l) ? ImDrawFlags_RoundCornersBottomLeft : 0) | ((round_b && round_r) ? ImDrawFlags_RoundCornersBottomRight : 0); } // Helper for ColorPicker4() @@ -7732,8 +7222,8 @@ ImDrawFlags ImGui::CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRe // Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether. void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float alpha, float grid_step, ImVec2 grid_off, float rounding, ImDrawFlags flags) { - if ((flags & ImDrawFlags_RoundMask_) == 0) - flags = ImDrawFlags_RoundAll; + if ((flags & ImDrawFlags_RoundCornersMask_) == 0) + flags = ImDrawFlags_RoundCornersAll; if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF) { IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f); @@ -7759,12 +7249,12 @@ void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p float x1 = ImClamp((float)(int)x, p_min.x, p_max.x), x2 = ImMin((float)(int)(x + grid_step), p_max.x); if (x2 <= x1) continue; - ImDrawFlags cell_flags = ImDrawFlags_RoundNone; // FIXME: Could use CalcRoundingFlagsForRectInRect() - if (y1 <= p_min.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundTopLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundTopRight; } - if (y2 >= p_max.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundBottomLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundBottomRight; } + ImDrawFlags cell_flags = ImDrawFlags_RoundCornersNone; // FIXME: Could use CalcRoundingFlagsForRectInRect() + if (y1 <= p_min.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersTopLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersTopRight; } + if (y2 >= p_max.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersBottomLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersBottomRight; } // Combine flags - cell_flags = (flags == ImDrawFlags_RoundNone || cell_flags == ImDrawFlags_RoundNone) ? ImDrawFlags_RoundNone : (cell_flags & flags); + cell_flags = (flags == ImDrawFlags_RoundCornersNone || cell_flags == ImDrawFlags_RoundCornersNone) ? ImDrawFlags_RoundCornersNone : (cell_flags & flags); ImU32 col_bg = dual_layer ? col_bg2 : (((yi + xi) & 1) ? col_bg2 : col_bg1); draw_list->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg, rounding, cell_flags); } diff --git a/imgui_internal.h b/imgui_internal.h index 9ab5bea1d..96f52bce3 100644 --- a/imgui_internal.h +++ b/imgui_internal.h @@ -1,4 +1,4 @@ -// dear imgui, v1.93.1 WIP +// dear imgui, v1.93.0 WIP // (internal structures/api) // You may use this file to debug, understand or extend Dear ImGui features but we don't provide any guarantee of forward compatibility. @@ -126,7 +126,7 @@ Index of this file: // Enable stb_truetype by default unless FreeType is enabled. // You can compile with both by defining both IMGUI_ENABLE_FREETYPE and IMGUI_ENABLE_STB_TRUETYPE together. -#if !defined(IMGUI_ENABLE_FREETYPE) && !defined(IMGUI_ENABLE_STB_TRUETYPE) && !defined(IMGUI_DISABLE_STB_TRUETYPE) +#ifndef IMGUI_ENABLE_FREETYPE #define IMGUI_ENABLE_STB_TRUETYPE #endif @@ -173,6 +173,7 @@ struct ImGuiOldColumns; // Storage data for a columns set for legacy struct ImGuiPopupData; // Storage for current popup stack struct ImGuiSettingsHandler; // Storage for one type registered in the .ini file struct ImGuiStyleMod; // Stacked style modifier, backup of modified data so we can restore it +struct ImGuiStyleShadowTexConfig; // Shadow Texture baking config struct ImGuiStyleVarInfo; // Style variable information (e.g. to access style variables from an enum) struct ImGuiTabBar; // Storage for a tab bar struct ImGuiTabItem; // Storage for a tab item (within a tab bar) @@ -284,8 +285,8 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer #define IM_MEMALIGN(_OFF,_ALIGN) (((_OFF) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align e.g. IM_ALIGN(0,4)=0, IM_ALIGN(1,4)=4, IM_ALIGN(4,4)=4, IM_ALIGN(5,4)=8 #define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose #define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 -#define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // Positive values only! == ImTrunc() which is not inlined in MSVC debug builds -#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // Positive values only! == ImRoundPositive() which is not inlined in MSVC debug builds. +#define IM_TRUNC(_VAL) ((float)(int)(_VAL)) // Positive values only! ImTrunc() is not inlined in MSVC debug builds +#define IM_ROUND(_VAL) ((float)(int)((_VAL) + 0.5f)) // Positive values only! //#define IM_FLOOR IM_TRUNC // [OBSOLETE] Renamed in 1.90.0 (Sept 2023) // Hint for branch prediction @@ -368,7 +369,6 @@ extern IMGUI_API ImGuiContext* GImGui; // Current implicit context pointer // - Helper: ImPool<> // - Helper: ImChunkStream<> // - Helper: ImGuiTextIndex -// - Helper: ImGuiTextFilterItem // - Helper: ImGuiStorage //----------------------------------------------------------------------------- @@ -408,7 +408,7 @@ IMGUI_API const char* ImStrSkipBlank(const char* str); IMGUI_API int ImStrlenW(const ImWchar* str); // Computer string length (ImWchar string) IMGUI_API const char* ImStrbol(const char* buf_mid_line, const char* buf_begin); // Find beginning-of-line IM_MSVC_RUNTIME_CHECKS_OFF -inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c & ~32 : c; } +inline char ImToUpper(char c) { return (c >= 'a' && c <= 'z') ? c &= ~32 : c; } inline bool ImCharIsBlankA(char c) { return c == ' ' || c == '\t'; } inline bool ImCharIsBlankW(unsigned int c) { return c == ' ' || c == '\t' || c == 0x3000; } inline bool ImCharIsXdigitA(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } @@ -506,23 +506,13 @@ inline float ImSign(float x) { return (x < 0.0f) ? -1.0f : (x > 0.0f inline double ImSign(double x) { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; } #ifdef IMGUI_ENABLE_SSE inline float ImRsqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); } -// Converge to more precise solution using single step of Newton-Raphson method, repeating increases precision -inline float ImRsqrtPrecise(float x) { const float r = _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); return r * (1.5f - x * 0.5f * r * r); } #else inline float ImRsqrt(float x) { return 1.0f / sqrtf(x); } -inline float ImRsqrtPrecise(float x) { return 1.0f / sqrtf(x); } #endif -inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } +inline double ImRsqrt(double x) { return 1.0 / sqrt(x); } #endif - // - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double -// (Specialized version ensure that runtime-check pragmas/macros are applied with caller settings. Template version are less reliable in this regards) -inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } -inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } -inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } -inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } -inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } -inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +// (Exceptionally using templates here but we could also redefine them for those types) template T ImMin(T lhs, T rhs) { return lhs < rhs ? lhs : rhs; } template T ImMax(T lhs, T rhs) { return lhs >= rhs ? lhs : rhs; } template T ImClamp(T v, T mn, T mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } @@ -531,9 +521,6 @@ template T ImLerp(T a, T b, float t) { return template void ImSwap(T& a, T& b) { T tmp = a; a = b; b = tmp; } template T ImAddClampOverflow(T a, T b, T mn, T mx) { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; } template T ImSubClampOverflow(T a, T b, T mn, T mx) { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; } -inline float ImMod(float a, float b) { return ImFmod(a, b); } -inline double ImMod(double a, double b) { return (double)ImFmod((float)a, (float)b); } // FIXME -template T ImMod(T a, T b) { return a % b; } // - Misc maths helpers inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); } inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); } @@ -544,18 +531,15 @@ inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) { return inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } inline float ImLengthSqr(const ImVec2& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y); } inline float ImLengthSqr(const ImVec4& lhs) { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); } +inline float ImLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImSqrt(d); return fail_value; } inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; } -inline float ImTrunc(float f) { return (float)(int)(f); } // == IM_TRUNC() +inline float ImTrunc(float f) { return (float)(int)(f); } inline ImVec2 ImTrunc(const ImVec2& v) { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); } -inline float ImTrunc64(float f) { return (float)(ImS64)(f); } inline float ImFloor(float f) { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf() inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2(ImFloor(v.x), ImFloor(v.y)); } -inline float ImRoundPositive(float f) { return (float)(int)(f + 0.5f); } // == IM_ROUND(). Positive values only. -inline float ImRoundPositive64(float f) { return (float)(ImS64)(f + 0.5f); } // Positive values only. -inline float ImRoundSigned(float f) { return (float)(int)(f >= 0.0f ? f + 0.5f : f - 0.5f); } -inline ImVec2 ImRoundSigned(const ImVec2& v) { return ImVec2((float)(int)(v.x >= 0.0f ? v.x + 0.5f : v.x - 0.5f), (float)(int)(v.y >= 0.0f ? v.y + 0.5f : v.y - 0.5f)); } -inline float ImRoundSigned64(float f) { return (float)(ImS64)(f >= 0.0f ? f + 0.5f : f - 0.5f); } -inline float ImCeilFast(float f) { int i = (int)f; return (float)(i + (f > (float)i)); } // Consider using the bit-hack version (search for "0x1p120f"). +inline float ImTrunc64(float f) { return (float)(ImS64)(f); } +inline float ImRound64(float f) { return (float)(ImS64)(f + 0.5f); } // FIXME: Positive values only. +inline float ImCeilFast(float f) { int i = (int)f; return (float)(i + (f > (float)i)); } // Consider using the the bit-hack version (search for "0x1p120f"). inline int ImModPositive(int a, int b) { return (a + b) % b; } inline float ImDot(const ImVec2& a, const ImVec2& b) { return a.x * b.x + a.y * b.y; } inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a) { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); } @@ -564,23 +548,6 @@ inline float ImLinearRemapClamp(float s0, float s1, float d0, float d1, float x inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); } inline bool ImIsFloatAboveGuaranteedIntegerPrecision(float f) { return f <= -16777216 || f >= 16777216; } inline float ImExponentialMovingAverage(float avg, float sample, int n){ avg -= avg / (float)n; avg += sample / (float)n; return avg; } - -inline bool ImIsTruncated(float x) { return (float)(int)x == x; } -#ifdef IMGUI_ENABLE_SSE -// Returns true if all parameters are whole numbers. -inline bool ImIsTruncated4(float x, float y, float z, float w) -{ - __m128 v = _mm_set_ps(x, y, z, w); - __m128i i = _mm_cvttps_epi32(v); - return _mm_movemask_ps(_mm_cmpeq_ps(v, _mm_cvtepi32_ps(i))) == 0xF; -} -#else -inline bool ImIsTruncated4(float x, float y, float z, float w) -{ - return (float)(int)x == x && (float)(int)y == y && (float)(int)z == z && (float)(int)w == w; -} -#endif - IM_MSVC_RUNTIME_CHECKS_RESTORE // Helpers: Geometry @@ -658,7 +625,6 @@ struct IMGUI_API ImRect void TranslateY(float dy) { Min.y += dy; Max.y += dy; } void ClipWith(const ImRect& r) { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); } // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. void ClipWithFull(const ImRect& r) { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped. - void ShrinkClamp(const ImVec2& inset_min, const ImVec2& inset_max) { Min.x = ImMin(Min.x + inset_min.x, Max.x); Min.y = ImMin(Min.y + inset_min.y, Max.y); Max.x = ImMax(Max.x - inset_max.x, Min.x); Max.y = ImMax(Max.y - inset_max.y, Min.y); } bool IsInverted() const { return Min.x > Max.x || Min.y > Max.y; } ImVec4 ToVec4() const { return ImVec4(Min.x, Min.y, Max.x, Max.y); } const ImVec4& AsVec4() const { return *(const ImVec4*)&Min.x; } @@ -872,16 +838,6 @@ struct ImGuiTextIndex void append(const char* base, int old_size, int new_size); }; -// [Internal] Types -struct ImGuiTextFilterItem -{ - const char* Begin; // Pointer within parent's buffer - int Len; // Length of text (non-zero terminated) - short CountInclude; // Number of consecutive items forming an end chain. >0 when beginning of an AND chain, =0 otherwise. - unsigned short MatchIncludesMask; // Storage for multi-sources versions of PassFilter(). Unused by core library. - ImGuiTextFilterItem(const char* b, const char* e) { IM_ASSERT(e > b); Begin = b; Len = (int)(e - b); CountInclude = 0; MatchIncludesMask = 0; } -}; - // Helper: ImGuiPackedDate (sizeof() == 2) // Store a date in a way that is efficient to read/write in text form. If we stored e.g. number of days since Epoch we'd need costlier back and forth. // This is specifically designed to be able to prune old .ini data. @@ -924,28 +880,11 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N,_MAXERROR) ((_MAXERROR) / (1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI)))) #define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N,_RAD) ((1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI))) / (_RAD)) -// ImDrawList: Lookup tables +// ImDrawList: Lookup table size for adaptive arc drawing, cover full circle. #ifndef IM_DRAWLIST_ARCFAST_TABLE_SIZE -#define IM_DRAWLIST_ARCFAST_TABLE_SIZE (48) // Number of samples in adaptive arc drawing lookup table. +#define IM_DRAWLIST_ARCFAST_TABLE_SIZE 48 // Number of samples in lookup table. #endif -#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. - -#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX -#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX (32) // The maximum line width to bake anti-aliased textures for. -#endif -#ifndef IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH -#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH (4) // Calculate detailed textures for width [1..IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH] -#endif -#ifndef IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT -#define IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT (4) // How many samples per integer thickness level. -#endif -#ifndef IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX -#define IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX (16) -#endif -#ifndef IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX -#define IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX (4) // 0: fill, 1-3: strokes thickness -#endif -#define IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT ((IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH - 1) * IM_DRAWLIST_TEX_LINES_SAMPLE_COUNT + 1) +#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle. // Data shared between all ImDrawList instances // Conceptually this could have been called e.g. ImDrawListSharedContext @@ -954,15 +893,14 @@ IMGUI_API ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStorag struct IMGUI_API ImDrawListSharedData { ImVec2 TexUvWhitePixel; // UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) - const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->Builder->TexUvLines) - const ImVec4* TexUvCorners; // UV of rounded corner (== FontAtlas->Builder->TexUvCorners) + const ImVec4* TexUvLines; // UV of anti-aliased lines in the atlas (== FontAtlas->TexUvLines) ImFontAtlas* FontAtlas; // Current font atlas ImFont* Font; // Current font (used for simplified AddText overload) - float FontSize; // Current font size (used for simplified AddText overload) + float FontSize; // Current font size (used for for simplified AddText overload) float FontScale; // Current font scale (== FontSize / Font->FontSize) float CurveTessellationMaxError; // Tessellation tolerance when using PathBezierCurveTo() float CircleTessellationMaxError; // Number of circle segments to use per pixel of radius for AddCircle() etc - ImDrawFlags InitialDrawFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) + ImDrawListFlags InitialFlags; // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) ImVec4 ClipRectFullscreen; // Value for PushClipRectFullscreen() ImVector TempBuffer; // Temporary write buffer ImVector DrawLists; // All draw lists associated to this ImDrawListSharedData @@ -973,6 +911,9 @@ struct IMGUI_API ImDrawListSharedData float ArcFastRadiusCutoff; // Cutoff radius after which arc drawing will fallback to slower PathArcTo() ImU8 CircleSegmentCounts[64]; // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) + int* ShadowRectIds; // IDs of rects for shadow texture (2 entries) + const ImVec4* ShadowRectUvs; // UV coordinates for shadow texture (10 entries) + ImDrawListSharedData(); ~ImDrawListSharedData(); void SetCircleTessellationMaxError(float max_error); @@ -2161,7 +2102,6 @@ enum ImGuiLocKey : int //ImGuiLocKey_TableResetAll, ImGuiLocKey_TableResetOrder, ImGuiLocKey_TableResetVisibility, - ImGuiLocKey_TableResetSizing, ImGuiLocKey_WindowingMainMenuBar, ImGuiLocKey_WindowingPopup, ImGuiLocKey_WindowingUntitled, @@ -2510,7 +2450,6 @@ struct ImGuiContext ImGuiID NavJustMovedToFocusScopeId; // Just navigated to this focus scope id (result of a successfully MoveRequest). ImGuiKeyChord NavJustMovedToKeyMods; bool NavJustMovedToIsTabbing; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. - bool NavJustMovedToIsInit; // Copy of ImGuiNavMoveFlags_IsTabbing. Maybe we should store whole flags. bool NavJustMovedToHasSelectionData; // Copy of move result's ItemFlags & ImGuiItemFlags_HasSelectionUserData). Maybe we should just store ImGuiNavItemData. // Navigation: extra config options (will be made public eventually) @@ -2943,7 +2882,7 @@ struct ImGuiTabItem { ImGuiID ID; ImGuiTabItemFlags Flags; - int LastFrameVisible; // TabItem visibility (not contents visibility) + int LastFrameVisible; int LastFrameSelected; // This allows us to infer an ordered list of the last activated tabs with little maintenance float Offset; // Position relative to beginning of tab bar float Width; // Width currently displayed @@ -2953,7 +2892,6 @@ struct ImGuiTabItem ImS16 BeginOrder; // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable ImS16 IndexDuringLayout; // Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. bool WantClose; // Marked as closed by SetTabItemClosed() - bool ContentsIsVisible; ImGuiTabItem() { memset((void*)this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; RequestedWidth = -1.0f; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; } }; @@ -2968,7 +2906,7 @@ struct IMGUI_API ImGuiTabBar ImGuiID SelectedTabId; // Selected tab/window ImGuiID NextSelectedTabId; // Next selected tab/window. Will also trigger a scrolling animation ImGuiID NextScrollToTabId; - ImGuiID VisibleTabContentsId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) + ImGuiID VisibleTabId; // Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) int CurrFrameVisible; int PrevFrameVisible; ImRect BarRect; @@ -2990,7 +2928,6 @@ struct IMGUI_API ImGuiTabBar ImS8 BeginCount; bool WantLayout; bool VisibleTabWasSubmitted; - bool LastTabItemContentsAppearing; bool TabsAddedNew; // Set to true when a new tab item or button has been added to the tab bar during last frame bool ScrollButtonEnabled; ImS16 TabsActiveCount; // Number of tabs submitted this frame. @@ -3163,7 +3100,6 @@ struct IMGUI_API ImGuiTable ImU32 BorderColorLight; float BorderX1; float BorderX2; - float BorderSize; float HostIndentX; float MinColumnWidth; float OuterPaddingX; @@ -3194,9 +3130,9 @@ struct IMGUI_API ImGuiTable ImDrawListSplitter* DrawSplitter; // Shortcut to TempData->DrawSplitter while in table. Isolate draw commands per columns to avoid switching clip rect constantly ImGuiTableInstanceData InstanceDataFirst; ImVector InstanceDataExtra; // FIXME-OPT: Using a small-vector pattern would be good. - ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() - ImVector SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would be good. ImGuiTableColumnSortSpecs SortSpecsSingle; + ImVector SortSpecsMulti; // FIXME-OPT: Using a small-vector pattern would be good. + ImGuiTableSortSpecs SortSpecs; // Public facing sorts specs, this is what we return in TableGetSortSpecs() ImGuiTableColumnIdx SortSpecsCount; ImGuiTableColumnIdx ColumnsEnabledCount; // Number of enabled columns (<= ColumnsCount) ImGuiTableColumnIdx ColumnsEnabledFixedCount; // Number of enabled columns using fixed width (<= ColumnsCount) @@ -3228,7 +3164,6 @@ struct IMGUI_API ImGuiTable ImS8 NavLayer; // ImGuiNavLayer at the time of BeginTable(). bool IsLayoutLocked; // Set by TableUpdateLayout() which is called when beginning the first row. bool IsInsideRow; // Set when inside TableBeginRow()/TableEndRow(). - bool IsNewTable; bool IsInitializing; bool IsReconcileMode; bool IsSortSpecsDirty; @@ -3242,7 +3177,6 @@ struct IMGUI_API ImGuiTable bool IsResetAllRequest; // Set to queue a call to TableResetSettings() in BeginTable() bool IsResetDisplayOrderRequest; bool IsResetVisibilityRequest; - bool IsResetSizesRequest; bool IsUnfrozenRows; // Set when we got past the frozen row. bool IsDefaultSizingPolicy; // Set if user didn't explicitly set a sizing policy in BeginTable() bool IsActiveIdAliveBeforeTable; @@ -3267,7 +3201,6 @@ struct IMGUI_API ImGuiTableTempData int TableIndex; // Index in g.Tables.Buf[] pool float LastTimeActive; // Last timestamp this structure was used float AngledHeadersExtraWidth; // Used in EndTable() - ImRect BorderOuterSizes; ImVector AngledHeadersRequests; // Used in TableAngledHeadersRow() // FIXME: Single instance is enough? // Topology change @@ -3286,7 +3219,6 @@ struct IMGUI_API ImGuiTableTempData ImVec1 HostBackupColumnsOffset; // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable() float HostBackupItemWidth; // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable() int HostBackupItemWidthStackSize;//Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable() - ImGuiLayoutType HostBackupLayoutType; // Backup of InnerWindow->DC.LayoutType at the end of BeginTable() ImGuiTableTempData() { memset((void*)this, 0, sizeof(*this)); LastTimeActive = -1.0f; } }; @@ -3502,7 +3434,6 @@ namespace ImGui IMGUI_API void StopMouseMovingWindow(); IMGUI_API void UpdateMouseMovingWindowNewFrame(); IMGUI_API void UpdateMouseMovingWindowEndFrame(); - IMGUI_API ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1); // Viewports inline ImGuiViewport* GetWindowViewport() { return GetMainViewport(); } // For code consistency. This is public API in docking branch. @@ -3790,7 +3721,6 @@ namespace ImGui IMGUI_API void TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, ImVec2 mouse_pos); IMGUI_API bool TabBarProcessReorder(ImGuiTabBar* tab_bar); IMGUI_API bool TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window); - IMGUI_API bool TabItemIsContentsAppearing(); IMGUI_API void TabItemSpacing(const char* str_id, ImGuiTabItemFlags flags, float width); IMGUI_API ImVec2 TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker); IMGUI_API ImVec2 TabItemCalcSize(ImGuiWindow* window); @@ -3818,9 +3748,9 @@ namespace ImGui // Render helpers (those functions don't access any ImGui state!) IMGUI_API void RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f); - IMGUI_API void RenderArrowEx(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float cos_a, float sin_a, float scale, ImVec2 arrow_sizes, float arrow_th); IMGUI_API void RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col); IMGUI_API void RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz); + IMGUI_API void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col); IMGUI_API void RenderRectFilledInRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float fill_x0, float fill_x1, float rounding); IMGUI_API void RenderRectFilledWithHole(ImDrawList* draw_list, const ImRect& outer, const ImRect& inner, ImU32 col, float rounding); IMGUI_API ImDrawFlags CalcRoundingFlagsForRectInRect(const ImRect& r_in, const ImRect& r_outer, float threshold); @@ -3993,11 +3923,10 @@ struct ImFontLoader void (*LoaderShutdown)(ImFontAtlas* atlas); bool (*FontSrcInit)(ImFontAtlas* atlas, ImFontConfig* src); void (*FontSrcDestroy)(ImFontAtlas* atlas, ImFontConfig* src); - int (*FontSrcGetGlyphIndexFromCodepoint)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); // Required - bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, int glyph_index); + bool (*FontSrcContainsGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint); bool (*FontBakedInit)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); void (*FontBakedDestroy)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src); - bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, int glyph_index, ImFontGlyph* out_glyph, float* out_advance_x); // Required + bool (*FontBakedLoadGlyph)(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x); // Size of backend data, Per Baked * Per Source. Buffers are managed by core to avoid excessive allocations. // FIXME: At this point the two other types of buffers may be managed by core to be consistent? @@ -4089,8 +4018,7 @@ struct ImFontAtlasBuilder ImVec2i MaxRectSize; // Largest rectangle to pack (de-facto used as a "minimum texture size") ImVec2i MaxRectBounds; // Bottom-right most used pixels bool LockDisableResize; // Disable resizing texture - bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. - ImS8 LoadedFontDefaultAsVector; // -1, or record with 0/1 whereas AddFontDefault() picked bitmap or vector font. + bool PreloadedAllGlyphsRanges; // Set when missing ImGuiBackendFlags_RendererHasTextures features forces atlas to preload everything. // Cache of all ImFontBaked ImStableVector BakedPool; @@ -4100,14 +4028,8 @@ struct ImFontAtlasBuilder // Custom rectangle identifiers ImFontAtlasRectId PackIdMouseCursors; // White pixel + mouse cursors. Also happen to be fallback in case of packing failure. ImFontAtlasRectId PackIdLinesTexData; - ImFontAtlasRectId PackIdLineFractTexData; - ImFontAtlasRectId PackIdCornersTexData; - // Cached UV coordinates - ImVec4 TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1 + IM_DRAWLIST_TEX_LINES_DETAILED_WIDTH_COUNT]; // UVs for baked anti-aliased lines (u0, u1, v, 1/thickness) - ImVec4 TexUvCorners[IM_DRAWLIST_TEX_CORNERS_ROUNDING_MAX * IM_DRAWLIST_TEX_CORNERS_THICKNESS_MAX]; // UVs for baked anti-aliased corners (0= fill, 1> stroke thickness) - - ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; LoadedFontDefaultAsVector = -1; PackIdMouseCursors = PackIdLinesTexData = PackIdLineFractTexData = PackIdCornersTexData = -1; } + ImFontAtlasBuilder() { memset((void*)this, 0, sizeof(*this)); FrameCount = -1; RectsIndexFreeListStart = -1; PackIdMouseCursors = PackIdLinesTexData = -1; } }; IMGUI_API void ImFontAtlasBuildInit(ImFontAtlas* atlas); @@ -4149,8 +4071,6 @@ IMGUI_API void ImFontAtlasBakedAddFontGlyphAdvancedX(ImFontAtlas* a IMGUI_API void ImFontAtlasBakedDiscardFontGlyph(ImFontAtlas* atlas, ImFont* font, ImFontBaked* baked, ImFontGlyph* glyph); IMGUI_API void ImFontAtlasBakedSetFontGlyphBitmap(ImFontAtlas* atlas, ImFontBaked* baked, ImFontConfig* src, ImFontGlyph* glyph, ImTextureRect* r, const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch); -IMGUI_API float ImFontBaked_BuildLoadGlyphAdvanceX(ImFontBaked* baked, ImWchar codepoint); - IMGUI_API void ImFontAtlasPackInit(ImFontAtlas* atlas); IMGUI_API ImFontAtlasRectId ImFontAtlasPackAddRect(ImFontAtlas* atlas, int w, int h, ImFontAtlasRectEntry* overwrite_entry = NULL); IMGUI_API ImTextureRect* ImFontAtlasPackGetRect(ImFontAtlas* atlas, ImFontAtlasRectId id); @@ -4162,7 +4082,6 @@ IMGUI_API void ImFontAtlasAddDrawListSharedData(ImFontAtlas* atlas, IMGUI_API void ImFontAtlasRemoveDrawListSharedData(ImFontAtlas* atlas, ImDrawListSharedData* data); IMGUI_API void ImFontAtlasUpdateDrawListsTextures(ImFontAtlas* atlas, ImTextureRef old_tex, ImTextureRef new_tex); IMGUI_API void ImFontAtlasUpdateDrawListsSharedData(ImFontAtlas* atlas); -IMGUI_API bool ImFontAtlasHeuristicShouldUseDefaultVectorFont(ImFontAtlas* atlas); IMGUI_API void ImFontAtlasTextureBlockConvert(const unsigned char* src_pixels, ImTextureFormat src_fmt, int src_pitch, unsigned char* dst_pixels, ImTextureFormat dst_fmt, int dst_pitch, int w, int h); IMGUI_API void ImFontAtlasTextureBlockPostProcess(ImFontAtlasPostProcessData* data); diff --git a/imgui_tables.cpp b/imgui_tables.cpp index 820b4dde4..fb1b998d0 100644 --- a/imgui_tables.cpp +++ b/imgui_tables.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.1 WIP +// dear imgui, v1.93.0 WIP // (tables and columns code) /* @@ -375,6 +375,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG const int previous_frame_active = table->LastFrameActive; const int instance_no = (previous_frame_active != g.FrameCount) ? 0 : table->InstanceCurrent + 1; const ImGuiTableFlags previous_flags = table->Flags; + const bool is_new_table = (previous_frame_active == -1); table->ID = id; table->Flags = flags; table->LastFrameActive = g.FrameCount; @@ -383,7 +384,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->IsLayoutLocked = false; table->InnerWidth = inner_width; table->NavLayer = (ImS8)outer_window->DC.NavLayerCurrent; - table->IsNewTable = (previous_frame_active == -1); temp_data->UserOuterSize = outer_size; // Instance data (for instance 0, TableID == TableInstanceID) @@ -476,28 +476,31 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos; temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth; temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size; - temp_data->HostBackupLayoutType = inner_window->DC.LayoutType; inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); - inner_window->DC.LayoutType = ImGuiLayoutType_Vertical; - // Border size - // FIXME-WIP: Changing this is not currently simple due to ClipRect requirements. Easier to manage with new 1.93 primitives though. - const float border_size = table->BorderSize = TABLE_BORDER_SIZE; - // Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752) - // - We normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the - // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap - // problem only affect scrolling tables in this case we can get away with doing it without extra cost). - // - (FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, - // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with - // different x/y values to BeginChild().) - // - For non-scrolling window, this is applied to table->InnerClipRect below. - temp_data->BorderOuterSizes.Min.x = (flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; - temp_data->BorderOuterSizes.Min.y = (flags & ImGuiTableFlags_BordersOuterH) ? border_size : 0.0f; - temp_data->BorderOuterSizes.Max.x = ((flags & ImGuiTableFlags_BordersOuterV) && ((inner_window == outer_window) || inner_window->DecoOuterSizeX2 == 0.0f)) ? border_size : 0.0f; - temp_data->BorderOuterSizes.Max.y = ((flags & ImGuiTableFlags_BordersOuterH) && ((inner_window == outer_window) || inner_window->DecoOuterSizeY2 == 0.0f)) ? border_size : 0.0f; + // (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the + // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap + // problem only affect scrolling tables in this case we can get away with doing it without extra cost). if (inner_window != outer_window) - table->HostClipRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); + { + // FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize, + // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with + // different x/y values to BeginChild(). + const float border_size = TABLE_BORDER_SIZE; + if (flags & ImGuiTableFlags_BordersOuterV) + { + table->HostClipRect.Min.x = ImMin(table->HostClipRect.Min.x + border_size, table->HostClipRect.Max.x); + if (inner_window->DecoOuterSizeX2 == 0.0f) + table->HostClipRect.Max.x = ImMax(table->HostClipRect.Max.x - border_size, table->HostClipRect.Min.x); + } + if (flags & ImGuiTableFlags_BordersOuterH) + { + table->HostClipRect.Min.y = ImMin(table->HostClipRect.Min.y + border_size, table->HostClipRect.Max.y); + if (inner_window->DecoOuterSizeY2 == 0.0f) + table->HostClipRect.Max.y = ImMax(table->HostClipRect.Max.y - border_size, table->HostClipRect.Min.y); + } + } // Padding and Spacing // - None ........Content..... Pad .....Content........ @@ -506,22 +509,29 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG // - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad | const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0; const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true; - const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? border_size : 0.0f; + const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f; const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f; const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f; table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border; table->CellSpacingX2 = inner_spacing_explicit; table->CellPaddingX = inner_padding_explicit; - const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? border_size : 0.0f; + const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f; table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX; + table->CurrentColumn = -1; + table->CurrentRow = -1; + table->RowBgColorCounter = 0; + table->LastRowFlags = ImGuiTableRowFlags_None; + table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; + table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width + table->InnerClipRect.ClipWithFull(table->HostClipRect); + table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : table->HostClipRect.Max.y; + table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow() table->RowCellPaddingY = 0.0f; - table->RowBgColorCounter = 0; - table->LastRowFlags = ImGuiTableRowFlags_None; table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any table->FreezeColumnsRequest = table->FreezeColumnsCount = 0; table->IsUnfrozenRows = true; @@ -531,15 +541,6 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG table->AngledHeadersHeight = 0.0f; temp_data->AngledHeadersExtraWidth = 0.0f; - table->CurrentColumn = -1; - table->CurrentRow = -1; - table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect; - if (inner_window == outer_window) - table->InnerClipRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); - table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width - table->InnerClipRect.ClipWithFull(table->HostClipRect); - if ((flags & ImGuiTableFlags_NoHostExtendY) == 0) - table->InnerClipRect.Max.y = table->HostClipRect.Max.y; // Using opaque colors facilitate overlapping lines of the grid, otherwise we'd need to improve TableDrawBorders() table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong); table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight); @@ -584,7 +585,7 @@ bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImG if (table->IsInitializing) { // Initialize - if (table->IsNewTable) + if (is_new_table) { table->SettingsOffset = -1; table->IsSettingsRequestLoad = true; @@ -707,10 +708,10 @@ void ImGui::TableApplyQueuedRequests(ImGuiTable* table) // table->ReorderColumn = -1; } - // Handle reset requests (display order / visibility / sizes) + // Handle display order / visibility reset requests if (table->IsResetDisplayOrderRequest) { - for (int n = 0; n < table->ColumnsCount; n++) // Variant of using TableInitColumnDefaults()( + for (int n = 0; n < table->ColumnsCount; n++) table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n; table->IsResetDisplayOrderRequest = false; table->IsSettingsDirty = true; @@ -718,17 +719,10 @@ void ImGui::TableApplyQueuedRequests(ImGuiTable* table) if (table->IsResetVisibilityRequest) { for (ImGuiTableColumn& column : table->Columns) - TableInitColumnDefaults(table, &column, ImGuiTableFlags_Hideable); + column.IsUserEnabled = column.IsUserEnabledNextFrame = (column.Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1; table->IsResetVisibilityRequest = false; table->IsSettingsDirty = true; } - if (table->IsResetSizesRequest) - { - for (ImGuiTableColumn& column : table->Columns) - TableInitColumnDefaults(table, &column, ImGuiTableFlags_Resizable); - table->IsResetSizesRequest = false; - table->IsSettingsDirty = true; - } } // Apply immediately. See TableQueueSetColumnDisplayOrder() for additional checks/constraints. @@ -1283,7 +1277,7 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) } if (order_n < table->FreezeColumnsCount) - host_clip_rect.Min.x = ImClamp(column->MaxX + table->BorderSize, host_clip_rect.Min.x, host_clip_rect.Max.x); + host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x); offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f; } @@ -1315,12 +1309,10 @@ void ImGui::TableUpdateLayout(ImGuiTable* table) table->Flags &= ~ImGuiTableFlags_NoHostExtendX; if (table->Flags & ImGuiTableFlags_NoHostExtendX) { - const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; - table->OuterRect.Max.x = table->WorkRect.Max.x = ImMin(table->OuterRect.Max.x, unused_x1 + border_size_outer_w); - table->InnerClipRect.Max.x = ImClamp(table->OuterRect.Max.x - border_size_outer_w, table->InnerClipRect.Min.x, table->InnerClipRect.Max.x); + table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1; + table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1); } - table->InnerWindow->ParentWorkRect = table->WorkRect; // Used by Selectable/TreeNode highlight - table->InnerWindow->ParentWorkRect.ShrinkClamp(temp_data->BorderOuterSizes.Min, temp_data->BorderOuterSizes.Max); + table->InnerWindow->ParentWorkRect = table->WorkRect; table->BorderX1 = table->InnerClipRect.Min.x; table->BorderX2 = table->InnerClipRect.Max.x; @@ -1495,7 +1487,6 @@ void ImGui::EndTable() // Finalize table height ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize; - inner_window->DC.LayoutType = temp_data->HostBackupLayoutType; inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize; inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos; const float inner_content_max_y = ImCeil(table->RowPosY2); // Rounding final position is important as we currently don't round row height ('Demo->Tables->Outer Size' demo uses non-integer heights) @@ -1512,10 +1503,10 @@ void ImGui::EndTable() // but since the later is likely to be impossible to do we'd rather update both axes together. if (table->Flags & ImGuiTableFlags_ScrollX) { - const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; + const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f; float max_pos_x = inner_window->DC.CursorMaxPos.x; if (table->RightMostEnabledColumn != -1) - max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - border_size_outer_w); + max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border); if (table->ResizedColumn != -1) max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2); inner_window->DC.CursorMaxPos.x = max_pos_x + table->TempData->AngledHeadersExtraWidth; @@ -1695,7 +1686,7 @@ void ImGui::TableInitColumnDefaults(ImGuiTable* table, ImGuiTableColumn* column, if (init_mask & ImGuiTableFlags_Resizable) { float init_width_or_weight = column->InitStretchWeightOrWidth; - column->WidthRequest = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthFixed)) ? init_width_or_weight : -1.0f; + column->WidthRequest = ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f; column->StretchWeight = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthStretch)) ? init_width_or_weight : -1.0f; if (init_width_or_weight > 0.0f) // Disable auto-fit if an explicit width/weight has been specified column->AutoFitQueue = 0x00; @@ -1765,7 +1756,7 @@ void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, flo ImGuiTableColumn* column = &table->Columns[column_idx]; // If topology change goes into reconcile mode - if (table->IsReconcileMode == false && column->ID != column_id && !table->IsNewTable) + if (table->IsReconcileMode == false && column->ID != column_id) { table->IsReconcileMode = true; table->TempData->ReconcileColumnsRequests.reserve(table->ColumnsCount - column_idx); @@ -2177,6 +2168,7 @@ void ImGui::TableEndRow(ImGuiTable* table) // Decide of top border color ImU32 top_border_col = 0; + const float border_size = TABLE_BORDER_SIZE; if (table->CurrentRow > 0 && (table->Flags & ImGuiTableFlags_BordersInnerH)) top_border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight; @@ -2223,11 +2215,11 @@ void ImGui::TableEndRow(ImGuiTable* table) // Draw top border if (top_border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y) - window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, table->BorderSize, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, border_size); // Draw bottom border at the row unfreezing mark (always strong) if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y) - window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, table->BorderSize, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, border_size); } // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) @@ -2425,7 +2417,7 @@ void ImGui::TableEndCell(ImGuiTable* table) //------------------------------------------------------------------------- // [SECTION] Tables: Columns width management //------------------------------------------------------------------------- -// - TableCalcMaxColumnWidth() [Internal] +// - TableGetMaxColumnWidth() [Internal] // - TableGetColumnWidthAuto() [Internal] // - TableSetColumnWidth() // - TableSetColumnWidthAutoSingle() [Internal] @@ -2578,7 +2570,6 @@ void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n) table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n; } -// FIXME: AutoFitQueue for Stretch columns can do a "reset" if InitStretchWeightOrWidth is valid, therefore might be misnamed. void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table) { for (int column_n = 0; column_n < table->ColumnsCount; column_n++) @@ -2743,10 +2734,6 @@ void ImGui::TableSetupDrawChannels(ImGuiTable* table) table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect; table->Bg2ClipRectForDrawCmd = table->HostClipRect; IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y); - if (table->Flags & ImGuiTableFlags_NoHostExtendX) - table->Bg2ClipRectForDrawCmd.Max.x = ImMin(table->Bg2ClipRectForDrawCmd.Max.x, table->BgClipRect.Max.x); // Don't apply to Bg0: shapes in Bg0 are already CPU clipped and it makes merging fails. - if (table->Flags & ImGuiTableFlags_NoHostExtendY) - table->Bg2ClipRectForDrawCmd.Max.y = ImMin(table->Bg2ClipRectForDrawCmd.Max.y, table->BgClipRect.Max.y); // " } // This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). @@ -2904,7 +2891,7 @@ void ImGui::TableMergeDrawChannels(ImGuiTable* table) merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x); if ((merge_group_n & 2) == 0 || !has_freeze_v) merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y); - if ((merge_group_n & 1) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendX) == 0) + if ((merge_group_n & 1) != 0) merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x); if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0) merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y); @@ -2964,52 +2951,19 @@ static ImU32 TableGetColumnBorderCol(ImGuiTable* table, int order_n, int column_ void ImGui::TableDrawBorders(ImGuiTable* table) { ImGuiWindow* inner_window = table->InnerWindow; - if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect)) // Note how OuterWindow->ClipRect == table->Bg0ClipRectForDrawCmd + if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect)) return; ImDrawList* inner_drawlist = inner_window->DrawList; table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0); - inner_drawlist->PushClipRect(table->OuterWindow->ClipRect.Min, table->OuterWindow->ClipRect.Max, false); - - // For e.g. non scrolling table we limit vertex coordinates in order to keep ImDrawCmd AABB roughly within visible range. - const float border_size_outer_w = (table->Flags & ImGuiTableFlags_BordersOuterV) ? table->BorderSize : 0.0f; - const float border_size_outer_h = (table->Flags & ImGuiTableFlags_BordersOuterH) ? table->BorderSize : 0.0f; - const float border_size_inner = table->BorderSize; - const float draw_y2_limit = table->OuterWindow->ClipRect.Max.y + (2.0f * ImMax(border_size_outer_h, inner_drawlist->_FringeScale)); - - // Draw outer border - if (table->Flags & ImGuiTableFlags_BordersOuter) - { - // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call - // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their - // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part - // of it in inner window, and the part that's over scrollbars in the outer window..) - // Either solution currently won't allow us to use a larger border size: the border would clipped. - ImRect outer_border = table->OuterRect; - outer_border.Max.y = ImMin(outer_border.Max.y, draw_y2_limit); // Clamp but keep bottom border non-visible. - const ImU32 outer_col = table->BorderColorStrong; - if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) - { - inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size_outer_w); - } - else if (table->Flags & ImGuiTableFlags_BordersOuterV) - { - inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); - inner_drawlist->AddLineV(outer_border.Max.x - border_size_outer_w, outer_border.Min.y, outer_border.Max.y, outer_col, border_size_outer_w); - } - else if (table->Flags & ImGuiTableFlags_BordersOuterH) - { - inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size_outer_h); - inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y - border_size_outer_h, outer_col, border_size_outer_h); - } - } + inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false); // Draw inner border and resizing feedback ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); - const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? border_size_outer_h : 0.0f); - const float draw_y2_body = ImMin(table->InnerRect.Max.y - border_size_outer_h, draw_y2_limit); - const float draw_y2_head = table->IsUsingHeaders ? ImMin(draw_y2_body, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; - + const float border_size = TABLE_BORDER_SIZE; + const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? 1.0f : 0.0f); + const float draw_y2_body = table->InnerRect.Max.y; + const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1; if (table->Flags & ImGuiTableFlags_BordersInnerV) { for (int order_n = 0; order_n < table->ColumnsCount; order_n++) @@ -3023,21 +2977,14 @@ void ImGui::TableDrawBorders(ImGuiTable* table) const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent); const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0; const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1); - - // FIXME-TABLE: 1-off display hack for right-most column when resizable (!Scroll && Resizable && (NoHostExtendX || RightMostIsFixed)). - // Fixing actual width would involve altering width_avail in layout and TableCalcMaxColumnWidth(), which would drop the property - // ColumnsGivenWidth == Outer Allocated Width. Worth reworking, but would only make sense if we accept that BorderSize affects layout. - float draw_x2 = column->MaxX; - if (draw_x2 >= table->InnerClipRect.Max.x && draw_x2 - 1.0f <= table->InnerClipRect.Max.x) - draw_x2 = table->InnerClipRect.Max.x; - if (draw_x2 >= table->InnerClipRect.Max.x && !is_resized && !is_hovered) + if (column->MaxX > table->InnerClipRect.Max.x && !is_resized) continue; // Decide whether right-most column is visible if (column->NextEnabledColumn == -1 && !is_resizable) if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX)) continue; - if (draw_x2 <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. + if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size.. continue; // Draw in outer window so right-most column won't be clipped @@ -3049,16 +2996,42 @@ void ImGui::TableDrawBorders(ImGuiTable* table) else if ((table->Flags & (ImGuiTableFlags_NoBordersInBodyUntilResize | ImGuiTableFlags_NoBordersInBody)) == 0) draw_y2 = draw_y2_body; if (draw_y2 > draw_y1) - inner_drawlist->AddLineV(draw_x2, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size_inner); + inner_drawlist->AddLineV(column->MaxX, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size); } } + // Draw outer border + // FIXME: could use AddRect or explicit VLine/HLine helper? + if (table->Flags & ImGuiTableFlags_BordersOuter) + { + // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + // of it in inner window, and the part that's over scrollbars in the outer window..) + // Either solution currently won't allow us to use a larger border size: the border would clipped. + const ImRect outer_border = table->OuterRect; + const ImU32 outer_col = table->BorderColorStrong; + if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter) + { + inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterV) + { + inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); + inner_drawlist->AddLineV(outer_border.Max.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size); + } + else if (table->Flags & ImGuiTableFlags_BordersOuterH) + { + inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size); + inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y - border_size, outer_col, border_size); + } + } if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y) { - // Draw bottom-most row border between it and above outer border. + // Draw bottom-most row border between it is above outer border. const float border_y = table->RowPosY2; if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y) - inner_drawlist->AddLineH(table->BorderX1, table->BorderX2, border_y, table->BorderColorLight, border_size_inner); + inner_drawlist->AddLineH(table->BorderX1, table->BorderX2, border_y, table->BorderColorLight, border_size); } inner_drawlist->PopClipRect(); @@ -3461,7 +3434,7 @@ void ImGui::TableHeader(const char* label) PopStyleColor(); x += w_sort_text; } - RenderArrow(window->DrawList, ImVec2(x + (g.FontSize * (1.0f - ARROW_SCALE) * 0.5f) , y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); + RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE); } // Handle clicking on column header to adjust Sort Order @@ -3651,9 +3624,7 @@ void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label if (pass == 1) { // Draw border - draw_list->AddLine( - bg_shape[0] + ImVec2(table->BorderSize * 0.5f, 0.0f), - bg_shape[3] + ImVec2(table->BorderSize * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), table->BorderSize); + draw_list->AddLine(bg_shape[0] - ImVec2(TABLE_BORDER_SIZE * 0.5f, 0.0f), bg_shape[3] - ImVec2(TABLE_BORDER_SIZE * 0.5f, 0.0f), TableGetColumnBorderCol(table, order_n, column_n), TABLE_BORDER_SIZE); } } PopClipRect(); @@ -3770,7 +3741,7 @@ void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags } // Reset Order/Visibility etc. - if (flags_for_section_to_display & (ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Resizable)) + if (flags_for_section_to_display & (ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable)) if (BeginMenu(LocalizeGetMsg(ImGuiLocKey_TableReset))) { //if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetAll))) // FIXME: Hiding because altering Sort Order + requesting auto-fit simultaneously has a tendency to exhibit a sizing glitch. @@ -3781,9 +3752,6 @@ void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags if (flags_for_section_to_display & ImGuiTableFlags_Hideable) if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetVisibility), NULL, false, !table->IsDefaultVisibility)) table->IsResetVisibilityRequest = true; - if (flags_for_section_to_display & ImGuiTableFlags_Resizable) - if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetSizing), NULL, false)) // Can't easily implement IsDefaultSize - table->IsResetSizesRequest = true; EndMenu(); } @@ -4002,10 +3970,12 @@ void ImGui::TableSaveSettings(ImGuiTable* table) if (column->DisplayOrder != n) settings->SaveFlags |= ImGuiTableFlags_Reorderable; if (column->SortOrder != -1) - settings->SaveFlags |= ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable; // Because SortOrder saving itself is gated, make sure every column is saved (#9519) + settings->SaveFlags |= ImGuiTableFlags_Sortable; if (column->IsUserEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0)) settings->SaveFlags |= ImGuiTableFlags_Hideable; } + if (table->Flags & ImGuiTableFlags_Sortable) + settings->SaveFlags |= ImGuiTableFlags_Sortable | ImGuiTableFlags_Reorderable; settings->SaveFlags &= table->Flags; settings->RefScale = save_ref_scale ? table->RefScale : 0.0f; @@ -4139,12 +4109,6 @@ static int IMGUI_CDECL TableFixDisplayOrderComparer(const void* lhs, const void* // Fix invalid display order data: compact values (0,1,3 -> 0,1,2); preserve relative order (0,3,1 -> 0,2,1); deduplicate (0,4,1,1 -> 0,3,1,2) void ImGui::TableFixDisplayOrder(ImGuiTable* table) { - if ((table->Flags & ImGuiTableFlags_Reorderable) == 0) - { - for (int n = 0; n < table->ColumnsCount; n++) - table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n; - return; - } ImGuiContext& g = *GImGui; g.TempBuffer.reserve((int)(sizeof(ImGuiTableFixDisplayOrderColumnData) * table->ColumnsCount)); // FIXME: Maybe wrap those two lines as a helper. ImGuiTableFixDisplayOrderColumnData* fdo_columns = (ImGuiTableFixDisplayOrderColumnData*)(void*)g.TempBuffer.Data; diff --git a/imgui_widgets.cpp b/imgui_widgets.cpp index f54a91160..2403fdd5c 100644 --- a/imgui_widgets.cpp +++ b/imgui_widgets.cpp @@ -1,4 +1,4 @@ -// dear imgui, v1.93.1 WIP +// dear imgui, v1.93.0 WIP // (widgets code) /* @@ -54,7 +54,6 @@ Index of this file: // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant -#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types @@ -74,7 +73,6 @@ Index of this file: #pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int' #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness -#pragma clang diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. @@ -86,7 +84,6 @@ Index of this file: #pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind -#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*' #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked @@ -935,7 +932,7 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos) window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col); RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact); const ImU32 cross_col = GetColorU32(ImGuiCol_Text); - const ImVec2 cross_center = bb.GetCenter(); + const ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f); const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; const float cross_thickness = 1.0f * (float)(int)g.Style._MainScale; // FIXME-DPI window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, cross_thickness); @@ -1302,9 +1299,8 @@ bool ImGui::Checkbox(const char* label, bool* v) { // Undocumented tristate/mixed/indeterminate checkbox (#2644) // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox) - const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)); - const float rounding = 0.0f;// IM_TRUNC(ImMin((square_sz - pad * 2.0f) * 0.20f, style.FrameRounding)); // Clamp rounding - window->DrawList->AddRectFilled(check_bb.Min + ImVec2(pad, pad), check_bb.Max - ImVec2(pad, pad), check_col, rounding); + ImVec2 pad(ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)), ImMax(1.0f, IM_TRUNC(square_sz / 3.6f))); + window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); } else if (*v) { @@ -1564,9 +1560,8 @@ bool ImGui::TextLink(const char* label) ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z); } - // FIXME-TEXT FIXME-DPI: Underline mode. Note how stb_truetype now expose stbtt_GetFontUnderlineMetrics(). float line_y = bb.Max.y + ImFloor(g.FontBaked->Descent * g.FontBakedScale * 0.20f); - window->DrawList->AddLineH(bb.Min.x, bb.Max.x, line_y, GetColorU32(line_colf), 1.0f * (float)(int)g.Style._MainScale); + window->DrawList->AddLineH(bb.Min.x, bb.Max.x, line_y, GetColorU32(line_colf), 1.0f * (float)(int)g.Style._MainScale); // FIXME-TEXT: Underline mode // FIXME-DPI PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf)); RenderText(bb.Min, label, label_end, false); @@ -1762,7 +1757,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end const float sep1_x1 = pos.x; const float sep2_x2 = bb.Max.x; - float seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f) + 1.0f; + const float seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.999f); const float label_avail_w = ImMax(0.0f, sep2_x2 - sep1_x1 - padding.x * 2.0f); const ImVec2 label_pos(pos.x + padding.x + ImMax(0.0f, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y); // FIXME-ALIGN @@ -1776,9 +1771,9 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end const float sep1_x2 = label_pos.x - style.ItemSpacing.x; const float sep2_x1 = label_pos.x + label_size.x + extra_w + style.ItemSpacing.x; if (sep1_x2 > sep1_x1 && separator_thickness > 0.0f) - window->DrawList->AddLineH(sep1_x1, sep1_x2, seps_y, separator_col, separator_thickness, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(sep1_x1, sep1_x2, seps_y, separator_col, separator_thickness); if (sep2_x2 > sep2_x1 && separator_thickness > 0.0f) - window->DrawList->AddLineH(sep2_x1, sep2_x2, seps_y, separator_col, separator_thickness, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(sep2_x1, sep2_x2, seps_y, separator_col, separator_thickness); if (g.LogEnabled) LogSetNextTextDecoration("---", NULL); RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, label, label_end, &label_size); @@ -1788,7 +1783,7 @@ void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end if (g.LogEnabled) LogText("---"); if (separator_thickness > 0.0f) - window->DrawList->AddLineH(sep1_x1, sep2_x2, seps_y, separator_col, separator_thickness, ImDrawFlags_StrokeCenterBiased); + window->DrawList->AddLineH(sep1_x1, sep2_x2, seps_y, separator_col, separator_thickness); } } @@ -1985,12 +1980,12 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size); RenderNavCursor(bb, id); if (!(flags & ImGuiComboFlags_NoPreview)) - window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundAll : ImDrawFlags_RoundLeft); + window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft); if (!(flags & ImGuiComboFlags_NoArrowButton)) { ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button); ImU32 text_col = GetColorU32(ImGuiCol_Text); - window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundAll : ImDrawFlags_RoundRight); + window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersRight); if (value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x) RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f); } @@ -2655,12 +2650,10 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const if (is_wrapped) { // Wrap values - const TYPE range = v_max - v_min + (is_floating_point ? 0 : 1); - TYPE offset = ImMod((TYPE)(v_cur - v_min), range); - if (offset < 0) - offset += range; - v_cur = (TYPE)(v_min + offset); - IM_ASSERT_PARANOID(v_cur >= v_min && v_cur <= v_max); + if (v_cur < v_min) + v_cur += v_max - v_min + (is_floating_point ? 0 : 1); + if (v_cur > v_max) + v_cur -= v_max - v_min + (is_floating_point ? 0 : 1); } else { @@ -2707,7 +2700,7 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v { // Canceling action reverts to initial value size_t data_size = DataTypeGetInfo(data_type)->Size; - bool value_changed = memcmp(p_v, &g.ActiveIdValueOnActivation, data_size) != 0; + bool value_changed = memcmp(p_v, &g.ActiveIdValueOnActivation, data_size); memcpy(p_v, &g.ActiveIdValueOnActivation, data_size); ClearActiveID(); return value_changed; @@ -3329,7 +3322,7 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type { // Canceling action reverts to initial value size_t data_size = DataTypeGetInfo(data_type)->Size; - bool value_changed = memcmp(p_v, &g.ActiveIdValueOnActivation, data_size) != 0; + bool value_changed = memcmp(p_v, &g.ActiveIdValueOnActivation, data_size); memcpy(p_v, &g.ActiveIdValueOnActivation, data_size); ClearActiveID(); return value_changed; @@ -4239,7 +4232,7 @@ static int STB_TEXTEDIT_MOVELINESTART_IMPL(ImGuiInputTextState* obj, ImStb::STB_ const char* p_eol = ImFontCalcWordWrapPositionEx(g.Font, g.FontSize, p, text_end, obj->WrapWidth, ImDrawTextFlags_WrapKeepBlanks); if (p == p_cursor) // If we are already on a visible beginning-of-line, return real beginning-of-line (would be same as regular handler below) return (int)(p_bol - obj->TextSrc); - if (p_eol == p_cursor && obj->TextSrc[cursor] != '\n' && obj->LastMoveDirectionLR == ImGuiDir_Left) + if (p_eol == p_cursor && obj->TextA[cursor] != '\n' && obj->LastMoveDirectionLR == ImGuiDir_Left) return (int)(p_bol - obj->TextSrc); if (p_eol >= p_cursor) return (int)(p - obj->TextSrc); @@ -4355,7 +4348,6 @@ static int STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const cha #define IMSTB_TEXTEDIT_IMPLEMENTATION #define IMSTB_TEXTEDIT_memmove memmove - #include "imstb_textedit.h" // stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling @@ -4479,7 +4471,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons if (new_text_len + BufTextLen + 1 > obj->TextA.Size && is_resizable && !is_readonly) { IM_ASSERT(Buf == obj->TextA.Data); - int new_buf_size = BufTextLen + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1; + int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; obj->TextA.resize(new_buf_size + 1); obj->TextSrc = obj->TextA.Data; Buf = obj->TextA.Data; @@ -4803,7 +4795,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ IM_ASSERT(buf != NULL && buf_size >= 0); IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) - IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not work with left-trimming + IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline does not not work with left-trimming IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Password) == 0); // WordWrap does not work with Password mode. IM_ASSERT((flags & ImGuiInputTextFlags_WordWrap) == 0 || (flags & ImGuiInputTextFlags_Multiline) != 0); // WordWrap does not work in single-line mode. @@ -5065,7 +5057,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // Select the buffer to render. const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state; - bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextSrc : buf)[0] == 0) && !is_mixed; + bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0) && !is_mixed; // Password pushes a temporary font with only a fallback glyph if (is_password && !is_displaying_hint) @@ -5291,7 +5283,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ { if (flags & ImGuiInputTextFlags_EscapeClearsAll) { - if (state->TextSrc[0] != 0) + if (state->TextA.Data[0] != 0) { revert_edit = true; } @@ -5384,14 +5376,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (flags & ImGuiInputTextFlags_EscapeClearsAll) { // Clear input - IM_ASSERT(state->TextSrc[0] != 0); + IM_ASSERT(state->TextA.Data[0] != 0); apply_new_text = ""; apply_new_text_length = 0; value_changed = true; char empty_string = 0; stb_textedit_replace(state, state->Stb, &empty_string, 0); } - else if (strcmp(state->TextSrc, state->TextToRevertTo.Data) != 0) + else if (strcmp(state->TextA.Data, state->TextToRevertTo.Data) != 0) { apply_new_text = state->TextToRevertTo.Data; apply_new_text_length = state->TextToRevertTo.Size - 1; @@ -5767,9 +5759,9 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ state->CursorAnim += io.DeltaTime; bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f; ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll); - ImRect cursor_screen_rect = ImRect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 1.0f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.0f); + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) - draw_window->DrawList->AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, GetColorU32(ImGuiCol_InputTextCursor), style.InputTextCursorSize, ImDrawFlags_StrokeInside); + draw_window->DrawList->AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, GetColorU32(ImGuiCol_InputTextCursor), style.InputTextCursorSize); // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) // This is required for some backends (SDL3) to start emitting character/text inputs. @@ -6184,23 +6176,14 @@ bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags fl return true; } -// Helper for RenderArrowsForVerticalBar(). 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. -static void RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 p, ImVec2 half_sz, ImGuiDir direction, ImU32 col) -{ - if (direction == ImGuiDir_Left) { draw_list->AddTriangleFilled(ImVec2(p.x + half_sz.x, p.y - half_sz.y), ImVec2(p.x + half_sz.x, p.y + half_sz.y), p, col); } - if (direction == ImGuiDir_Right) { draw_list->AddTriangleFilled(ImVec2(p.x - half_sz.x, p.y + half_sz.y), ImVec2(p.x - half_sz.x, p.y - half_sz.y), p, col); } - //if (direction == ImGuiDir_Up) { draw_list->AddTriangleFilled(ImVec2(p.x + half_sz.x, p.y + half_sz.y), ImVec2(p.x - half_sz.x, p.y + half_sz.y), p, col); } - //if (direction == ImGuiDir_Down){ draw_list->AddTriangleFilled(ImVec2(p.x - half_sz.x, p.y - half_sz.y), ImVec2(p.x + half_sz.x, p.y - half_sz.y), p, col); } -} - // Helper for ColorPicker4() -static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 p, ImVec2 half_sz, float bar_w, float alpha) +static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha) { ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha); - RenderArrowPointingAt(draw_list, ImVec2(p.x + half_sz.x + 1, p.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); - RenderArrowPointingAt(draw_list, ImVec2(p.x + half_sz.x, p.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); - RenderArrowPointingAt(draw_list, ImVec2(p.x + bar_w - half_sz.x - 1, p.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); - RenderArrowPointingAt(draw_list, ImVec2(p.x + bar_w - half_sz.x, p.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8)); } // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. @@ -6223,8 +6206,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl g.NextItemData.ClearFlags(); const float backup_alpha = g.Style.Alpha; - const bool is_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0 && (g.DisabledStackSize > 0); // Intentionally not check ItemFlagsSet - if (is_disabled) + if (g.DisabledStackSize > 0) g.Style.Alpha = g.DisabledAlphaBackup; // Cancel out effect of BeginDisabled() for color swatches. PushID(label); @@ -6586,7 +6568,7 @@ bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags fl g.ColorEditCurrentID = 0; PopID(); - if (is_disabled) + if (g.DisabledStackSize > 0) g.Style.Alpha = backup_alpha; return value_changed; @@ -6627,8 +6609,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl const bool is_mixed = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0; const float backup_alpha = g.Style.Alpha; - const bool is_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0 && (g.DisabledStackSize > 0); // Intentionally not use LastItemData.ItemFlags here. - if (is_disabled) + if (g.DisabledStackSize > 0) g.Style.Alpha = g.DisabledAlphaBackup; // Cancel out effect of BeginDisabled() for color swatches. if (is_mixed) { @@ -6642,10 +6623,10 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl { float mid_x = IM_ROUND((bb.Min.x + bb.Max.x) * 0.5f); if ((flags & ImGuiColorEditFlags_AlphaNoBg) == 0) - RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, ColorConvertFloat4ToU32(col_rgb), g.Style.Alpha, grid_step, ImVec2(-grid_step, 0.0f), rounding, ImDrawFlags_RoundRight); + RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, ColorConvertFloat4ToU32(col_rgb), g.Style.Alpha, grid_step, ImVec2(-grid_step, 0.0f), rounding, ImDrawFlags_RoundCornersRight); else - window->DrawList->AddRectFilled(ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundRight); - window->DrawList->AddRectFilled(bb.Min, ImVec2(mid_x, bb.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundLeft); + window->DrawList->AddRectFilled(ImVec2(bb.Min.x + grid_step, bb.Min.y), bb.Max, GetColorU32(col_rgb), rounding, ImDrawFlags_RoundCornersRight); + window->DrawList->AddRectFilled(bb.Min, ImVec2(mid_x, bb.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft); } else { @@ -6656,7 +6637,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl else window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(col_source), rounding); } - if (is_disabled) + if (g.DisabledStackSize > 0) g.Style.Alpha = backup_alpha; RenderNavCursor(bb, id); if ((flags & ImGuiColorEditFlags_NoBorder) == 0) @@ -6941,15 +6922,13 @@ bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char return TreeNodeBehavior(id, flags, label, label_end); } -// I would like to design a more feature-full and generic API for this. -// (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722, #9569) -bool ImGui::TreeNodeGetOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags) +// The reason those two functions are not yet in public API is because I would like to design a more feature-full and generic API for this. +// They are otherwise function (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722) +bool ImGui::TreeNodeGetOpen(ImGuiID storage_id) { - if (flags & ImGuiTreeNodeFlags_Leaf) - return true; ImGuiContext& g = *GImGui; ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage; - return storage->GetInt(storage_id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; + return storage->GetInt(storage_id, 0) != 0; } void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool is_open) @@ -7051,10 +7030,9 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l label_end = FindRenderedTextEnd(label); const ImVec2 label_size = CalcTextSize(label, label_end, false); - const float icon_width = g.FontSize + padding.x * 2; - const float text_offset_x = display_frame ? icon_width + padding.x : icon_width; // Collapsing arrow width + Spacing + const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapsing arrow width + Spacing const float text_offset_y = use_frame_padding ? ImMax(style.FramePadding.y, window->DC.CurrLineTextBaseOffset) : window->DC.CurrLineTextBaseOffset; // Latch before ItemSize changes it - const float text_width = icon_width + label_size.x; // Include collapsing arrow + const float text_width = g.FontSize + label_size.x + padding.x * 2; // Include collapsing arrow const float frame_height = label_size.y + padding.y * 2; const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL); @@ -7087,7 +7065,6 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (span_all_columns || span_all_columns_label) { // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. - // FIXME: Investigate moving this to an item flag, along duplicate code in Selectable(). How to do optimally? const float backup_clip_rect_min_x = window->ClipRect.Min.x; const float backup_clip_rect_max_x = window->ClipRect.Max.x; window->ClipRect.Min.x = window->ParentWorkRect.Min.x; @@ -7295,7 +7272,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col); else if (!is_leaf) - RenderArrow(window->DrawList, ImVec2(text_pos.x + g.FontSize * 0.15f - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 0.70f); + RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 0.70f); if (g.LogEnabled) LogSetNextTextDecoration(">", NULL); } @@ -7331,19 +7308,17 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) if ((window->DC.TreeHasStackDataDepthMask & TREE_NODE_GET_DEPTH_MASK(window->DC.TreeDepth - 1)) == 0) return; - // FIXME: Could this be simplified using new stroke flags? ImGuiTreeNodeStackData* parent_data = &g.TreeNodeStack.Data[g.TreeNodeStack.Size - 1]; - const float half_size = g.Style.TreeLinesSize * 0.5f; - float x1 = ImTrunc(parent_data->DrawLinesX1 - half_size) + half_size; // Draw line centered at X1, but snap to pixels boundary. + float x1 = ImTrunc(parent_data->DrawLinesX1); float x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x); - float y = ImTrunc(target_pos.y - half_size) + half_size; + float y = ImTrunc(target_pos.y); float rounding = (g.Style.TreeLinesRounding > 0.0f) ? ImMin(x2 - x1, g.Style.TreeLinesRounding) : 0.0f; parent_data->DrawLinesToNodesY2 = ImMax(parent_data->DrawLinesToNodesY2, y - rounding); if (x1 >= x2) return; - if (rounding > 0.0f && rounding > half_size) + if (rounding > 0.0f) { - x1 += rounding; + x1 += 0.5f + rounding; window->DrawList->PathArcToFast(ImVec2(x1, y - rounding), rounding, 6, 3); if (x1 < x2) window->DrawList->PathLineTo(ImVec2(x2, y)); @@ -7351,10 +7326,7 @@ void ImGui::TreeNodeDrawLineToChildNode(const ImVec2& target_pos) } else { - // We use AddLine() instead of AddLineH() as we provide coordinates for line center, - // in order to make the code use same coordinates for both rounded and non-rounded version. (FIXME-OPT) - x1 += half_size; // Avoid overdraw - window->DrawList->AddLine(ImVec2(x1, y), ImVec2(x2, y), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + window->DrawList->AddLineH(x1, x2, y, GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); } } @@ -7377,12 +7349,10 @@ void ImGui::TreeNodeDrawLineToTreePop(const ImGuiTreeNodeStackData* data) y2 = ImMin(y2, window->ClipRect.Max.y); if (y2 <= y1) return; - float x = ImTrunc(data->DrawLinesX1 - g.Style.TreeLinesSize * 0.5f) + g.Style.TreeLinesSize * 0.5f; // Draw line centered at X1, but snap to pixels boundary. + float x = ImTrunc(data->DrawLinesX1); if (data->DrawLinesTableColumn != -1) TablePushColumnChannel(data->DrawLinesTableColumn); - - // We use AddLine() instead of AddLineV() as we provide coordinates for line center (FIXME-OPT) - window->DrawList->AddLine(ImVec2(x, y1), ImVec2(x, y2), GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); + window->DrawList->AddLineV(x, y1, y2, GetColorU32(ImGuiCol_TreeLines), g.Style.TreeLinesSize); if (data->DrawLinesTableColumn != -1) TablePopColumnChannel(); } @@ -7646,7 +7616,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope()) // - (2) usage will fail with clipped items // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API. - if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId && !g.NavJustMovedToIsInit) + if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId) if (g.NavJustMovedToId == id && (g.NavJustMovedToKeyMods & ImGuiMod_Ctrl) == 0) selected = pressed = auto_selected = true; } @@ -8813,7 +8783,7 @@ bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* it = _Storage.Data.Data; IM_ASSERT(it >= _Storage.Data.Data && it <= it_end); if (it != it_end) - while (it < it_end && it->val_i == 0) + while (it->val_i == 0 && it < it_end) it++; const bool has_more = (it != it_end); *opaque_it = has_more ? (void**)(it + 1) : (void**)(it); @@ -9167,7 +9137,7 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) ); - // We could render lower-level to save a bit of CPU. + // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t)); if (plot_type == ImGuiPlotType_Lines) @@ -9178,8 +9148,6 @@ int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_get { if (pos1.x >= pos0.x + 2.0f) pos1.x -= 1.0f; - if (pos0.y > pos1.y) - ImSwap(pos0.y, pos1.y); window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base); } @@ -9455,10 +9423,14 @@ bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, Im } window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; + + // Create window + PushStyleColor(ImGuiCol_WindowShadow, ImVec4(0, 0, 0, 0)); PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint bool is_open = Begin(name, NULL, window_flags); PopStyleVar(2); + PopStyleColor(); return is_open; } @@ -10081,7 +10053,7 @@ void ImGui::EndTabBar() // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); - if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabContentsId == 0 || tab_bar_appearing) + if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing) { tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight); window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight; @@ -10129,7 +10101,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose) { // Remove tab - if (tab_bar->VisibleTabContentsId == tab->ID) { tab_bar->VisibleTabContentsId = 0; } + if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; } if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; } if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; } continue; @@ -10334,8 +10306,8 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID; // Lock in visible tab - tab_bar->VisibleTabContentsId = tab_bar->SelectedTabId; - tab_bar->VisibleTabWasSubmitted = tab_bar->LastTabItemContentsAppearing = false; + tab_bar->VisibleTabId = tab_bar->SelectedTabId; + tab_bar->VisibleTabWasSubmitted = false; // Apply request requests if (scroll_to_tab_id != 0) @@ -10448,9 +10420,9 @@ void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) { if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) tab_bar->Tabs.erase(tab); - if (tab_bar->VisibleTabContentsId == tab_id){ tab_bar->VisibleTabContentsId = 0; } - if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } - if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } + if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; } + if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } + if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } } // Called on manual closure attempt @@ -10464,7 +10436,7 @@ void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) // This will remove a frame of lag for selecting another tab on closure. // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure tab->WantClose = true; - if (tab_bar->VisibleTabContentsId == tab->ID) + if (tab_bar->VisibleTabId == tab->ID) { tab->LastFrameVisible = -1; tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0; @@ -10473,7 +10445,7 @@ void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) else { // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) - if (tab_bar->VisibleTabContentsId != tab->ID) + if (tab_bar->VisibleTabId != tab->ID) TabBarQueueFocus(tab_bar, tab); } } @@ -10764,12 +10736,6 @@ void ImGui::EndTabItem() PopID(); } -bool ImGui::TabItemIsContentsAppearing() -{ - ImGuiContext& g = *GImGui; - return g.CurrentTabBar->LastTabItemContentsAppearing; -} - bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags) { ImGuiContext& g = *GImGui; @@ -10881,24 +10847,21 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, TabBarQueueFocus(tab_bar, tab); } - // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches - if (tab_bar->VisibleTabContentsId == 0 && tab_bar->SelectedTabId == 0 && tab_bar_appearing) - if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) - tab_bar->VisibleTabContentsId = id; - // Lock visibility // (Note: tab_contents_visible != tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) - const bool tab_contents_visible = (tab_bar->VisibleTabContentsId == id); + bool tab_contents_visible = (tab_bar->VisibleTabId == id); if (tab_contents_visible) tab_bar->VisibleTabWasSubmitted = true; - tab_bar->LastTabItemContentsAppearing = tab_contents_visible && !tab->ContentsIsVisible; - tab->ContentsIsVisible = tab_contents_visible; + + // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches + if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing) + if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) + tab_contents_visible = true; // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. if (tab_appearing && (!tab_bar_appearing || tab_is_new)) { - // This path doesn't render the tab. ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav); if (is_tab_button) return false; @@ -10985,8 +10948,8 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f) { // Might be moved to TabItemBackground() ? - ImVec2 tl = bb.GetTL() + ImVec2(0, style.TabBarOverlineSize * 0.5f); - ImVec2 tr = bb.GetTR() + ImVec2(0, style.TabBarOverlineSize * 0.5f); + ImVec2 tl = bb.GetTL() + ImVec2(0, 1.0f * g.CurrentDpiScale); + ImVec2 tr = bb.GetTR() + ImVec2(0, 1.0f * g.CurrentDpiScale); ImU32 overline_col = GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline); if (style.TabRounding > 0.0f) { @@ -10997,7 +10960,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, } else { - display_draw_list->AddLine(tl, tr, overline_col, style.TabBarOverlineSize); + display_draw_list->AddLine(tl - ImVec2(0.5f, 0.5f), tr - ImVec2(0.5f, 0.5f), overline_col, style.TabBarOverlineSize); } } RenderNavCursor(bb, id); @@ -11086,14 +11049,14 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f)); const float y1 = bb.Min.y + 1.0f; // Leave a bit of room in title bars. const float y2 = bb.Max.y - g.Style.TabBarBorderSize; - draw_list->AddRectFilled(ImVec2(bb.Min.x, y1), ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags_RoundTop); + draw_list->AddRectFilled(bb.Min, ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags_RoundCornersTop); if (g.Style.TabBorderSize > 0.0f) { - draw_list->PathLineTo(ImVec2(bb.Min.x, y2)); - draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9); - draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12); - draw_list->PathLineTo(ImVec2(bb.Max.x, y2)); - draw_list->PathStroke(GetColorU32(ImGuiCol_Border), g.Style.TabBorderSize, ImDrawFlags_StrokeCenterBiased); // Use _StrokeInside? + draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2)); + draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9); + draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12); + draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2)); + draw_list->PathStroke(GetColorU32(ImGuiCol_Border), g.Style.TabBorderSize); } } diff --git a/imstb_rectpack.h b/imstb_rectpack.h index a80217382..ad0892130 100644 --- a/imstb_rectpack.h +++ b/imstb_rectpack.h @@ -2,7 +2,7 @@ // This is a slightly modified version of stb_rect_pack.h 1.01. // Grep for [DEAR IMGUI] to find the changes. // -// stb_rect_pack.h - v1.02 - public domain - rectangle packing +// stb_rect_pack.h - v1.01 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -42,7 +42,6 @@ // Bugfixes / warning fixes // Jeremy Jaussaud // Fabian Giesen -// Joshua Simmons // // Version history: // @@ -534,11 +533,7 @@ static int STBRP__CDECL rect_height_compare(const void *a, const void *b) return -1; if (p->h < q->h) return 1; - if (p->w > q->w) - return -1; - if (p->w < q->w) - return 1; - return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); + return (p->w > q->w) ? -1 : (p->w < q->w); } static int STBRP__CDECL rect_original_order(const void *a, const void *b) diff --git a/imstb_textedit.h b/imstb_textedit.h index a5b0b2687..583508f0b 100644 --- a/imstb_textedit.h +++ b/imstb_textedit.h @@ -1,15 +1,15 @@ // [DEAR IMGUI] -// This is a slightly modified version of stb_textedit.h 1.15. +// This is a slightly modified version of stb_textedit.h 1.14. // Those changes would need to be pushed into nothings/stb: // - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) -// - Added line movement hooks and cursor-side tracking for word-wrapping. +// - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783) // - Added name to struct or it may be forward declared in our code. // - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925) // - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. // Grep for [DEAR IMGUI] to find some changes. // - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* -// stb_textedit.h - v1.15 - public domain - Sean Barrett +// stb_textedit.h - v1.14 - public domain - Sean Barrett // Development of this library was sponsored by RAD Game Tools // // This C header file implements the guts of a multi-line text-editing @@ -40,9 +40,7 @@ // // VERSION HISTORY // -// x.xx (2026-11-12) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. -// x.xx (2026-11-12) add stb_textedit_text(), STB_TEXTEDIT_GETPREVCHARINDEX(), STB_TEXTEDIT_GETNEXTCHARINDEX() to facilitate UTF-8 support while preserving byte indices. -// 1.15 (2026-11-08) various fixes +// !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. // 1.14 (2021-07-11) page up/down, various fixes // 1.13 (2019-02-07) fix bug in undo size management // 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash @@ -184,12 +182,12 @@ // STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text // STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text // -// To support UTF-8 while using indices to _bytes_ (instead of indices to _codepoints_): +// To support UTF-8: // // STB_TEXTEDIT_GETPREVCHARINDEX returns index of previous character // STB_TEXTEDIT_GETNEXTCHARINDEX returns index of next character -// Call stb_textedit_text() directly to submit text contents. // Do NOT define STB_TEXTEDIT_KEYTOTEXT. +// Instead, call stb_textedit_text() directly for text contents. // // Keyboard input must be encoded as a single integer value; e.g. a character code // and some bitflags that represent shift states. to simplify the interface, SHIFT must @@ -223,9 +221,8 @@ // void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) // int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) // int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) -// void stb_textedit_char(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE ch) -// void stb_textedit_text(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len) // void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key) +// void stb_textedit_text(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int text_len) // // Each of these functions potentially updates the string and updates the // state. @@ -252,18 +249,6 @@ // call this to paste text at the current cursor point or over the current // selection if there is one. // -// char: -// (optional) call this for character input sent to the textfield. if the -// framework you are using supplies you with a character or text event, it -// makes sense to use this function. -// make sure to set STB_TEXTEDIT_KEYTOTEXT to 0 for any key that generates -// a corresponding character or text event. -// -// text: -// (optional) call this to directly send text input the textfield, which is -// helpful for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() -// cannot infer text length. -// // key: // call this for keyboard inputs sent to the textfield. you can use it // for "key down" events or for "translated" key events. if you need to @@ -272,10 +257,15 @@ // various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit // set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is // clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to -// any other type you want before including. +// anything other type you want before including. // if the STB_TEXTEDIT_KEYTOTEXT function is defined, selected keys are // transformed into text and stb_textedit_text() is automatically called. // +// text: (added 2025) +// call this to directly send text input the textfield, which is required +// for UTF-8 support, because stb_textedit_key() + STB_TEXTEDIT_KEYTOTEXT() +// cannot infer text length. +// // // When rendering, you can read the cursor position and selection state from // the STB_TexteditState. @@ -423,9 +413,12 @@ typedef struct #define IMSTB_TEXTEDIT_memmove memmove #endif -// Functions must be implemented for UTF-8 support with indices to bytes. -#ifndef STB_TEXTEDIT_GETPREVCHARINDEX -#define STB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) +// [DEAR IMGUI] +// Functions must be implemented for UTF8 support +// Code in this file that uses those functions is modified for [DEAR IMGUI] and deviates from the original stb_textedit. +// There is not necessarily a '[DEAR IMGUI]' at the usage sites. +#ifndef IMSTB_TEXTEDIT_GETPREVCHARINDEX +#define IMSTB_TEXTEDIT_GETPREVCHARINDEX(OBJ, IDX) ((IDX) - 1) #endif #ifndef IMSTB_TEXTEDIT_GETNEXTCHARINDEX #define IMSTB_TEXTEDIT_GETNEXTCHARINDEX(OBJ, IDX) ((IDX) + 1) @@ -574,25 +567,36 @@ static void stb_textedit_find_charpos(StbFindState *find, IMSTB_TEXTEDIT_STRING int z = STB_TEXTEDIT_STRINGLEN(str); int i=0, first; + if (n == z && single_line) { + // special case if it's at the end (may not be needed?) + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + find->y = 0; + find->first_char = 0; + find->length = z; + find->height = r.ymax - r.ymin; + find->x = r.x1; + return; + } + // search rows to find the one that straddles character n find->y = 0; for(;;) { STB_TEXTEDIT_LAYOUTROW(&r, str, i); - - // Use the regular layout scan for EOF, including an empty final row. - // [DEAR IMGUI] At a soft-wrap boundary, the cursor side determines the row. - // A row without a newline is not necessarily the last row when word-wrapping. - if (n <= i + r.num_chars) { - if (n < i + r.num_chars || r.num_chars == 0 || single_line) - break; - if (STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE && (n == z || str->LastMoveDirectionLR == ImGuiDir_Right)) - break; - } - + if (n < i + r.num_chars) + break; + if (str->LastMoveDirectionLR == ImGuiDir_Right && str->Stb->cursor > 0 && str->Stb->cursor == i + r.num_chars && STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] Wrapping point handling + break; + if (i + r.num_chars == z && z > 0 && STB_TEXTEDIT_GETCHAR(str, z - 1) != STB_TEXTEDIT_NEWLINE) // [DEAR IMGUI] special handling for last line + break; // [DEAR IMGUI] prev_start = i; i += r.num_chars; find->y += r.baseline_y_delta; + if (i == z) // [DEAR IMGUI] + { + r.num_chars = 0; // [DEAR IMGUI] + break; // [DEAR IMGUI] + } } find->first_char = first = i; @@ -785,11 +789,16 @@ static int stb_textedit_paste_internal(IMSTB_TEXTEDIT_STRING *str, STB_TexteditS return 0; } +#ifndef STB_TEXTEDIT_KEYTYPE +#define STB_TEXTEDIT_KEYTYPE int +#endif + // API key: process text input +// [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len) { // can't add newline in single-line mode - if (text[0] == STB_TEXTEDIT_NEWLINE && state->single_line) + if (text[0] == '\n' && state->single_line) return; if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { @@ -811,16 +820,6 @@ static void stb_textedit_text(IMSTB_TEXTEDIT_STRING* str, STB_TexteditState* sta } } -// API char: process a character input -static void stb_textedit_char(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, IMSTB_TEXTEDIT_CHARTYPE ch) -{ - stb_textedit_text(str, state, &ch, 1); -} - -#ifndef STB_TEXTEDIT_KEYTYPE -#define STB_TEXTEDIT_KEYTYPE int -#endif - // API key: process a keyboard input static void stb_textedit_key(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key) { @@ -828,11 +827,11 @@ retry: switch (key) { default: { #ifdef STB_TEXTEDIT_KEYTOTEXT - // This is not suitable for UTF-8 support with indices to bytes. + // This is not suitable for UTF-8 support. int c = STB_TEXTEDIT_KEYTOTEXT(key); if (c > 0) { - IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE) c; - stb_textedit_char(str, state, ch); + IMSTB_TEXTEDIT_CHARTYPE ch = (IMSTB_TEXTEDIT_CHARTYPE)c; + stb_textedit_text(str, state, &ch, 1); } #endif break; @@ -1034,15 +1033,9 @@ retry: for (j = 0; j < row_count; ++j) { float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x; - // if there's no previous row set cursor to start of the line - if (find.prev_first == find.first_char) { - state->cursor = find.first_char; - stb_textedit_clamp(str, state); - - if (sel) - state->select_end = state->cursor; + // can only go up if there's a previous row + if (find.prev_first == find.first_char) break; - } // now find character position up a row state->cursor = find.prev_first; @@ -1370,7 +1363,6 @@ static void stb_text_undo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) } state->cursor = u.where + u.insert_length; - state->select_start = state->select_end = state->cursor; s->undo_point--; s->redo_point--; @@ -1422,7 +1414,6 @@ static void stb_text_redo(IMSTB_TEXTEDIT_STRING *str, STB_TexteditState *state) } state->cursor = r.where + r.insert_length; - state->select_start = state->select_end = state->cursor; s->undo_point++; s->redo_point++; diff --git a/imstb_truetype.h b/imstb_truetype.h index 0bc602f6c..ec4d42c7d 100644 --- a/imstb_truetype.h +++ b/imstb_truetype.h @@ -1,9 +1,9 @@ // [DEAR IMGUI] -// This is a slightly modified version of stb_truetype.h 1.27. +// This is a slightly modified version of stb_truetype.h 1.26. // Mostly fixing for compiler and static analyzer warnings. // Grep for [DEAR IMGUI] to find the changes. -// stb_truetype.h - v1.27 - public domain +// stb_truetype.h - v1.26 - public domain // authored from 2009-2021 by Sean Barrett / RAD Game Tools // // ======================================================================= @@ -50,7 +50,7 @@ // Cass Everitt Martins Mozeiko github:aloucks // stoiko (Haemimont Games) Cap Petschulat github:oyvindjam // Brian Hook Omar Cornut github:vassvik -// Walter van Niftrik Ryan Griege github:Cerallin +// Walter van Niftrik Ryan Griege // David Gow Peter LaValle // David Given Sergey Popov // Ivan-Assen Ivanov Giumo X. Clanjor @@ -59,13 +59,10 @@ // Hou Qiming Derek Vinyard // Rob Loach Cort Stratton // Kenney Phillis Jr. Brian Costabile -// Ken Voskuil (kaesve) Yakov Galka -// Neil Bickford Matthias Dorfelt -// Isaac "Atridas" Serrano +// Ken Voskuil (kaesve) // // VERSION HISTORY // -// 1.27 (2026-11-08) many fixes, support vertical layout, underlines, font name // 1.26 (2021-08-28) fix broken rasterizer // 1.25 (2021-07-11) many fixes // 1.24 (2020-02-05) fix warning @@ -209,10 +206,10 @@ // Baseline: // You need to select a y-coordinate that is the baseline of where // your text will appear. Call GetFontBoundingBox to get the baseline-relative -// bounding box for all characters. SF*y1 will be the distance in pixels +// bounding box for all characters. SF*-y0 will be the distance in pixels // that the worst-case character could extend above the baseline, so if // you want the top edge of characters to appear at the top of the -// screen where y=0, then you would set the baseline to SF*y1. +// screen where y=0, then you would set the baseline to SF*-y0. // // Current point: // Set the current point where the first character will appear. The @@ -223,10 +220,10 @@ // the current point based on that. // // Displaying a character: -// Call a function to compute the bounding box of the character. It will contain -// signed values relative to . I.e. if it returns x0,y0, -// x1,y1, then the character should be displayed in the rectangle from -// to . +// Compute the bounding box of the character. It will contain signed values +// relative to . I.e. if it returns x0,y0,x1,y1, +// then the character should be displayed in the rectangle from +// to @@ -345,10 +342,10 @@ int main(int argc, char **argv) unsigned char *bitmap; int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); - fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); // fclose() omitted for clarity + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); - bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); // stbtt_FreeBitmap() omitted for clarity + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); for (j=0; j < h; ++j) { for (i=0; i < w; ++i) @@ -374,7 +371,7 @@ int main(int argc, char **argv) // ////////////////////////////////////////////////////////////////////////////// // -// Complete program: print "Hello World!" banner, with bugs & no cleanup +// Complete program: print "Hello World!" banner, with bugs // #if 0 char buffer[24<<20]; @@ -628,7 +625,7 @@ typedef struct { float font_size; int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint - const int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints int num_chars; stbtt_packedchar *chardata_for_range; // output unsigned char h_oversample, v_oversample; // don't set these, they're used internally @@ -726,7 +723,7 @@ struct stbtt_fontinfo int numGlyphs; // number of glyphs, needed for range checking - int loca,head,glyf,hhea,hmtx,vhea,vmtx,kern,gpos,svg; // table locations as offset from start of .ttf + int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph @@ -748,7 +745,7 @@ STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, in ////////////////////////////////////////////////////////////////////////////// // -// CHARACTER TO GLYPH-INDEX CONVERSION +// CHARACTER TO GLYPH-INDEX CONVERSIOn STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); // If you're going to perform multiple operations on the same character @@ -771,10 +768,6 @@ STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixe // scale = pixels / (ascent - descent) // so if you prefer to measure height by the ascent only, use a similar calculation. -STBTT_DEF float stbtt_ScaleForPixelWidth(const stbtt_fontinfo *info, float pixels); -// computes a scale factor to produce a font whose width is 'pixels' wide. -// Width is measured as the distance from the left-side-bearing to the right-side-bearing - STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); // computes a scale factor to produce a font whose EM size is mapped to // 'pixels' tall. This is probably what traditional APIs compute, but @@ -788,9 +781,6 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in // these are expressed in unscaled coordinates, so you must multiply by // the scale factor for a given size -STBTT_DEF void stbtt_GetFontHMetrics(const stbtt_fontinfo *info, int *vertTypoAscender, int *vertTypoDescender, int *vertTypoLineGap); - - STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); // analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 // table (specific to MS/Windows TTF files). @@ -800,11 +790,6 @@ STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAsc STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); // the bounding box around all possible characters -STBTT_DEF int stbtt_GetFontUnderlineMetrics(const stbtt_fontinfo *info, int *position, int *thickness); -// the underline position and thickness as defined in the "post" table -// -// Returns 1 on success (table present), 0 on failure. - STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); // leftSideBearing is the offset from the current horizontal position to the left edge of the character // advanceWidth is the offset from the current horizontal position to the next horizontal position @@ -817,7 +802,6 @@ STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, i // Gets the bounding box of the visible part of the glyph, in unscaled coordinates STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); -STBTT_DEF void stbtt_GetGlyphVMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceHeight, int *topSideBearing); STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); // as above, but takes one or more glyph indices for greater efficiency @@ -1059,12 +1043,9 @@ STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *l // and puts the length in bytes in *length. // // some of the values for the IDs are below; for more see the truetype spec: -// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html +// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html // http://www.microsoft.com/typography/otspec/name.htm -STBTT_DEF int stbtt_GetFontNameDefault(const stbtt_fontinfo *font, char *output_buffer, size_t output_buffer_len); -// return the default english full name of the font as utf-8 - enum { // platformID STBTT_PLATFORM_ID_UNICODE =0, STBTT_PLATFORM_ID_MAC =1, @@ -1408,7 +1389,6 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in { stbtt_uint32 cmap, t; stbtt_int32 i,numTables; - stbtt_uint32 symbol_map=0; info->data = data; info->fontstart = fontstart; @@ -1420,8 +1400,6 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required - info->vhea = stbtt__find_table(data, fontstart, "vhea"); // not required - info->vmtx = stbtt__find_table(data, fontstart, "vmtx"); // not required info->kern = stbtt__find_table(data, fontstart, "kern"); // not required info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required @@ -1504,9 +1482,6 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in // MS/Unicode info->index_map = cmap + ttULONG(data+encoding_record+4); break; - case STBTT_MS_EID_SYMBOL: - symbol_map = cmap + ttULONG(data+encoding_record+4); - break; } break; case STBTT_PLATFORM_ID_UNICODE: @@ -1516,9 +1491,6 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in break; } } - if (info->index_map == 0) - info->index_map = symbol_map; - if (info->index_map == 0) return 0; @@ -1532,7 +1504,6 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep stbtt_uint32 index_map = info->index_map; stbtt_uint16 format = ttUSHORT(data + index_map + 0); - if (format == 0) { // apple byte encoding stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) @@ -1578,35 +1549,19 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep search += 2; { - stbtt_uint16 offset, start, last, index; - stbtt_int16 delta; + stbtt_uint16 offset, start, last; stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); - // get the actual range for this segment start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); last = ttUSHORT(data + endCount + 2*item); if (unicode_codepoint < start || unicode_codepoint > last) return 0; offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); - delta = ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item); - - // "if idRangeOffset is 0, the idDelta value is added directly to the character code" if (offset == 0) - return (stbtt_uint16) (unicode_codepoint + delta); + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); - // "If the idRangeOffset value for the segment is not 0, ..." - // "glyphIndexAddress = idRangeOffset[i] + 2 * (c - startCode[i]) + (Ptr) &idRangeOffset[i]" - index = ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); - - // "Once the glyph indexing operation is complete, the glyph ID at the indicated address - // is checked. If it's not 0 (that is, if it's not the missing glyph), the value is added - // to idDelta[i] to get the actual glyph ID to use." - if (index != 0) { - index = (stbtt_uint16) (index + delta); - } - - return index; + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); @@ -1675,7 +1630,7 @@ static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, in STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { if (info->cff.size) { - return stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); } else { int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; @@ -1817,8 +1772,8 @@ static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, s if (i != 0) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - // now start the new one... avoid looking ahead if we're at the end of a contour - start_off = !(flags & 1) && i < ttUSHORT(endPtsOfContours+j*2); + // now start the new one + start_off = !(flags & 1); if (start_off) { // if we start off with an off-curve point, then when we need to find a point on the curve // where we can start, and we need to save some state for when we wraparound. @@ -1901,35 +1856,23 @@ static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, s mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; } - // Find transformation scales. Per TrueType spec, these are used - // ONLY to rescale the offsets (mtx[4], mtx[5]) when - // SCALED_COMPONENT_OFFSET (flag bit 11, 0x800) is set. They must - // NOT scale the linear part of the transform — doing so squares - // the scale factor and is the cause of composite sub-components - // rendering at wrong sizes in COLR emoji fonts (OpenMoji, Noto - // Color Emoji, Microsoft Fluent Emoji). + // Find transformation scales. m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); - // Default: UNSCALED offsets (Microsoft convention; matches modern - // font tooling). Only SCALED_COMPONENT_OFFSET (bit 11) set without - // UNSCALED_COMPONENT_OFFSET (bit 12) triggers the offset rescale. - if ((flags & (1<<11)) && !(flags & (1<<12))) { - mtx[4] *= m; mtx[5] *= n; - } // Get indexed glyph. comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); if (comp_num_verts > 0) { - // Transform vertices: v' = M·v + t. No double-scaling. + // Transform vertices. for (i = 0; i < comp_num_verts; ++i) { stbtt_vertex* v = &comp_verts[i]; stbtt_vertex_type x,y; x=v->x; y=v->y; - v->x = (stbtt_vertex_type)(mtx[0]*x + mtx[2]*y + mtx[4]); - v->y = (stbtt_vertex_type)(mtx[1]*x + mtx[3]*y + mtx[5]); + v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); x=v->cx; y=v->cy; - v->cx = (stbtt_vertex_type)(mtx[0]*x + mtx[2]*y + mtx[4]); - v->cy = (stbtt_vertex_type)(mtx[1]*x + mtx[3]*y + mtx[5]); + v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); } // Append vertices. tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); @@ -2065,7 +2008,7 @@ static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int gly start = end; } } - if (fdselector == -1) return stbtt__new_buf(NULL, 0); + if (fdselector == -1) return stbtt__new_buf(NULL, 0); // [DEAR IMGUI] fixed, see #6007 and nothings/stb#1422 return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); } @@ -2376,12 +2319,6 @@ STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_inde } } -STBTT_DEF void stbtt_GetGlyphVMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceHeight, int *topSideBearing) -{ - if (advanceHeight) *advanceHeight = ttSHORT(info->data + info->vmtx + 4*glyph_index); - if (topSideBearing) *topSideBearing = ttSHORT(info->data + info->vmtx + 4*glyph_index + 2); -} - STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) { stbtt_uint8 *data = info->data + info->kern; @@ -2574,7 +2511,7 @@ static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, in data = info->data + info->gpos; if (ttUSHORT(data+0) != 1) return 0; // Major version 1 - if (ttUSHORT(data+2) > 1) return 0; // Minor version 0, or 1 + if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 lookupListOffset = ttUSHORT(data+8); lookupList = data + lookupListOffset; @@ -2587,28 +2524,15 @@ static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, in stbtt_uint16 lookupType = ttUSHORT(lookupTable); stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4); stbtt_uint8 *subTableOffsets = lookupTable + 6; - if (lookupType != 2 && // Pair Adjustment Positioning Subtable - lookupType != 9) // Positioning Subtable Extension + if (lookupType != 2) // Pair Adjustment Positioning Subtable continue; for (sti=0; sti= class1Count) return 0; // malformed if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed - valueRecordPairSizeInBytes = valueFormat1 == 68 ? 4 : 2; - class1Records = table + 16; - class2Records = class1Records + valueRecordPairSizeInBytes * (glyph1class * class2Count); - xAdvance = ttSHORT(class2Records + valueRecordPairSizeInBytes * glyph2class); + class2Records = class1Records + 2 * (glyph1class * class2Count); + xAdvance = ttSHORT(class2Records + 2 * glyph2class); return xAdvance; } else return 0; @@ -2700,10 +2617,9 @@ STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int int xAdvance = 0; if (info->gpos) - xAdvance = stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); - - if (info->kern && xAdvance == 0) - xAdvance = stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + else if (info->kern) + xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); return xAdvance; } @@ -2720,11 +2636,6 @@ STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepo stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); } -STBTT_DEF void stbtt_GetCodepointVMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceHeight, int *topSideBearing) -{ - stbtt_GetGlyphVMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceHeight, topSideBearing); -} - STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) { if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); @@ -2732,13 +2643,6 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); } -STBTT_DEF void stbtt_GetFontHMetrics(const stbtt_fontinfo *info, int *vertTypoAscender, int *vertTypoDescender, int *vertTypoLineGap) -{ - if (vertTypoAscender ) *vertTypoAscender = ttSHORT(info->data+info->vhea + 4); - if (vertTypoDescender) *vertTypoDescender = ttSHORT(info->data+info->vhea + 6); - if (vertTypoLineGap) *vertTypoLineGap = ttSHORT(info->data+info->vhea + 8); -} - STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) { int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); @@ -2758,28 +2662,12 @@ STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y1 = ttSHORT(info->data + info->head + 42); } -STBTT_DEF int stbtt_GetFontUnderlineMetrics(const stbtt_fontinfo *info, int *position, int *thickness) -{ - int tab = stbtt__find_table(info->data, info->fontstart, "post"); - if (!tab) - return 0; - *position = ttSHORT(info->data + tab + 8); - *thickness = ttSHORT(info->data + tab + 10); - return 1; -} - STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } -STBTT_DEF float stbtt_ScaleForPixelWidth(const stbtt_fontinfo *info, float width) -{ - int fwidth = ttSHORT(info->data + info->hhea + 10) - ttSHORT(info->data + info->hhea + 12); - return (float) width / fwidth; -} - STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { int unitsPerEm = ttUSHORT(info->data + info->head + 18); @@ -3314,8 +3202,9 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, if (y_final > y_bottom) { int denom = (x2 - (x1+1)); y_final = y_bottom; - if (denom != 0) + if (denom != 0) { // [DEAR IMGUI] Avoid div by zero (https://github.com/nothings/stb/issues/1316) dy = (y_final - y_crossing ) / denom; // if denom=0, y_final = y_crossing, so y_final <= y_bottom + } } // in second pixel, area covered by line segment found in first pixel @@ -4326,7 +4215,7 @@ STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { - int i,j,k, missing_range = -1, missing_glyph = -1, return_value = 1; + int i,j,k, missing_glyph = -1, return_value = 1; // save current values int old_h_over = spc->h_oversample; @@ -4392,14 +4281,12 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const bc->xoff2 = (x0 + r->w) * recip_h + sub_x; bc->yoff2 = (y0 + r->h) * recip_v + sub_y; - if (glyph == 0) { - missing_range = i; + if (glyph == 0) missing_glyph = j; - } } else if (spc->skip_missing) { return_value = 0; } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { - ranges[i].chardata_for_range[j] = ranges[missing_range].chardata_for_range[missing_glyph]; + ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; } else { return_value = 0; // if any fail, report failure } @@ -4423,7 +4310,7 @@ STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) { stbtt_fontinfo info; - int i, j, n, return_value; + int i, j, n, return_value; // [DEAR IMGUI] removed = 1; //stbrp_context *context = (stbrp_context *) spc->pack_info; stbrp_rect *rects; @@ -4580,7 +4467,7 @@ static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], } } -static int stbtt__equal(float *a, float *b) +static int equal(float *a, float *b) { return (a[0] == b[0] && a[1] == b[1]); } @@ -4628,7 +4515,7 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex q1[1] = (float)y1; q2[0] = (float)x2; q2[1] = (float)y2; - if (stbtt__equal(q0,q1) || stbtt__equal(q1,q2)) { + if (equal(q0,q1) || equal(q1,q2)) { x0 = (int)verts[i-1].x; //-V1048 y0 = (int)verts[i-1].y; //-V1048 x1 = (int)verts[i ].x; @@ -4705,13 +4592,8 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); // if empty, return NULL - if (ix0 == ix1 || iy0 == iy1) { - if (width) *width = 0; - if (height) *height = 0; - if (xoff) *xoff = 0; - if (yoff) *yoff = 0; + if (ix0 == ix1 || iy0 == iy1) return NULL; - } ix0 -= padding; iy0 -= padding; @@ -4730,8 +4612,6 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc scale_y = -scale_y; { - // distance from singular values (in the same units as the pixel grid) - const float eps = 1./1024, eps2 = eps*eps; int x,y,i,j; float *precompute; stbtt_vertex *verts; @@ -4744,15 +4624,15 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); - precompute[i] = (dist < eps) ? 0.0f : 1.0f / dist; + precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; } else if (verts[i].type == STBTT_vcurve) { float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; float len2 = bx*bx + by*by; - if (len2 >= eps2) - precompute[i] = 1.0f / len2; + if (len2 != 0.0f) + precompute[i] = 1.0f / (bx*bx + by*by); else precompute[i] = 0.0f; } else @@ -4817,8 +4697,8 @@ STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float sc float a = 3*(ax*bx + ay*by); float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); float c = mx*ax+my*ay; - if (STBTT_fabs(a) < eps2) { // if a is 0, it's linear - if (STBTT_fabs(b) >= eps2) { + if (a == 0.0) { // if a is 0, it's linear + if (b != 0.0) { res[num++] = -c/b; } } else { @@ -4968,126 +4848,6 @@ STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *l return NULL; } -// convert utf16 to utf8 and return the length required to output NUL-terminated; buffer_len of 0 means to just query length -// if you pass a buffer that's too small, it'll NULL terminate and return the actual length computed -STBTT_DEF int stbtt__ConvertUTF16BEtoUTF8(char *buffer, size_t buffer_len, unsigned char *src, size_t src_len_raw) -{ - int src_len = (int) src_len_raw; - int write_max = 0; - int i = 0, write, off = 0; - write = (buffer_len != 0); - write_max = (int) (buffer_len-1); - - if ((size_t) src_len != src_len_raw) - return -1; - - if (write) { - if (write_max < 0 || ((size_t) write_max+1 != buffer_len && write_max != 0)) - return -1; - } - - if (buffer_len == 1) { - buffer[0] = 0; - return 1; - } - - while (off < src_len) { - stbtt_uint16 ch = src[off+0]*256 + src[off+1]; - off += 2; - if (ch < 0x80) { - if (write) { - if (i >= write_max) { buffer[i] = 0; return i+1; } - buffer[i] = (char) ch; - } - ++i; - } else if (ch < 0x800) { - if (write) { - if (i+1 >= write_max) { buffer[i] = 0; return i+1; } - buffer[i+0] = (char) ( 0xc0 + (ch >> 6) ); - buffer[i+1] = (char) ( 0x80 + (ch & 0x3f) ); - } - i += 2; - } else if (ch >= 0xd800 && ch < 0xdc00) { - stbtt_uint32 c; - stbtt_uint16 ch2 = src[off+0]*256 + src[off+1]; - off += 2; - if (write) { - if (i+3 >= write_max) { buffer[i] = 0; return i+1; } - c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; - buffer[i+0] = (char) ( 0xf0 + (c >> 18) ); - buffer[i+1] = (char) ( 0x80 + ((c >> 12) & 0x3f) ); - buffer[i+2] = (char) ( 0x80 + ((c >> 6) & 0x3f) ); - buffer[i+3] = (char) ( 0x80 + ((c ) & 0x3f) ); - } - i += 4; - } else if (ch >= 0xdc00 && ch < 0xe000) { - if (write) - buffer[i] = 0; - return -1; - } else { - if (write) { - if (i+2 >= write_max) { buffer[i] = 0; return i+1; } - buffer[i+0] = (char) ( 0xe0 + (ch >> 12) ); - buffer[i+1] = (char) ( 0x80 + ((ch >> 6) & 0x3f) ); - buffer[i+2] = (char) ( 0x80 + ((ch ) & 0x3f) ); - } - i += 3; - } - } - if (write) { - STBTT_assert(i <= write_max); - buffer[i] = 0; - } - return i+1; -} - -// Returns the english full name of the font as UTF-8 -STBTT_DEF int stbtt_GetFontNameDefault(const stbtt_fontinfo *font, char *buffer, size_t buffer_len) -{ - stbtt_int32 i,count,stringOffset; - stbtt_uint8 *fc = font->data; - stbtt_uint32 offset = font->fontstart; - stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); - if (!nm) return -1; - - count = ttUSHORT(fc+nm+2); - stringOffset = nm + ttUSHORT(fc+nm+4); - for (i=0; i < count; ++i) { - char* str; - stbtt_uint16 platformId; - stbtt_uint16 encodingId; - stbtt_uint16 languageId; - size_t length; - stbtt_uint32 loc = nm + 6 + 12 * i; - if (ttUSHORT(fc+loc+6) != 4) continue; - platformId = ttUSHORT(fc+loc+0); - encodingId = ttUSHORT(fc+loc+2); - languageId = ttUSHORT(fc+loc+4); - if (!(platformId == STBTT_PLATFORM_ID_MAC && languageId == STBTT_MAC_LANG_ENGLISH) && !(platformId == STBTT_PLATFORM_ID_MICROSOFT && languageId == STBTT_MS_LANG_ENGLISH)) - continue; - - length = ttUSHORT(fc+loc+8); - str = (char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); - if (platformId == STBTT_PLATFORM_ID_UNICODE || (platformId == STBTT_PLATFORM_ID_MICROSOFT && (encodingId == 1 || encodingId == 10))) //-V560 - return stbtt__ConvertUTF16BEtoUTF8(buffer, buffer_len, (unsigned char *) str, length); - else { - if (buffer == NULL) - return (int) length; - - if (length < buffer_len) { - memcpy(buffer, str, length); - buffer[length] = 0; - return (int) length; - } else { - memcpy(buffer, str, buffer_len-1); - buffer[buffer_len-1] = 0; - return (int) length; - } - } - } - return -1; -} - static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; diff --git a/misc/freetype/imgui_freetype.cpp b/misc/freetype/imgui_freetype.cpp index d0d6b8950..79dff8bfb 100644 --- a/misc/freetype/imgui_freetype.cpp +++ b/misc/freetype/imgui_freetype.cpp @@ -1,6 +1,5 @@ -// dear imgui: FreeType font builder +// dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder) // (code) -// (used as a replacement for the stb_truetype builder) // Get the latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype // Original code by @vuhdo (Aleksei Skriabin) in 2017, with improvements by @mikesart. @@ -8,7 +7,6 @@ // CHANGELOG // (minor and older changes stripped away, please see git history for details) -// 2026/09/25: fixed handling of ExtraSizeScale. // 2025/06/11: refactored for the new ImFontLoader architecture, and ImGuiBackendFlags_RendererHasTextures support. // 2024/10/17: added plutosvg support for SVG Fonts (seems faster/better than lunasvg). Enable by using '#define IMGUI_ENABLE_FREETYPE_PLUTOSVG'. (#7927) // 2023/11/13: added support for ImFontConfig::RasterizationDensity field for scaling render density without scaling metrics. @@ -222,14 +220,17 @@ void ImGui_ImplFreeType_FontSrcData::CloseFont() } } -static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_FontSrcData* src_data, uint32_t glyph_index) +static const FT_Glyph_Metrics* ImGui_ImplFreeType_LoadGlyph(ImGui_ImplFreeType_FontSrcData* src_data, uint32_t codepoint) { + uint32_t glyph_index = FT_Get_Char_Index(src_data->FtFace, codepoint); + if (glyph_index == 0) + return nullptr; + // If this crash for you: FreeType 2.11.0 has a crash bug on some bitmap/colored fonts. // - https://gitlab.freedesktop.org/freetype/freetype/-/issues/1076 // - https://github.com/ocornut/imgui/issues/4567 // - https://github.com/ocornut/imgui/issues/4566 // You can use FreeType 2.10, or the patched version of 2.11.0 in VcPkg, or probably any upcoming FreeType version. - IM_ASSERT(glyph_index != 0); FT_Error error = FT_Load_Glyph(src_data->FtFace, glyph_index, src_data->LoadFlags); if (error) return nullptr; @@ -295,7 +296,7 @@ static void ImGui_ImplFreeType_BlitGlyph(const FT_Bitmap* ft_bitmap, uint32_t* d case FT_PIXEL_MODE_BGRA: { // FIXME: Converting pre-multiplied alpha to straight. Doesn't smell good. - #define DE_MULTIPLY(color, alpha) (ImU32)ImMin(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f, 255.0f) + #define DE_MULTIPLY(color, alpha) ImMin((ImU32)(255.0f * (float)color / (float)(alpha + FLT_MIN) + 0.5f), 255u) for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch) for (uint32_t x = 0; x < w; x++) { @@ -415,15 +416,17 @@ static bool ImGui_ImplFreeType_FontSrcInit(ImFontAtlas* atlas, ImFontConfig* src return true; } -static void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas*, ImFontConfig* src) +static void ImGui_ImplFreeType_FontSrcDestroy(ImFontAtlas* atlas, ImFontConfig* src) { + IM_UNUSED(atlas); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; IM_DELETE(bd_font_data); src->FontLoaderData = nullptr; } -static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas*, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { + IM_UNUSED(atlas); float size = baked->Size; const float ref_size = baked->OwnerFont->Sources[0]->SizePixels; if (src->MergeMode && src->SizePixels != 0.0f) @@ -460,19 +463,18 @@ static bool ImGui_ImplFreeType_FontBakedInit(ImFontAtlas*, ImFontConfig* src, Im // Read metrics FT_Size_Metrics metrics = bd_baked_data->FtSize->metrics; const float scale = 1.0f / (rasterizer_density * src->ExtraSizeScale); - baked->Ascent = ((float)metrics.ascender / FT_SCALEFACTOR) * scale; // The pixel extents above the baseline in pixels (typically positive). - baked->Descent = ((float)metrics.descender / FT_SCALEFACTOR) * scale; // The extents below the baseline in pixels (typically negative). + baked->Ascent = (float)FT_CEIL(metrics.ascender) * scale; // The pixel extents above the baseline in pixels (typically positive). + baked->Descent = (float)FT_CEIL(metrics.descender) * scale; // The extents below the baseline in pixels (typically negative). //LineSpacing = (float)FT_CEIL(metrics.height) * scale; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate. //LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender) * scale; // The spacing in pixels between one row's descent and the next row's ascent. //MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance) * scale; // This field gives the maximum horizontal cursor advance for all glyphs in the font. - baked->Ascent = ImRoundSigned64(baked->Ascent * rasterizer_density) / rasterizer_density; - baked->Descent = ImRoundSigned64(baked->Descent * rasterizer_density) / rasterizer_density; } return true; } -static void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas*, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) +static void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src) { + IM_UNUSED(atlas); IM_UNUSED(baked); IM_UNUSED(src); ImGui_ImplFreeType_FontSrcBakedData* bd_baked_data = (ImGui_ImplFreeType_FontSrcBakedData*)loader_data_for_baked_src; @@ -481,9 +483,13 @@ static void ImGui_ImplFreeType_FontBakedDestroy(ImFontAtlas*, ImFontConfig* src, bd_baked_data->~ImGui_ImplFreeType_FontSrcBakedData(); // ~IM_PLACEMENT_DELETE() } -static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, int glyph_index, ImFontGlyph* out_glyph, float* out_advance_x) +static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImFontBaked* baked, void* loader_data_for_baked_src, ImWchar codepoint, ImFontGlyph* out_glyph, float* out_advance_x) { ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; + uint32_t glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); + if (glyph_index == 0) + return false; + if (bd_font_data->BakedLastActivated != baked) // <-- could use id { // Activate current size @@ -492,7 +498,7 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf bd_font_data->BakedLastActivated = baked; } - const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, glyph_index); + const FT_Glyph_Metrics* metrics = ImGui_ImplFreeType_LoadGlyph(bd_font_data, codepoint); if (metrics == nullptr) return false; @@ -521,6 +527,7 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf const bool is_visible = (w != 0 && h != 0); // Prepare glyph + out_glyph->Codepoint = codepoint; out_glyph->AdvanceX = advance_x; // Pack and retrieve position inside texture atlas @@ -563,16 +570,12 @@ static bool ImGui_ImplFreeType_FontBakedLoadGlyph(ImFontAtlas* atlas, ImFontConf return true; } -static int ImGui_ImplFreetype_FontSrcGetGlyphIndexFromCodepoint(ImFontAtlas*, ImFontConfig* src, ImWchar codepoint) +static bool ImGui_ImplFreetype_FontSrcContainsGlyph(ImFontAtlas* atlas, ImFontConfig* src, ImWchar codepoint) { + IM_UNUSED(atlas); ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; - return (int)FT_Get_Char_Index(bd_font_data->FtFace, codepoint); -} - -static bool ImGui_ImplFreeType_FontSrcContainsGlyph(ImFontAtlas*, ImFontConfig* src, int glyph_index) -{ - ImGui_ImplFreeType_FontSrcData* bd_font_data = (ImGui_ImplFreeType_FontSrcData*)src->FontLoaderData; - return glyph_index > 0 && glyph_index < bd_font_data->FtFace->num_glyphs; + int glyph_index = FT_Get_Char_Index(bd_font_data->FtFace, codepoint); + return glyph_index != 0; } const ImFontLoader* ImGuiFreeType::GetFontLoader() @@ -583,8 +586,7 @@ const ImFontLoader* ImGuiFreeType::GetFontLoader() loader->LoaderShutdown = ImGui_ImplFreeType_LoaderShutdown; loader->FontSrcInit = ImGui_ImplFreeType_FontSrcInit; loader->FontSrcDestroy = ImGui_ImplFreeType_FontSrcDestroy; - loader->FontSrcGetGlyphIndexFromCodepoint = ImGui_ImplFreetype_FontSrcGetGlyphIndexFromCodepoint; - loader->FontSrcContainsGlyph = ImGui_ImplFreeType_FontSrcContainsGlyph; + loader->FontSrcContainsGlyph = ImGui_ImplFreetype_FontSrcContainsGlyph; loader->FontBakedInit = ImGui_ImplFreeType_FontBakedInit; loader->FontBakedDestroy = ImGui_ImplFreeType_FontBakedDestroy; loader->FontBakedLoadGlyph = ImGui_ImplFreeType_FontBakedLoadGlyph; diff --git a/misc/freetype/imgui_freetype.h b/misc/freetype/imgui_freetype.h index d271d49da..85313699d 100644 --- a/misc/freetype/imgui_freetype.h +++ b/misc/freetype/imgui_freetype.h @@ -1,6 +1,5 @@ -// dear imgui: FreeType font builder +// dear imgui: FreeType font builder (used as a replacement for the stb_truetype builder) // (headers) -// (used as a replacement for the stb_truetype builder) #pragma once #include "imgui.h" // IMGUI_API @@ -41,7 +40,6 @@ enum ImGuiFreeTypeLoaderFlags_ ImGuiFreeTypeLoaderFlags_Bitmap = 1 << 9, // Enable FreeType bitmap glyphs #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - // Renamed in 1.92.0 (June 2025) ImGuiFreeTypeBuilderFlags_NoHinting = ImGuiFreeTypeLoaderFlags_NoHinting, ImGuiFreeTypeBuilderFlags_NoAutoHint = ImGuiFreeTypeLoaderFlags_NoAutoHint, ImGuiFreeTypeBuilderFlags_ForceAutoHint = ImGuiFreeTypeLoaderFlags_ForceAutoHint,