From f37ae2d20eaf110378d6b9b6959a3ad6906d2d7d Mon Sep 17 00:00:00 2001 From: Belonit <54427022+Belonit@users.noreply.github.com> Date: Mon, 31 Aug 2026 19:18:55 +0300 Subject: [PATCH] Fix bgfx backend allocation alignment Define the required bx debug configuration and provide cache-line-aligned storage for bgfx render records. --- code/CMakeLists.txt | 2 ++ code/bgfxbackend.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/code/CMakeLists.txt b/code/CMakeLists.txt index d7c705fb..8e90291c 100644 --- a/code/CMakeLists.txt +++ b/code/CMakeLists.txt @@ -163,6 +163,8 @@ set(BGFX_ROOT "${CMAKE_SOURCE_DIR}/thirdparty/bgfx.cmake/bgfx") set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/bgfxbackend.cpp" PROPERTIES INCLUDE_DIRECTORIES "${BGFX_ROOT}/include;${CMAKE_SOURCE_DIR}/thirdparty/bgfx.cmake/bx/include;${BGFX_ROOT}/examples/common/imgui" + COMPILE_DEFINITIONS + "BX_CONFIG_DEBUG=$,1,$>" COMPILE_OPTIONS "/Zc:preprocessor" ) diff --git a/code/bgfxbackend.cpp b/code/bgfxbackend.cpp index 2645ede6..3dc92567 100644 --- a/code/bgfxbackend.cpp +++ b/code/bgfxbackend.cpp @@ -15,15 +15,18 @@ #include "dbgprint.h" #include "except.h" +#include #include #include #include #include +#include #include #include #include +#include static const bgfx::EmbeddedShader _EmbeddedShaders[] = { @@ -119,6 +122,30 @@ class BackendCallback : public bgfx::CallbackI static BackendCallback _Callback; +// bgfx contains cache-line-aligned render records but requests their backing arrays with +// the allocator's default alignment. The Win32 CRT only guarantees eight-byte alignment, +// which is insufficient when clang-cl copies those records with aligned SSE instructions. +class BackendAllocator : public bx::AllocatorI +{ + public: + virtual ~BackendAllocator(void) override {} + + virtual void * realloc(void * ptr, size_t size, size_t alignment, const char *, uint32_t) override + { + if (size == 0) { + _aligned_free(ptr); + return(NULL); + } + + const size_t cachelinealignment = BX_CACHE_LINE_SIZE; + alignment = std::max(alignment, cachelinealignment); + return(_aligned_realloc(ptr, size, alignment)); + } +}; + +static BackendAllocator _Allocator; + + /// /// Builds the table that widens a 565 pixel to the 32 bit color the fallback path uploads. /// @@ -273,6 +300,7 @@ bool Backend_Init(HWND window, int windowwidth, int windowheight, BackendRendere init.resolution.height = (uint32_t)windowheight; init.resolution.reset = _ResetFlags; init.callback = &_Callback; + init.allocator = &_Allocator; switch (renderer) { case BACKEND_RENDERER_D3D11: