diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e634b61f81..ced9a18bc4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -81,7 +81,7 @@ jobs: - run: cmake --install build --prefix build/install android: - runs-on: macos-latest + runs-on: ubuntu-latest if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name steps: - uses: actions/checkout@v7 diff --git a/CMakeLists.txt b/CMakeLists.txt index 13d1e0c535..d68d61c499 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,7 +47,7 @@ set(CMAKE_VISIBILITY_INLINES_HIDDEN "YES") include(GNUInstallDirs) -set_property(GLOBAL PROPERTY USE_FOLDERS ON) +set_property(GLOBAL PROPERTY USE_FOLDERS ON) # Remove when CMake min is 3.26 option(BUILD_WERROR "Treat compiler warnings as errors") if (BUILD_WERROR) @@ -94,34 +94,15 @@ if (MSVC) add_link_options("$<$:/DEBUG:FULL>") endif() -if (CMAKE_SYSTEM_NAME MATCHES "Windows|Linux|BSD") +option(BUILD_APIDUMP "Build api_dump layer" ON) +option(BUILD_MONITOR "Build monitor layer" ON) +option(BUILD_SCREENSHOT "Build screenshot layer" ON) - option(BUILD_APIDUMP "Build api_dump layer" ON) - option(BUILD_MONITOR "Build monitor layer" ON) - option(BUILD_SCREENSHOT "Build screenshot layer" ON) +if (CMAKE_SYSTEM_NAME MATCHES "Windows|Linux|BSD|Darwin") option(BUILD_LAYERMGR "Build Vulkan Configurator" ON) - set(SDK_VERSION "" CACHE STRING "Vulkan SDK version") - -elseif(ANDROID) - - # Currently the Android build only build the API dump and screen shot layer. - # - libVkLayer_api_dump.so - # - libVkLayer_screenshot.so - option(BUILD_APIDUMP "Build api_dump layer" ON) - option(BUILD_SCREENSHOT "Build screenshot layer" ON) - set(BUILD_MONITOR OFF) +else() + message(DEBUG "VkConfig only supported on desktop platforms") set(BUILD_LAYERMGR OFF) - -elseif (APPLE) - - option(BUILD_APIDUMP "Build api_dump layer" ON) - option(BUILD_SCREENSHOT "Build screenshot layer" ON) - set(BUILD_MONITOR OFF) - - if (CMAKE_SYSTEM_NAME STREQUAL "Darwin") - option(BUILD_LAYERMGR "Build Vulkan Configurator" ON) - endif() - endif() if(BUILD_TESTS) @@ -129,11 +110,14 @@ if(BUILD_TESTS) endif() if(BUILD_APIDUMP OR BUILD_MONITOR OR BUILD_SCREENSHOT) - message(STATUS "INFO: Building Vulkan Layers") add_subdirectory(layersvt) endif() if(BUILD_LAYERMGR) + # Provided when building SDK to get the Vulkan SDK version for the Vulkan Configurator + # Useful metadata to have for the Vulkan Configurator build + set(SDK_VERSION "" CACHE STRING "Vulkan SDK version") + if(NOT Qt6_FOUND) message("WARNING: Vulkan Configurator will be excluded from the build because Qt6 was not found. Please add Qt6 into the PATH environment variable") else() diff --git a/layersvt/CMakeLists.txt b/layersvt/CMakeLists.txt index 43d24d685b..7c7fe0c48d 100644 --- a/layersvt/CMakeLists.txt +++ b/layersvt/CMakeLists.txt @@ -1,6 +1,8 @@ file(GLOB IMAGES "${PROJECT_SOURCE_DIR}/layersvt/images/*") file(COPY ${IMAGES} DESTINATION ${CMAKE_BINARY_DIR}/layersvt/images) +set(CMAKE_FOLDER "${CMAKE_FOLDER}/layers") + if(WIN32) add_compile_definitions(VK_USE_PLATFORM_WIN32_KHR) # Minimize what Windows.h leaks @@ -43,18 +45,23 @@ else() add_compile_options(-Wpointer-arith) endif() +# Vulkan Layers are typically built as MODULEs, except on iOS where they are SHARED libraries +# From the CMake docs: "A Module Library: a plugin that may not be linked by other targets, but may be dynamically loaded at runtime using dlopen-like functionality." +# This exactly describes a Vulkan layer. In particular, it is a plugin that is dynamically loaded by the Vulkan loader at runtime and is not linked by other targets. +# On WIN32 when installing the layers specifying libraries as MODULE avoids installing the import library (.lib) that would be generated for SHARED libraries. +set(VK_LAYER_TYPE "MODULE") +if (IOS) + # "Apples App store rules require dynamic libraries be packaged as Frameworks for iOS. + # This requirement is not applied for macOS, so all iOS libraries should be packaged as Frameworks moving forward to comply with Apples policy." + set(VK_LAYER_TYPE "SHARED") +endif() + if(BUILD_APIDUMP) find_package(Python3 REQUIRED) set(VULKAN_REGISTRY "${VULKAN_HEADERS_INSTALL_DIR}/${CMAKE_INSTALL_DATADIR}/vulkan/registry") - if(IOS) - add_library(VkLayer_api_dump SHARED) - else() - add_library(VkLayer_api_dump MODULE) - endif() - set_target_properties(VkLayer_api_dump PROPERTIES FOLDER "layers/api_dump") - + add_library(VkLayer_api_dump "${VK_LAYER_TYPE}") target_sources(VkLayer_api_dump PRIVATE api_dump_handwritten_dispatch.cpp generated/api_dump_dispatch.h @@ -91,20 +98,47 @@ if(BUILD_APIDUMP) endif () if(BUILD_MONITOR) - add_library(VkLayer_monitor MODULE) - set_target_properties(VkLayer_monitor PROPERTIES FOLDER "layers/monitor") - target_sources(VkLayer_monitor PRIVATE - monitor.cpp + # Everything but the exported entry points, so the unit tests can link it too + add_library(VkLayer_monitor_core STATIC) + target_sources(VkLayer_monitor_core PRIVATE + monitor_layer.cpp + monitor_layer.h + monitor_overlay.cpp + monitor_overlay.h + monitor_overlay_shaders.h + monitor_present.cpp + monitor_present.h + monitor_renderer.cpp + monitor_renderer.h + monitor_settings.cpp + monitor_settings.h + shaders/monitor_overlay.vert + shaders/monitor_overlay.frag vk_layer_table.cpp vk_layer_table.h + ) + target_include_directories(VkLayer_monitor_core PUBLIC .) + target_link_libraries(VkLayer_monitor_core PUBLIC Vulkan::Headers Vulkan::UtilityHeaders Vulkan::LayerSettings) + if (ANDROID) + target_link_libraries(VkLayer_monitor_core PUBLIC log) + endif() + # The dispatch table's layout depends on the VK_USE_PLATFORM_* definitions above, so code linking the core, like the + # unit tests in tests/monitor, has to be compiled with the same ones + get_directory_property(LAYER_COMPILE_DEFINITIONS COMPILE_DEFINITIONS) + target_compile_definitions(VkLayer_monitor_core INTERFACE ${LAYER_COMPILE_DEFINITIONS}) + # The monitor layer itself remains small with only the exported entry points, while the core functionality is in the static library. + # This separation allows the core functionality to be reused by unit tests and other components without requiring the full layer to be linked. + add_library(VkLayer_monitor "${VK_LAYER_TYPE}") + target_sources(VkLayer_monitor PRIVATE + monitor.cpp monitor_layer.md json/VkLayer_monitor.json.in ) + target_link_libraries(VkLayer_monitor PRIVATE VkLayer_monitor_core) endif () if(BUILD_SCREENSHOT) - add_library(VkLayer_screenshot MODULE) - set_target_properties(VkLayer_screenshot PROPERTIES FOLDER "layers/screenshot") + add_library(VkLayer_screenshot "${VK_LAYER_TYPE}") target_sources(VkLayer_screenshot PRIVATE screenshot.cpp screenshot_parsing.cpp @@ -126,6 +160,8 @@ foreach(layer ${TOOL_LAYERS}) continue() endif() + message(DEBUG "Configuring Vulkan layer ${layer}") + target_link_Libraries(${layer} PRIVATE Vulkan::Headers Vulkan::UtilityHeaders Vulkan::LayerSettings) if (ANDROID) @@ -144,10 +180,10 @@ foreach(layer ${TOOL_LAYERS}) # IOS and APPLE can both be true (FYI) if(IOS) set_target_properties(${layer} PROPERTIES - FRAMEWORK TRUE - MACOSX_FRAMEWORK_BUNDLE_VERSION "${VulkanHeaders_VERSION}" + FRAMEWORK TRUE + MACOSX_FRAMEWORK_BUNDLE_VERSION "${VulkanHeaders_VERSION}" MACOSX_FRAMEWORK_SHORT_VERSION_STRING "${VulkanHeaders_VERSION}" - MACOSX_FRAMEWORK_IDENTIFIER com.khronos.${layer} + MACOSX_FRAMEWORK_IDENTIFIER com.khronos.${layer} ) else() set_target_properties(${layer} PROPERTIES SUFFIX ".dylib") diff --git a/layersvt/README.md b/layersvt/README.md index c171692d68..eb359ab7c0 100644 --- a/layersvt/README.md +++ b/layersvt/README.md @@ -30,24 +30,20 @@ Note that some layers are code-generated and will therefore exist in the directo layersvt/screenshot.cpp (name='VK_LAYER_LUNARG_screenshot') - utility layer used to capture and save screenshots of running applications. To specify frames to be captured, the environment variable 'VK_SCREENSHOT_FRAMES' can be set to a comma-separated list of frame numbers (ex: 4,8,15,16,23,42). -### View Frames Per Second -layersvt/monitor.cpp - utility layer that will display an applications FPS in the title bar of a windowed application. +### Monitor Frames Per Second +layersvt/monitor.cpp - utility layer that draws an application's FPS, frame time and frame number on top of the images it presents. ## Using Layers 1. Build VK loader using normal steps (cmake and make) -2. Place libVkLayer_.so or VkLayer_.dll in the same directory as your Vulkan test or application, or use the VK\_LAYER\_PATH environment variable to specify where the layer libraries reside. +2. Place `libVkLayer_.so` or `VkLayer_.dll` in the same directory as your Vulkan test or application, or use the `VK_LAYER_PATH` environment variable to specify where the layer libraries reside. 3. Create a vk_layer_settings.txt file in the same directory to specify how your layers should behave. Model it after the following example: [*vk_layer_settings.txt*](vk_layer_settings.txt) -4. Specify which Layers to activate by using -vkCreateDevice and/or vkCreateInstance or environment variables. +4. Specify which Layers to activate by using vkCreateDevice and/or vkCreateInstance or environment variables. - export VK\_INSTANCE\_LAYERS=VK_LAYER_LUNARG_api_dump - cd build/tests; ./vkinfo - -## Status - - -### Current known issues +```sh +export VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump +vulkaninfo +``` diff --git a/layersvt/VKLayer_monitor.def b/layersvt/VKLayer_monitor.def index e6c0045c9c..080ce8ed10 100644 --- a/layersvt/VKLayer_monitor.def +++ b/layersvt/VKLayer_monitor.def @@ -21,4 +21,8 @@ LIBRARY VkLayer_monitor EXPORTS vkGetInstanceProcAddr vkGetDeviceProcAddr +vkEnumerateInstanceLayerProperties +vkEnumerateDeviceLayerProperties +vkEnumerateInstanceExtensionProperties +vkEnumerateDeviceExtensionProperties diff --git a/layersvt/api_dump.h b/layersvt/api_dump.h index 8456e4ff67..e850d68ab9 100644 --- a/layersvt/api_dump.h +++ b/layersvt/api_dump.h @@ -79,8 +79,12 @@ #if defined(_WIN32) // Used by GetCurrentProcessName. NOMINMAX avoids windows.h's min/max macros shadowing std::min/max, // used throughout this header. +#ifndef NOMINMAX #define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN +#endif #include #endif diff --git a/layersvt/json/VkLayer_monitor.json.in b/layersvt/json/VkLayer_monitor.json.in index c8c716f091..82f2247502 100644 --- a/layersvt/json/VkLayer_monitor.json.in +++ b/layersvt/json/VkLayer_monitor.json.in @@ -5,11 +5,11 @@ "type": "GLOBAL", "library_path": "@JSON_LIBRARY_PATH@", "api_version": "@JSON_VERSION@", - "implementation_version": "1", + "implementation_version": "2", "description": "Execution Monitoring Layer", - "introduction": "The monitor utility layer displays the real-time frame rate in frames-per-second in the application's title bar.", + "introduction": "The monitor utility layer draws the frame rate, frame time and frame number on top of the images the application presents.", "url": "https://vulkan.lunarg.com/doc/sdk/latest/windows/monitor_layer.html", - "platforms": [ "WINDOWS", "LINUX" ], + "platforms": [ "WINDOWS", "LINUX", "MACOS", "ANDROID" ], "instance_extensions": [ { "name": "VK_EXT_layer_settings", @@ -24,6 +24,90 @@ "vkGetPhysicalDeviceToolPropertiesEXT" ] } - ] + ], + "features": { + "settings": [ + { + "key": "position", + "label": "Position", + "description": "Corner of the presented image the overlay is drawn in.", + "type": "ENUM", + "flags": [ + { + "key": "TOP_LEFT", + "label": "Top Left", + "description": "Draw the overlay in the top left corner." + }, + { + "key": "TOP_RIGHT", + "label": "Top Right", + "description": "Draw the overlay in the top right corner." + }, + { + "key": "BOTTOM_LEFT", + "label": "Bottom Left", + "description": "Draw the overlay in the bottom left corner." + }, + { + "key": "BOTTOM_RIGHT", + "label": "Bottom Right", + "description": "Draw the overlay in the bottom right corner." + } + ], + "default": "TOP_LEFT" + }, + { + "key": "scale", + "label": "Scale", + "description": "Size of the overlay text, as a percentage of the default size. The default size grows with the resolution of the presented images. Text is drawn in whole pixels, so the size changes in steps.", + "type": "INT", + "default": 100, + "range": { + "min": 50, + "max": 400 + }, + "unit": "%" + }, + { + "key": "update_interval_ms", + "label": "Update Interval", + "description": "How often the frame rate and frame times are updated. The frame number is updated every frame.", + "type": "INT", + "default": 500, + "range": { + "min": 50 + }, + "unit": "ms" + }, + { + "key": "show_fps", + "label": "Show Frame Rate", + "description": "Show the frame rate in frames per second.", + "type": "BOOL", + "default": true + }, + { + "key": "show_frame_time", + "label": "Show Frame Time", + "description": "Show the average frame time in milliseconds, with the shortest and longest frame time.", + "type": "BOOL", + "default": true + }, + { + "key": "show_frame_number", + "label": "Show Frame Number", + "description": "Show the number of the frame being presented. Frame 0 is the first presented image.", + "type": "BOOL", + "default": true + }, + { + "key": "log_warnings", + "label": "Log Warnings", + "description": "Print why the overlay isn't shown on some swapchains, once per reason.", + "type": "BOOL", + "default": false + } + ] + } } } diff --git a/layersvt/monitor.cpp b/layersvt/monitor.cpp index 332912754c..6facba604c 100644 --- a/layersvt/monitor.cpp +++ b/layersvt/monitor.cpp @@ -1,8 +1,6 @@ /* - * Vulkan - * * Copyright (C) 2016-2022 Valve Corporation - * Copyright (C) 2016-2022 LunarG, Inc. + * Copyright (C) 2016-2026 LunarG, Inc. * Copyright (C) 2016-2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,363 +14,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - * Author: Chris Forbes - * Author: Tony Barbour */ -#include "vk_layer_table.h" -#include -#include -#include -#include -#include -#include - -#include - -#if defined(__linux__) -#include -#endif - -#if (!defined(VK_USE_PLATFORM_XCB_KHR) && !defined(VK_USE_PLATFORM_WIN32_KHR)) -#warning "Monitor layer only has code for XCB and Windows at this time" -#endif - -#if defined(_WIN32) && !defined(NDEBUG) -#include -#endif - -#define TITLE_LENGTH 1000 -#define FPS_LENGTH 24 -struct monitor_layer_data { - VkuDeviceDispatchTable *device_dispatch_table{}; - VkuInstanceDispatchTable *instance_dispatch_table{}; - - PFN_vkQueuePresentKHR pfnQueuePresentKHR{}; -#if defined(VK_USE_PLATFORM_WIN32_KHR) - HWND hwnd{}; -#elif defined(VK_USE_PLATFORM_XCB_KHR) - xcb_connection_t *connection{}; - xcb_window_t xcb_window{}; - bool xcb_fps{}; -#endif - char base_title[TITLE_LENGTH]{}; - bool got_title = false; - VkPhysicalDevice gpu{}; - VkDevice device{}; - - PFN_vkSetDeviceLoaderData pfn_dev_init{}; - int lastFrame{}; - time_t lastTime{}; - float fps{}; - int frame{}; -}; - -#if defined(VK_USE_PLATFORM_XCB_KHR) -static struct { - void *xcbLib{}; - decltype(xcb_change_property) *change_property{}; - decltype(xcb_flush) *flush{}; - decltype(xcb_get_property) *get_property{}; - decltype(xcb_get_property_reply) *get_property_reply{}; - decltype(xcb_get_property_value_length) *get_property_value_length{}; - decltype(xcb_get_property_value) *get_property_value{}; -} xcb = {NULL}; -#endif - -static std::unordered_map layer_instances; -static std::unordered_map layer_data_map; - -template monitor_layer_data *GetLayerDataPtr(void *data_key, - std::unordered_map &data_map); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo, - const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) { - VkLayerDeviceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO); - - assert(chain_info->u.pLayerInfo); - PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; - PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr; - PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(layer_instances.at(gpu), "vkCreateDevice"); - if (fpCreateDevice == NULL) { - return VK_ERROR_INITIALIZATION_FAILED; - } - - // Advance the link info for the next element on the chain - chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; - - VkResult result = fpCreateDevice(gpu, pCreateInfo, pAllocator, pDevice); - if (result != VK_SUCCESS) { - return result; - } - - monitor_layer_data *my_device_data = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map); - - // Setup device dispatch table - my_device_data->device_dispatch_table = new VkuDeviceDispatchTable; - vkuInitDeviceDispatchTable(*pDevice, my_device_data->device_dispatch_table, fpGetDeviceProcAddr); - - // store the loader callback for initializing created dispatchable objects - chain_info = get_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK); - if (chain_info) { - my_device_data->pfn_dev_init = chain_info->u.pfnSetDeviceLoaderData; - } else { - my_device_data->pfn_dev_init = NULL; - } - - my_device_data->gpu = gpu; - my_device_data->device = *pDevice; - my_device_data->frame = 0; - my_device_data->lastFrame = 0; - my_device_data->fps = 0.0; - time(&my_device_data->lastTime); - - // Get our WSI hooks in - VkuDeviceDispatchTable *pTable = my_device_data->device_dispatch_table; - my_device_data->pfnQueuePresentKHR = (PFN_vkQueuePresentKHR)pTable->GetDeviceProcAddr(*pDevice, "vkQueuePresentKHR"); - - return result; -} - -VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDevices(VkInstance instance, uint32_t *pPhysicalDeviceCount, - VkPhysicalDevice *pPhysicalDevices) { - dispatch_key key = get_dispatch_key(instance); - monitor_layer_data *my_data = GetLayerDataPtr(key, layer_data_map); - VkuInstanceDispatchTable *pTable = my_data->instance_dispatch_table; - - VkResult result = pTable->EnumeratePhysicalDevices(instance, pPhysicalDeviceCount, pPhysicalDevices); - - if (pPhysicalDevices != nullptr) { - for (int i = 0; i < *pPhysicalDeviceCount; ++i) { - if (layer_instances.count(pPhysicalDevices[i]) == 0) { - layer_instances.insert({pPhysicalDevices[i], instance}); - } - } - } - - return result; -} - -VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDeviceGroups(VkInstance instance, uint32_t *pPhysicalDeviceGroupCount, - VkPhysicalDeviceGroupProperties *pPhysicalDeviceGroupProperties) { - dispatch_key key = get_dispatch_key(instance); - monitor_layer_data *my_data = GetLayerDataPtr(key, layer_data_map); - VkuInstanceDispatchTable *pTable = my_data->instance_dispatch_table; - - VkResult result = pTable->EnumeratePhysicalDeviceGroups(instance, pPhysicalDeviceGroupCount, pPhysicalDeviceGroupProperties); - - if (pPhysicalDeviceGroupProperties != nullptr) { - for (int i = 0; i < *pPhysicalDeviceGroupCount; ++i) { - for (int j = 0; j < pPhysicalDeviceGroupProperties[i].physicalDeviceCount; ++j) { - if (layer_instances.count(pPhysicalDeviceGroupProperties[i].physicalDevices[j]) == 0) { - layer_instances.insert({pPhysicalDeviceGroupProperties[i].physicalDevices[j], instance}); - } - } - } - } - - return result; -} - -VKAPI_ATTR void VKAPI_CALL vkDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) { - dispatch_key key = get_dispatch_key(device); - monitor_layer_data *my_data = GetLayerDataPtr(key, layer_data_map); - VkuDeviceDispatchTable *pTable = my_data->device_dispatch_table; - pTable->DeviceWaitIdle(device); - pTable->DestroyDevice(device, pAllocator); - delete pTable; - layer_data_map.erase(key); -} - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateInstance(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, - VkInstance *pInstance) { -#if defined(_WIN32) && defined(_CRTDBG_MODE_FILE) -#if !defined(NDEBUG) - _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); -#endif - // Avoid "Abort, Retry, Ignore" dialog boxes - _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); - SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); - _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); -#endif - VkLayerInstanceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO); +// The layer's exported entry points. Everything they call is in monitor_layer.cpp, so it can be unit tested. +#include "monitor_layer.h" - assert(chain_info->u.pLayerInfo); - PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; - PFN_vkCreateInstance fpCreateInstance = (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance"); - if (fpCreateInstance == NULL) { - return VK_ERROR_INITIALIZATION_FAILED; - } - - // Advance the link info for the next element on the chain - chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; - - VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance); - if (result != VK_SUCCESS) return result; - - monitor_layer_data *my_data = GetLayerDataPtr(get_dispatch_key(*pInstance), layer_data_map); - my_data->instance_dispatch_table = new VkuInstanceDispatchTable; - vkuInitInstanceDispatchTable(*pInstance, my_data->instance_dispatch_table, fpGetInstanceProcAddr); - -#if defined(VK_USE_PLATFORM_XCB_KHR) - // Initialize connection to null in case vkCreateXcbSurfaceKHR is never called - my_data->connection = nullptr; - // Load the xcb library and initialize xcb function pointers - if (!xcb.xcbLib) { - xcb.xcbLib = dlopen("libxcb.so", RTLD_NOW | RTLD_LOCAL); - if (xcb.xcbLib) { - xcb.change_property = reinterpret_cast(dlsym(xcb.xcbLib, "xcb_change_property")); - xcb.flush = reinterpret_cast(dlsym(xcb.xcbLib, "xcb_flush")); - xcb.get_property = reinterpret_cast(dlsym(xcb.xcbLib, "xcb_get_property")); - xcb.get_property_reply = - reinterpret_cast(dlsym(xcb.xcbLib, "xcb_get_property_reply")); - xcb.get_property_value_length = - reinterpret_cast(dlsym(xcb.xcbLib, "xcb_get_property_value_length")); - xcb.get_property_value = - reinterpret_cast(dlsym(xcb.xcbLib, "xcb_get_property_value")); - if (!xcb.change_property || !xcb.flush || !xcb.get_property || !xcb.get_property_reply || - !xcb.get_property_value_length || !xcb.get_property_value) { - // Something went wrong querying the entry points - set xcb.xdbLib to NULL - // to indicate we didn't successufly load libxcb.so - xcb.xcbLib = NULL; - } - } - } -#endif - - return result; -} - -VKAPI_ATTR void VKAPI_CALL vkDestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) { - dispatch_key key = get_dispatch_key(instance); - monitor_layer_data *my_data = GetLayerDataPtr(key, layer_data_map); - VkuInstanceDispatchTable *pTable = my_data->instance_dispatch_table; - pTable->DestroyInstance(instance, pAllocator); - delete pTable; - layer_data_map.erase(key); -} - -VKAPI_ATTR VkResult VKAPI_CALL vkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo) { - monitor_layer_data *my_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); - - time_t now; - time(&now); - float seconds = (float)difftime(now, my_data->lastTime); - - if (seconds > 0.5) { - char str[TITLE_LENGTH + FPS_LENGTH]; - char fpsstr[FPS_LENGTH]; - monitor_layer_data *my_instance_data = GetLayerDataPtr(get_dispatch_key(my_data->gpu), layer_data_map); - my_data->fps = (my_data->frame - my_data->lastFrame) / seconds; - my_data->lastFrame = my_data->frame; - my_data->lastTime = now; -#if defined(VK_USE_PLATFORM_WIN32_KHR) - if (IsWindow(my_instance_data->hwnd) && !my_instance_data->got_title) { - GetWindowText(my_instance_data->hwnd, my_instance_data->base_title, TITLE_LENGTH); - my_instance_data->got_title = true; - } -#endif - sprintf(fpsstr, " FPS = %.2f", my_data->fps); - strcpy(str, my_instance_data->base_title); - strcat(str, fpsstr); -#if defined(VK_USE_PLATFORM_WIN32_KHR) - if (IsWindow(my_instance_data->hwnd)) { - SetWindowText(my_instance_data->hwnd, str); - } -#elif defined(VK_USE_PLATFORM_XCB_KHR) - if (xcb.xcbLib && my_instance_data->xcb_fps && my_instance_data->connection) { - xcb.change_property(my_instance_data->connection, XCB_PROP_MODE_REPLACE, my_instance_data->xcb_window, XCB_ATOM_WM_NAME, - XCB_ATOM_STRING, 8, strlen(str), str); - xcb.flush(my_instance_data->connection); - } -#endif - } - my_data->frame++; - - VkResult result = my_data->pfnQueuePresentKHR(queue, pPresentInfo); - return result; -} - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceToolPropertiesEXT(VkPhysicalDevice physicalDevice, uint32_t *pToolCount, - VkPhysicalDeviceToolPropertiesEXT *pToolProperties) { - static const VkPhysicalDeviceToolPropertiesEXT monitor_layer_tool_props = { - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES_EXT, - nullptr, - "Monitor Layer", - "1", - VK_TOOL_PURPOSE_PROFILING_BIT_EXT | VK_TOOL_PURPOSE_ADDITIONAL_FEATURES_BIT_EXT, - "The VK_LAYER_LUNARG_monitor utility layer prints the real-time frames-per-second value to the application's title bar.", - "VK_LAYER_LUNARG_monitor"}; - - auto original_pToolProperties = pToolProperties; - if (pToolProperties != nullptr) { - *pToolProperties = monitor_layer_tool_props; - pToolProperties = ((*pToolCount > 1) ? &pToolProperties[1] : nullptr); - (*pToolCount)--; - } - - monitor_layer_data *my_data = GetLayerDataPtr(get_dispatch_key(physicalDevice), layer_data_map); - VkResult result = - my_data->instance_dispatch_table->GetPhysicalDeviceToolPropertiesEXT(physicalDevice, pToolCount, pToolProperties); - - if (original_pToolProperties != nullptr) { - pToolProperties = original_pToolProperties; - } - - (*pToolCount)++; - - return result; -} - -#if defined(VK_USE_PLATFORM_WIN32_KHR) -VKAPI_ATTR VkResult VKAPI_CALL vkCreateWin32SurfaceKHR(VkInstance instance, const VkWin32SurfaceCreateInfoKHR *pCreateInfo, - const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface) { - monitor_layer_data *my_data = GetLayerDataPtr(get_dispatch_key(instance), layer_data_map); - my_data->hwnd = pCreateInfo->hwnd; - - VkResult result = my_data->instance_dispatch_table->CreateWin32SurfaceKHR(instance, pCreateInfo, pAllocator, pSurface); - return result; -} -#elif defined(VK_USE_PLATFORM_XCB_KHR) -VKAPI_ATTR VkResult VKAPI_CALL vkCreateXcbSurfaceKHR(VkInstance instance, const VkXcbSurfaceCreateInfoKHR *pCreateInfo, - const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface) { - static bool xcbErrorPrinted = false; // Only print xcb error message once - xcb_get_property_cookie_t cookie; - xcb_get_property_reply_t *reply; - xcb_atom_t property = XCB_ATOM_WM_NAME; - xcb_atom_t type = XCB_ATOM_STRING; - - monitor_layer_data *my_data = GetLayerDataPtr(get_dispatch_key(instance), layer_data_map); - - if (!xcb.xcbLib and !xcbErrorPrinted) { - fprintf(stderr, "Monitor layer libxcb.so load failure, will not be able to display frame rate\n"); - xcbErrorPrinted = true; - } - if (xcb.xcbLib) { - my_data->xcb_window = pCreateInfo->window; - my_data->connection = pCreateInfo->connection; - cookie = xcb.get_property(my_data->connection, 0, my_data->xcb_window, property, type, 0, 0); - if ((reply = xcb.get_property_reply(my_data->connection, cookie, NULL))) { - my_data->xcb_fps = true; - int len = xcb.get_property_value_length(reply); - if (len > TITLE_LENGTH) { - my_data->xcb_fps = false; - } else if (len > 0) { - strcpy(my_data->base_title, (char *)xcb.get_property_value(reply)); - } else { - // No window title - make base title null string - my_data->base_title[0] = 0; - } - } - } - - VkResult result = my_data->instance_dispatch_table->CreateXcbSurfaceKHR(instance, pCreateInfo, pAllocator, pSurface); - return result; -} -#endif +#include #if defined(__GNUC__) && __GNUC__ >= 4 #define EXPORT_FUNCTION __attribute__((visibility("default"))) @@ -382,49 +29,31 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateXcbSurfaceKHR(VkInstance instance, const #define EXPORT_FUNCTION #endif -EXPORT_FUNCTION VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev, const char *funcName) { -#define ADD_HOOK(fn) \ - if (!strncmp(#fn, funcName, sizeof(#fn))) return (PFN_vkVoidFunction)fn +EXPORT_FUNCTION VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties(uint32_t *pCount, + VkLayerProperties *pProperties) { + return monitor::EnumerateInstanceLayerProperties(pCount, pProperties); +} - ADD_HOOK(vkGetDeviceProcAddr); - ADD_HOOK(vkDestroyDevice); - ADD_HOOK(vkQueuePresentKHR); -#undef ADD_HOOK +EXPORT_FUNCTION VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice, uint32_t *pCount, + VkLayerProperties *pProperties) { + return monitor::EnumerateDeviceLayerProperties(physicalDevice, pCount, pProperties); +} - if (dev == NULL) return NULL; +EXPORT_FUNCTION VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pCount, + VkExtensionProperties *pProperties) { + return monitor::EnumerateInstanceExtensionProperties(pLayerName, pCount, pProperties); +} - monitor_layer_data *dev_data; - dev_data = GetLayerDataPtr(get_dispatch_key(dev), layer_data_map); - VkuDeviceDispatchTable *pTable = dev_data->device_dispatch_table; +EXPORT_FUNCTION VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice, + const char *pLayerName, uint32_t *pCount, + VkExtensionProperties *pProperties) { + return monitor::EnumerateDeviceExtensionProperties(physicalDevice, pLayerName, pCount, pProperties); +} - if (pTable->GetDeviceProcAddr == NULL) return NULL; - return pTable->GetDeviceProcAddr(dev, funcName); +EXPORT_FUNCTION VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev, const char *funcName) { + return monitor::GetDeviceProcAddr(dev, funcName); } EXPORT_FUNCTION VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char *funcName) { -#define ADD_HOOK(fn) \ - if (!strncmp(#fn, funcName, sizeof(#fn))) return (PFN_vkVoidFunction)fn - - ADD_HOOK(vkCreateInstance); - ADD_HOOK(vkEnumeratePhysicalDevices); - ADD_HOOK(vkEnumeratePhysicalDeviceGroups); - ADD_HOOK(vkCreateDevice); - ADD_HOOK(vkDestroyInstance); - ADD_HOOK(vkGetInstanceProcAddr); - ADD_HOOK(vkGetPhysicalDeviceToolPropertiesEXT); -#if defined(VK_USE_PLATFORM_WIN32_KHR) - ADD_HOOK(vkCreateWin32SurfaceKHR); -#elif defined(VK_USE_PLATFORM_XCB_KHR) - ADD_HOOK(vkCreateXcbSurfaceKHR); -#endif -#undef ADD_HOOK - - if (instance == NULL) return NULL; - - monitor_layer_data *instance_data; - instance_data = GetLayerDataPtr(get_dispatch_key(instance), layer_data_map); - VkuInstanceDispatchTable *pTable = instance_data->instance_dispatch_table; - - if (pTable->GetInstanceProcAddr == NULL) return NULL; - return pTable->GetInstanceProcAddr(instance, funcName); + return monitor::GetInstanceProcAddr(instance, funcName); } diff --git a/layersvt/monitor_layer.cpp b/layersvt/monitor_layer.cpp new file mode 100644 index 0000000000..7e45240ca1 --- /dev/null +++ b/layersvt/monitor_layer.cpp @@ -0,0 +1,505 @@ +/* + * Vulkan + * + * Copyright (C) 2016-2022 Valve Corporation + * Copyright (C) 2016-2026 LunarG, Inc. + * Copyright (C) 2016-2022 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Author: Chris Forbes + * Author: Tony Barbour + */ +#include "monitor_layer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "monitor_overlay.h" +#include "monitor_present.h" +#include "monitor_settings.h" +#include "vk_layer_table.h" + +#ifdef __ANDROID__ +#include +#endif + +#if defined(_WIN32) && !defined(NDEBUG) +#include +#include // NOLINT(modernize-deprecated-headers): Microsoft declares _set_abort_behavior here +#endif + +namespace monitor { +namespace { + +struct LayerData { + std::unique_ptr device_dispatch_table; + std::unique_ptr instance_dispatch_table; + + VkInstance instance{}; + VkPhysicalDevice gpu{}; + + // Instance state for the overlay + std::atomic frame_counter{0}; + uint32_t api_version = VK_API_VERSION_1_0; // From VkApplicationInfo + MonitorSettings settings; + + // Device state for the overlay + LayerData *instance_data{}; + DeviceOverlay overlay; +}; + +// Loaders without layer manifests, such as Android's, find the layer through these +constexpr VkLayerProperties kLayerProperties = { + "VK_LAYER_LUNARG_monitor", + VK_HEADER_VERSION_COMPLETE, + 2, + "Execution Monitoring Layer", +}; +static_assert(kLayerName == kLayerProperties.layerName); + +constexpr std::array kInstanceExtensions = { + VkExtensionProperties{VK_EXT_LAYER_SETTINGS_EXTENSION_NAME, VK_EXT_LAYER_SETTINGS_SPEC_VERSION}, +}; + +// Must match the device_extensions of the layer manifest +constexpr std::array kDeviceExtensions = { + VkExtensionProperties{VK_EXT_TOOLING_INFO_EXTENSION_NAME, VK_EXT_TOOLING_INFO_SPEC_VERSION}, +}; + +// Instances and devices are created and destroyed from any thread, so the map is always locked. +std::mutex layer_data_lock; +// Constructed on first use, so a failed allocation happens in a Vulkan call rather than when the library loads +[[nodiscard]] std::unordered_map> &LayerDataMap() { + static std::unordered_map> map; + return map; +} + +// The data for `key`, added the first time the key is seen +[[nodiscard]] LayerData *GetLayerData(void *key) { + const std::scoped_lock lock(layer_data_lock); + std::unique_ptr &data = LayerDataMap()[key]; + if (!data) { + data = std::make_unique(); + } + return data.get(); +} + +// For entry points the loader can call outside the dispatch chain, with handles the layer may never have seen. +// Unlike GetLayerData, an unknown key returns null instead of adding data that nothing would free. +[[nodiscard]] LayerData *FindLayerData(void *key) { + const std::scoped_lock lock(layer_data_lock); + const auto it = LayerDataMap().find(key); + return it != LayerDataMap().end() ? it->second.get() : nullptr; +} + +void FreeLayerData(void *key) { + const std::scoped_lock lock(layer_data_lock); + LayerDataMap().erase(key); +} + +// Each distinct message is only shown once. Messages already shown cost a lookup, without allocating. The message only +// has to live for the call. +void WarnOnce(const char *message) { + static std::mutex lock; + static ShownMessages shown; + const std::scoped_lock guard(lock); + if (!FirstTimeShown(shown, message)) { + return; + } +#ifdef __ANDROID__ + __android_log_print(ANDROID_LOG_WARN, "VK_LAYER_LUNARG_monitor", "%s", message); +#else + (void)fprintf(stderr, "VK_LAYER_LUNARG_monitor: %s\n", message); +#endif +} + +[[nodiscard]] bool HasExtension(const VkDeviceCreateInfo &create_info, std::string_view name) { + for (uint32_t i = 0; i < create_info.enabledExtensionCount; ++i) { + if (create_info.ppEnabledExtensionNames[i] == name) { + return true; + } + } + return false; +} + +VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo, + const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) { + VkLayerDeviceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO); + + assert(chain_info->u.pLayerInfo); + PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; + PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr; + // Physical devices share their instance's dispatch key + LayerData *instance_data = GetLayerData(get_dispatch_key(gpu)); + auto fpCreateDevice = reinterpret_cast(fpGetInstanceProcAddr(instance_data->instance, "vkCreateDevice")); + if (fpCreateDevice == nullptr) { + return VK_ERROR_INITIALIZATION_FAILED; + } + + // Advance the link info for the next element on the chain + chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; + + const VkResult result = fpCreateDevice(gpu, pCreateInfo, pAllocator, pDevice); + if (result != VK_SUCCESS) { + return result; + } + + LayerData *my_device_data = GetLayerData(get_dispatch_key(*pDevice)); + + // Setup device dispatch table + my_device_data->device_dispatch_table = std::make_unique(); + vkuInitDeviceDispatchTable(*pDevice, my_device_data->device_dispatch_table.get(), fpGetDeviceProcAddr); + + // The loader callback gives the layer's command buffers their dispatch pointer + chain_info = get_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK); + my_device_data->overlay.set_loader_data = chain_info ? chain_info->u.pfnSetDeviceLoaderData : nullptr; + + my_device_data->gpu = gpu; + my_device_data->overlay.device = *pDevice; + my_device_data->instance_data = instance_data; + + VkPhysicalDeviceProperties properties = {}; + instance_data->instance_dispatch_table->GetPhysicalDeviceProperties(gpu, &properties); + const bool maintenance2 = HasExtension(*pCreateInfo, VK_KHR_MAINTENANCE_2_EXTENSION_NAME); + my_device_data->overlay.view_usage = ImageViewUsageAvailable(instance_data->api_version, properties.apiVersion, maintenance2); + + uint32_t family_count = 0; + instance_data->instance_dispatch_table->GetPhysicalDeviceQueueFamilyProperties(gpu, &family_count, nullptr); + my_device_data->overlay.queue_families.resize(family_count); + instance_data->instance_dispatch_table->GetPhysicalDeviceQueueFamilyProperties(gpu, &family_count, + my_device_data->overlay.queue_families.data()); + return result; +} + +VKAPI_ATTR void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) { + dispatch_key key = get_dispatch_key(device); + LayerData *my_data = GetLayerData(key); + const VkuDeviceDispatchTable &dispatch = *my_data->device_dispatch_table; + (void)dispatch.DeviceWaitIdle(device); + DestroyDeviceOverlay(dispatch, my_data->overlay); + dispatch.DestroyDevice(device, pAllocator); + // Also frees the dispatch table + FreeLayerData(key); +} + +VKAPI_ATTR VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, + VkInstance *pInstance) { +#if defined(_WIN32) && defined(_CRTDBG_MODE_FILE) +#ifndef NDEBUG + _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); +#endif + // Avoid "Abort, Retry, Ignore" dialog boxes + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); + _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); +#endif + + VkLayerInstanceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO); + + assert(chain_info->u.pLayerInfo); + PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr; + auto fpCreateInstance = reinterpret_cast(fpGetInstanceProcAddr(nullptr, "vkCreateInstance")); + if (fpCreateInstance == nullptr) { + return VK_ERROR_INITIALIZATION_FAILED; + } + + // Advance the link info for the next element on the chain + chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; + + const VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance); + if (result != VK_SUCCESS) { + return result; + } + + LayerData *my_data = GetLayerData(get_dispatch_key(*pInstance)); + my_data->instance = *pInstance; + if (pCreateInfo->pApplicationInfo && pCreateInfo->pApplicationInfo->apiVersion != 0) { + my_data->api_version = pCreateInfo->pApplicationInfo->apiVersion; + } + my_data->instance_dispatch_table = std::make_unique(); + vkuInitInstanceDispatchTable(*pInstance, my_data->instance_dispatch_table.get(), fpGetInstanceProcAddr); + + VkuLayerSettingSet layer_settings = VK_NULL_HANDLE; + (void)vkuCreateLayerSettingSet(kLayerProperties.layerName, vkuFindLayerSettingsCreateInfo(pCreateInfo), pAllocator, nullptr, + &layer_settings); + my_data->settings = ParseSettings(ReadRawSettings(layer_settings)); + vkuDestroyLayerSettingSet(layer_settings, pAllocator); + + return result; +} + +VKAPI_ATTR void VKAPI_CALL DestroyInstance(VkInstance instance, const VkAllocationCallbacks *pAllocator) { + dispatch_key key = get_dispatch_key(instance); + GetLayerData(key)->instance_dispatch_table->DestroyInstance(instance, pAllocator); + // Also frees the dispatch table + FreeLayerData(key); +} + +VKAPI_ATTR VkResult VKAPI_CALL QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo) { + LayerData *my_data = GetLayerData(get_dispatch_key(queue)); + LayerData *instance_data = my_data->instance_data; + const uint64_t frame_number = NextFrameNumber(instance_data->frame_counter); + const auto now = std::chrono::steady_clock::now(); + return PresentWithOverlay(*my_data->device_dispatch_table, my_data->overlay, queue, *pPresentInfo, instance_data->settings, + frame_number, now, WarnIf(instance_data->settings.log_warnings, WarnOnce)); +} + +VKAPI_ATTR VkResult VKAPI_CALL GetPhysicalDeviceToolPropertiesEXT(VkPhysicalDevice physicalDevice, uint32_t *pToolCount, + VkPhysicalDeviceToolPropertiesEXT *pToolProperties) { + constexpr VkPhysicalDeviceToolPropertiesEXT kTool = { + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES_EXT, + nullptr, + "Monitor Layer", + "2", + VK_TOOL_PURPOSE_PROFILING_BIT_EXT | VK_TOOL_PURPOSE_ADDITIONAL_FEATURES_BIT_EXT, + "The VK_LAYER_LUNARG_monitor utility layer draws the frame rate, frame time and frame number on top of the presented " + "images.", + "VK_LAYER_LUNARG_monitor"}; + + const LayerData *my_data = GetLayerData(get_dispatch_key(physicalDevice)); + return PrependToolProperties(kTool, physicalDevice, my_data->instance_dispatch_table->GetPhysicalDeviceToolPropertiesEXT, + pToolCount, pToolProperties); +} + +VKAPI_ATTR void VKAPI_CALL GetDeviceQueue(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue *pQueue) { + LayerData *my_data = GetLayerData(get_dispatch_key(device)); + my_data->device_dispatch_table->GetDeviceQueue(device, queueFamilyIndex, queueIndex, pQueue); + + const std::scoped_lock lock(my_data->overlay.lock); + my_data->overlay.queue_family_index[*pQueue] = queueFamilyIndex; +} + +VKAPI_ATTR void VKAPI_CALL GetDeviceQueue2(VkDevice device, const VkDeviceQueueInfo2 *pQueueInfo, VkQueue *pQueue) { + LayerData *my_data = GetLayerData(get_dispatch_key(device)); + my_data->device_dispatch_table->GetDeviceQueue2(device, pQueueInfo, pQueue); + + const std::scoped_lock lock(my_data->overlay.lock); + my_data->overlay.queue_family_index[*pQueue] = pQueueInfo->queueFamilyIndex; +} + +VKAPI_ATTR VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo, + const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchain) { + LayerData *my_data = GetLayerData(get_dispatch_key(device)); + const VkuDeviceDispatchTable &dispatch = *my_data->device_dispatch_table; + + // The overlay renders into the swapchain images, so they need to be color attachments + const SwapchainPatch patch = PatchSwapchainCreateInfo(*pCreateInfo, my_data->instance_data->settings.lines); + const VkResult result = dispatch.CreateSwapchainKHR(device, &patch.create_info, pAllocator, pSwapchain); + if (result != VK_SUCCESS) { + return result; + } + + VkFormatProperties format_properties = {}; + my_data->instance_data->instance_dispatch_table->GetPhysicalDeviceFormatProperties(my_data->gpu, patch.create_info.imageFormat, + &format_properties); + const bool blend = (format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) != 0; + + const char *reason = AddSwapchainOverlay(dispatch, my_data->overlay, *pSwapchain, patch, blend); + // Checked here rather than with WarnIf, so the message is only built when it's shown + if (reason && my_data->instance_data->settings.log_warnings) { + WarnOnce((std::string("no overlay on some swapchains, ") + reason).c_str()); + } + return result; +} + +VKAPI_ATTR void VKAPI_CALL DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks *pAllocator) { + LayerData *my_data = GetLayerData(get_dispatch_key(device)); + const VkuDeviceDispatchTable &dispatch = *my_data->device_dispatch_table; + const std::unique_ptr overlay = ForgetSwapchain(dispatch, my_data->overlay, swapchain); + dispatch.DestroySwapchainKHR(device, swapchain, pAllocator); + if (overlay) { + DestroySwapchainOverlay(my_data->overlay.device, dispatch, *overlay); + } +} + +VKAPI_ATTR VkResult VKAPI_CALL CreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount, + const VkSwapchainCreateInfoKHR *pCreateInfos, + const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchains) { + const LayerData *my_data = GetLayerData(get_dispatch_key(device)); + if (const char *warning = SharedSwapchainsWarning(my_data->instance_data->settings.lines)) { + WarnIf(my_data->instance_data->settings.log_warnings, WarnOnce)(warning); + } + return my_data->device_dispatch_table->CreateSharedSwapchainsKHR(device, swapchainCount, pCreateInfos, pAllocator, pSwapchains); +} + +template +[[nodiscard]] PFN_vkVoidFunction ToVoidFunction(Function *function) { + return reinterpret_cast(function); +} + +struct Hook { + std::string_view name; + PFN_vkVoidFunction function; +}; + +[[nodiscard]] PFN_vkVoidFunction Find(std::initializer_list hooks, std::string_view name) { + for (const Hook &hook : hooks) { + if (hook.name == name) { + return hook.function; + } + } + return nullptr; +} + +} // namespace + +VkResult PrependToolProperties(const VkPhysicalDeviceToolPropertiesEXT &tool, VkPhysicalDevice physical_device, + PFN_vkGetPhysicalDeviceToolPropertiesEXT next, uint32_t *pToolCount, + VkPhysicalDeviceToolPropertiesEXT *pToolProperties) { + uint32_t next_count = 0; + if (pToolProperties == nullptr) { + const VkResult result = next ? next(physical_device, &next_count, nullptr) : VK_SUCCESS; + *pToolCount = next_count + 1; + return result; + } + if (*pToolCount == 0) { + return VK_INCOMPLETE; + } + + pToolProperties[0] = tool; + VkResult result = VK_SUCCESS; + if (next && *pToolCount > 1) { + next_count = *pToolCount - 1; + result = next(physical_device, &next_count, &pToolProperties[1]); + } else if (next) { + // No room for the next tools, so only find out whether there are any + result = next(physical_device, &next_count, nullptr); + if (result == VK_SUCCESS && next_count > 0) { + result = VK_INCOMPLETE; + } + next_count = 0; + } + *pToolCount = next_count + 1; + return result; +} + +PFN_vkVoidFunction FindInstanceHook(std::string_view name) { + return Find( + { + {"vkCreateInstance", ToVoidFunction(CreateInstance)}, + {"vkCreateDevice", ToVoidFunction(CreateDevice)}, + {"vkDestroyInstance", ToVoidFunction(DestroyInstance)}, + {"vkGetInstanceProcAddr", ToVoidFunction(GetInstanceProcAddr)}, + {"vkGetPhysicalDeviceToolPropertiesEXT", ToVoidFunction(GetPhysicalDeviceToolPropertiesEXT)}, + {"vkEnumerateInstanceLayerProperties", ToVoidFunction(EnumerateInstanceLayerProperties)}, + {"vkEnumerateDeviceLayerProperties", ToVoidFunction(EnumerateDeviceLayerProperties)}, + {"vkEnumerateInstanceExtensionProperties", ToVoidFunction(EnumerateInstanceExtensionProperties)}, + {"vkEnumerateDeviceExtensionProperties", ToVoidFunction(EnumerateDeviceExtensionProperties)}, + }, + name); +} + +PFN_vkVoidFunction FindDeviceHook(std::string_view name, bool next_supported) { + const PFN_vkVoidFunction core = Find( + { + {"vkGetDeviceProcAddr", ToVoidFunction(GetDeviceProcAddr)}, + {"vkDestroyDevice", ToVoidFunction(DestroyDevice)}, + {"vkGetDeviceQueue", ToVoidFunction(GetDeviceQueue)}, + }, + name); + if (core || !next_supported) { + return core; + } + return Find( + { + {"vkGetDeviceQueue2", ToVoidFunction(GetDeviceQueue2)}, + {"vkQueuePresentKHR", ToVoidFunction(QueuePresentKHR)}, + {"vkCreateSwapchainKHR", ToVoidFunction(CreateSwapchainKHR)}, + {"vkDestroySwapchainKHR", ToVoidFunction(DestroySwapchainKHR)}, + {"vkCreateSharedSwapchainsKHR", ToVoidFunction(CreateSharedSwapchainsKHR)}, + }, + name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance, const char *pName) { + if (const PFN_vkVoidFunction hook = FindInstanceHook(pName)) { + return hook; + } + if (instance == VK_NULL_HANDLE) { + return nullptr; + } + const VkuInstanceDispatchTable &dispatch = *GetLayerData(get_dispatch_key(instance))->instance_dispatch_table; + if (dispatch.GetInstanceProcAddr == nullptr) { + return nullptr; + } + return dispatch.GetInstanceProcAddr(instance, pName); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice device, const char *pName) { + if (const PFN_vkVoidFunction hook = FindDeviceHook(pName, false)) { + return hook; + } + if (device == VK_NULL_HANDLE) { + return nullptr; + } + const VkuDeviceDispatchTable &dispatch = *GetLayerData(get_dispatch_key(device))->device_dispatch_table; + if (dispatch.GetDeviceProcAddr == nullptr) { + return nullptr; + } + const PFN_vkVoidFunction next = dispatch.GetDeviceProcAddr(device, pName); + if (const PFN_vkVoidFunction hook = FindDeviceHook(pName, next != nullptr)) { + return hook; + } + return next; +} + +VKAPI_ATTR VkResult VKAPI_CALL EnumerateInstanceLayerProperties(uint32_t *pPropertyCount, VkLayerProperties *pProperties) { + return util_GetLayerProperties(1, &kLayerProperties, pPropertyCount, pProperties); +} + +VKAPI_ATTR VkResult VKAPI_CALL EnumerateDeviceLayerProperties(VkPhysicalDevice /*physicalDevice*/, uint32_t *pPropertyCount, + VkLayerProperties *pProperties) { + return util_GetLayerProperties(1, &kLayerProperties, pPropertyCount, pProperties); +} + +VKAPI_ATTR VkResult VKAPI_CALL EnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pPropertyCount, + VkExtensionProperties *pProperties) { + if (pLayerName && pLayerName == kLayerName) { + return util_GetExtensionProperties(static_cast(kInstanceExtensions.size()), kInstanceExtensions.data(), + pPropertyCount, pProperties); + } + return VK_ERROR_LAYER_NOT_PRESENT; +} + +VKAPI_ATTR VkResult VKAPI_CALL EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice, const char *pLayerName, + uint32_t *pPropertyCount, VkExtensionProperties *pProperties) { + if (pLayerName && pLayerName == kLayerName) { + return util_GetExtensionProperties(static_cast(kDeviceExtensions.size()), kDeviceExtensions.data(), + pPropertyCount, pProperties); + } + if (physicalDevice == VK_NULL_HANDLE) { + return VK_ERROR_LAYER_NOT_PRESENT; + } + const LayerData *my_data = FindLayerData(get_dispatch_key(physicalDevice)); + if (!my_data || !my_data->instance_dispatch_table) { + return VK_ERROR_LAYER_NOT_PRESENT; + } + return my_data->instance_dispatch_table->EnumerateDeviceExtensionProperties(physicalDevice, pLayerName, pPropertyCount, + pProperties); +} + +} // namespace monitor diff --git a/layersvt/monitor_layer.h b/layersvt/monitor_layer.h new file mode 100644 index 0000000000..379613107d --- /dev/null +++ b/layersvt/monitor_layer.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include + +// The layer's Vulkan functions. The layer library only exports the entry points below; everything else is reached +// through them, and lives here so it can be unit tested. +namespace monitor { + +inline constexpr std::string_view kLayerName = "VK_LAYER_LUNARG_monitor"; + +// The layer's own function for `name`, or null if the layer doesn't hook it. +[[nodiscard]] PFN_vkVoidFunction FindInstanceHook(std::string_view name); + +// The same for device functions. Functions from extensions or newer versions are only hooked when `next_supported`, +// meaning the next layer or the driver has the function for this device. +[[nodiscard]] PFN_vkVoidFunction FindDeviceHook(std::string_view name, bool next_supported); + +// vkGetPhysicalDeviceToolPropertiesEXT for a layer that adds `tool` in front of the tools of `next`, which may be null. +[[nodiscard]] VkResult PrependToolProperties(const VkPhysicalDeviceToolPropertiesEXT &tool, VkPhysicalDevice physical_device, + PFN_vkGetPhysicalDeviceToolPropertiesEXT next, uint32_t *pToolCount, + VkPhysicalDeviceToolPropertiesEXT *pToolProperties); + +// The exported entry points +[[nodiscard]] VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetInstanceProcAddr(VkInstance instance, const char *pName); +[[nodiscard]] VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice device, const char *pName); +[[nodiscard]] VKAPI_ATTR VkResult VKAPI_CALL EnumerateInstanceLayerProperties(uint32_t *pPropertyCount, + VkLayerProperties *pProperties); +[[nodiscard]] VKAPI_ATTR VkResult VKAPI_CALL EnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice, + uint32_t *pPropertyCount, + VkLayerProperties *pProperties); +[[nodiscard]] VKAPI_ATTR VkResult VKAPI_CALL EnumerateInstanceExtensionProperties(const char *pLayerName, uint32_t *pPropertyCount, + VkExtensionProperties *pProperties); +[[nodiscard]] VKAPI_ATTR VkResult VKAPI_CALL EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice, + const char *pLayerName, uint32_t *pPropertyCount, + VkExtensionProperties *pProperties); + +} // namespace monitor diff --git a/layersvt/monitor_layer.md b/layersvt/monitor_layer.md index 781aa8c2ed..e934a6d13c 100644 --- a/layersvt/monitor_layer.md +++ b/layersvt/monitor_layer.md @@ -1,6 +1,6 @@

LunarG

-

Copyright © 2015-2022 LunarG, Inc.

+

Copyright © 2015-2026 LunarG, Inc.

[![Creative Commons][3]][4] @@ -8,11 +8,47 @@ [4]: https://creativecommons.org/licenses/by-nd/4.0/ # VK\_LAYER\_LUNARG\_monitor -The `VK_LAYER_LUNARG_monitor` utility layer displays the real-time frame rate in frames-per-second in the application's title bar. It is only compatible with the Win32 and XCB windowing systems and will not display the frame rate on other platforms. +The `VK_LAYER_LUNARG_monitor` utility layer draws a small overlay in the corner of every image the application presents, showing: + +- the frame rate in frames per second +- the average frame time in milliseconds, with the shortest and longest frame time in parentheses +- the frame number + +The overlay is drawn into the presented images, so it works in fullscreen and doesn't depend on the window system. The layer is available on Windows, Linux, macOS, iOS and Android, and the overlay stays upright on Android devices that pre-rotate the swapchain. + +The frame rate and frame times are measured between presents of each swapchain, and refresh twice a second by default. The frame number updates every frame: it starts at 0 for the first presented image and counts every `vkQueuePresentKHR` call of the `VkInstance`. For an overview of how to configure layers, refer to the [Layers Overview and Configuration](https://vulkan.lunarg.com/doc/sdk/latest/windows/layer_configuration.html) document. The Monitor Layer can be enabled using the [Vulkan Configurator](https://vulkan.lunarg.com/doc/sdk/latest/windows/vkconfig.html) included with the Vulkan SDK. -## Layer Options -The options for this layer are specified in VK_LAYER_LUNARG_monitor.json. The layer option details are in the [monitor layer documentation](https://vulkan.lunarg.com/doc/sdk/latest/windows/monitor_layer.html#user-content-layer-details). +## Layer Settings + +| Setting | Default | Description | +|---|---|---| +| `position` | `TOP_LEFT` | Corner the overlay is drawn in: `TOP_LEFT`, `TOP_RIGHT`, `BOTTOM_LEFT` or `BOTTOM_RIGHT`. | +| `scale` | `100` | Size of the overlay text as a percentage of the default size, from 50 to 400. The default size grows with the resolution of the presented images. | +| `update_interval_ms` | `500` | How often the frame rate and frame times are updated, at least 50. | +| `show_fps` | `true` | Show the frame rate. | +| `show_frame_time` | `true` | Show the frame times. | +| `show_frame_number` | `true` | Show the frame number. | +| `log_warnings` | `false` | Print why the overlay isn't shown on some swapchains, once per reason, to stderr or the Android log. | + +The settings can be set with the Vulkan Configurator, `vk_layer_settings.txt`, environment variables such as `VK_LUNARG_MONITOR_POSITION=BOTTOM_RIGHT`, or `VK_EXT_layer_settings`. The layer option details are in the [monitor layer documentation](https://vulkan.lunarg.com/doc/sdk/latest/windows/monitor_layer.html#user-content-layer-details). + +If every line is hidden, nothing is drawn and swapchains are created exactly as the application asks. + +## Limitations + +In these cases the frame rate isn't shown, and the application's frames are presented exactly as they would be without the layer: + +- Presents from a queue that can't do graphics work, such as a compute or transfer only queue. The overlay is drawn on the queue the application presents from. +- Swapchains with a shared present mode. The application and the display use the same image all the time, so there is no moment the overlay could be drawn without getting in the way. +- Protected swapchains. The layer can't draw into protected images. +- Swapchains created with `vkCreateSharedSwapchainsKHR`. + +With `VK_KHR_incremental_present`, the layer marks the whole image as changed so the overlay is updated. If `VkPresentRegionsKHR` comes after an extension struct the layer doesn't know in the `pNext` chain, it can't, and the overlay may only update where the application's rectangles cover it. + +Turn on `log_warnings` to have the layer say when any of these happens. + +To draw into the swapchain images, the layer adds `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` to the swapchain image usage. diff --git a/layersvt/monitor_overlay.cpp b/layersvt/monitor_overlay.cpp new file mode 100644 index 0000000000..0266f0c3fd --- /dev/null +++ b/layersvt/monitor_overlay.cpp @@ -0,0 +1,417 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "monitor_overlay.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace monitor { + +constexpr double kMillisecondsPerSecond = 1000.0; + +void RecordPresent(FrameStats &stats, std::chrono::steady_clock::time_point now, std::chrono::milliseconds interval) { + if (!stats.started) { + stats.started = true; + stats.last_present = now; + stats.interval_start = now; + return; + } + + const double frame_ms = std::chrono::duration(now - stats.last_present).count(); + stats.last_present = now; + + if (stats.frame_count == 0) { + stats.min_ms = frame_ms; + stats.max_ms = frame_ms; + } + stats.frame_count++; + stats.total_ms += frame_ms; + stats.min_ms = std::min(stats.min_ms, frame_ms); + stats.max_ms = std::max(stats.max_ms, frame_ms); + + if (now - stats.interval_start < interval || stats.total_ms <= 0.0) { + return; + } + + stats.snapshot.valid = true; + stats.snapshot.avg_ms = stats.total_ms / stats.frame_count; + stats.snapshot.fps = kMillisecondsPerSecond / stats.snapshot.avg_ms; + stats.snapshot.min_ms = stats.min_ms; + stats.snapshot.max_ms = stats.max_ms; + + stats.interval_start = now; + stats.frame_count = 0; + stats.total_ms = 0.0; +} + +uint64_t NextFrameNumber(std::atomic &counter) { return counter.fetch_add(1, std::memory_order_relaxed); } + +// Characters in glyph order, index 0 being the blank glyph. The font only has the characters the overlay prints: +// digits and punctuation for the numbers, "FPS", and the lowercase letters of "ms" and "Frame". +constexpr std::string_view kGlyphChars = " 0123456789.-()FPSaemrs"; +static_assert(kGlyphChars.size() == kGlyphCount); + +constexpr std::array, kGlyphCount> kFont = {{ + {0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000}, // ' ' + {0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110}, // '0' + {0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110}, // '1' + {0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111}, // '2' + {0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110}, // '3' + {0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010}, // '4' + {0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110}, // '5' + {0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110}, // '6' + {0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000}, // '7' + {0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110}, // '8' + {0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100}, // '9' + {0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100}, // '.' + {0b00000, 0b00000, 0b00000, 0b01110, 0b00000, 0b00000, 0b00000}, // '-' + {0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010}, // '(' + {0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000}, // ')' + {0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000}, // 'F' + {0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000}, // 'P' + {0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110}, // 'S' + {0b00000, 0b00000, 0b01110, 0b00001, 0b01111, 0b10001, 0b01111}, // 'a' + {0b00000, 0b00000, 0b01110, 0b10001, 0b11111, 0b10000, 0b01110}, // 'e' + {0b00000, 0b00000, 0b11010, 0b10101, 0b10101, 0b10001, 0b10001}, // 'm' + {0b00000, 0b00000, 0b10110, 0b11001, 0b10000, 0b10000, 0b10000}, // 'r' + {0b00000, 0b00000, 0b01111, 0b10000, 0b01110, 0b00001, 0b11110}, // 's' +}}; + +uint8_t GlyphIndex(char character) { + const size_t index = kGlyphChars.find(character); + return index == std::string_view::npos ? uint8_t{0} : static_cast(index); +} + +uint8_t GlyphRow(uint8_t glyph, int row) { + if (glyph >= kGlyphCount || row < 0 || row >= kGlyphHeight) { + return 0; + } + return kFont[glyph][static_cast(row)]; +} + +bool AnyLineVisible(const LineFlags &flags) { return flags.fps || flags.frame_time || flags.frame_number; } + +const char *SharedSwapchainsWarning(const LineFlags &flags) { + return AnyLineVisible(flags) ? "no overlay on swapchains from vkCreateSharedSwapchainsKHR" : nullptr; +} + +bool FirstTimeShown(ShownMessages &shown, std::string_view message) { + if (shown.find(message) != shown.end()) { + return false; + } + shown.emplace(message); + return true; +} + +void FormatOverlayLines(const StatsSnapshot &snapshot, uint64_t frame_number, const LineFlags &flags, + std::vector &lines) { + size_t count = 0; + const auto next_line = [&]() -> std::string & { + if (count == lines.size()) { + lines.emplace_back(); + } + return lines[count++]; + }; + // Longer than any line the overlay can show; snprintf truncates the rest + std::array text = {}; + + if (flags.fps) { + if (snapshot.valid) { + (void)snprintf(text.data(), text.size(), "FPS %.1f", snapshot.fps); + next_line().assign(text.data()); + } else { + next_line().assign("FPS -"); + } + } + if (flags.frame_time) { + if (snapshot.valid) { + const int length = + snprintf(text.data(), text.size(), "%.2f ms (%.2f-%.2f)", snapshot.avg_ms, snapshot.min_ms, snapshot.max_ms); + // After a very long frame, such as a debugger break, drop the decimals rather than cut off the longest time + if (length > static_cast(kMaxColumns)) { + (void)snprintf(text.data(), text.size(), "%.0f ms (%.0f-%.0f)", snapshot.avg_ms, snapshot.min_ms, snapshot.max_ms); + } + next_line().assign(text.data()); + } else { + next_line().assign("- ms"); + } + } + if (flags.frame_number) { + (void)snprintf(text.data(), text.size(), "Frame %llu", static_cast(frame_number)); + next_line().assign(text.data()); + } + lines.resize(count); +} + +std::vector FormatOverlayLines(const StatsSnapshot &snapshot, uint64_t frame_number, const LineFlags &flags) { + std::vector lines; + FormatOverlayLines(snapshot, frame_number, flags, lines); + return lines; +} + +// Every 540 pixels of the image's shorter side add one image pixel per font pixel at 100% scale +constexpr uint32_t kImagePixelsPerSize = 540; +constexpr uint32_t kMinBasePixelSize = 2; +constexpr uint32_t kPercent = 100; + +// At 100% scale a font pixel is the shorter side of the image divided by 540, rounded, and at least 2 image pixels. +// That is 2 until the shorter side reaches 1350, then 3 at 1728p and 4 at 2160p. +static uint32_t PixelSize(VkExtent2D visible_extent, int scale_percent) { + const uint32_t shorter_side = std::min(visible_extent.width, visible_extent.height); + const uint32_t base = std::max(kMinBasePixelSize, (shorter_side + (kImagePixelsPerSize / 2)) / kImagePixelsPerSize); + const auto scale = static_cast(std::clamp(scale_percent, kMinScalePercent, kMaxScalePercent)); + return std::max(1u, ((base * scale) + (kPercent / 2)) / kPercent); +} + +namespace { +struct Point { + int32_t x; + int32_t y; +}; +} // namespace + +// Maps a point from visible space to image space. Image content is the visible content rotated clockwise. +[[nodiscard]] static Point VisibleToImage(uint32_t rotation, VkExtent2D visible, int32_t vx, int32_t vy) { + const auto vw = static_cast(visible.width); + const auto vh = static_cast(visible.height); + switch (rotation) { + case 1: + return {vh - vy, vx}; + case 2: + return {vw - vx, vh - vy}; + case 3: + return {vy, vw - vx}; + default: + return {vx, vy}; + } +} + +OverlayLayout ComputeOverlayLayout(VkExtent2D image_extent, Position position, int scale_percent, + VkSurfaceTransformFlagBitsKHR transform, const std::vector &lines) { + OverlayLayout layout; + + switch (transform) { + case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR: + layout.rotation = 1; + break; + case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR: + layout.rotation = 2; + break; + case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR: + layout.rotation = 3; + break; + case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR: + layout.rotation = 1; + layout.transform_warning = true; + break; + case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR: + layout.rotation = 2; + layout.transform_warning = true; + break; + case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR: + layout.rotation = 3; + layout.transform_warning = true; + break; + case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR: + break; + default: + layout.transform_warning = true; + break; + } + + layout.visible_extent = image_extent; + if (layout.rotation % 2 == 1) { + std::swap(layout.visible_extent.width, layout.visible_extent.height); + } + + const size_t line_count = std::min(lines.size(), static_cast(kMaxLines)); + size_t columns = 0; + for (size_t i = 0; i < line_count; ++i) { + columns = std::max(columns, std::min(lines[i].size(), static_cast(kMaxColumns))); + } + + layout.pixel_size = PixelSize(layout.visible_extent, scale_percent); + const auto px = static_cast(layout.pixel_size); + const int32_t width = ((2 * kPadding) + (static_cast(columns) * kCharAdvance) - 1) * px; + const int32_t height = ((2 * kPadding) + (static_cast(line_count) * kLineAdvance) - 2) * px; + const int32_t margin = kMargin * px; + const auto vw = static_cast(layout.visible_extent.width); + const auto vh = static_cast(layout.visible_extent.height); + + const bool right = position == Position::TopRight || position == Position::BottomRight; + const bool bottom = position == Position::BottomLeft || position == Position::BottomRight; + // A panel bigger than the image is clipped, so the image rect is always a valid scissor. + const int32_t x0 = std::clamp(right ? vw - margin - width : margin, 0, vw); + const int32_t y0 = std::clamp(bottom ? vh - margin - height : margin, 0, vh); + layout.visible_rect[0] = x0; + layout.visible_rect[1] = y0; + layout.visible_rect[2] = std::min(x0 + width, vw); + layout.visible_rect[3] = std::min(y0 + height, vh); + + const Point first = VisibleToImage(layout.rotation, layout.visible_extent, layout.visible_rect[0], layout.visible_rect[1]); + const Point second = VisibleToImage(layout.rotation, layout.visible_extent, layout.visible_rect[2], layout.visible_rect[3]); + layout.image_rect[0] = std::min(first.x, second.x); + layout.image_rect[1] = std::min(first.y, second.y); + layout.image_rect[2] = std::max(first.x, second.x); + layout.image_rect[3] = std::max(first.y, second.y); + + return layout; +} + +OverlayPushConstants PackOverlayPushConstants(const OverlayLayout &layout, const std::vector &lines, float white, + bool opaque) { + OverlayPushConstants push_constants = {}; + push_constants.visible_rect = layout.visible_rect; + push_constants.visible_extent = + (layout.visible_extent.width & kExtentWidthMask) | (layout.visible_extent.height << kExtentHeightShift); + + const uint32_t line_count = std::min(static_cast(lines.size()), kMaxLines); + push_constants.params = (layout.pixel_size & kParamsPixelSizeMask) | + ((layout.rotation & kParamsRotationMask) << kParamsRotationShift) | + (line_count << kParamsLineCountShift) | ((opaque ? 1u : 0u) << kParamsOpaqueShift); + push_constants.white = white; + + for (uint32_t line = 0; line < line_count; ++line) { + const uint32_t columns = std::min(static_cast(lines[line].size()), kMaxColumns); + for (uint32_t column = 0; column < columns; ++column) { + const uint32_t byte = (line * kMaxColumns) + column; + push_constants.glyphs[byte / kGlyphsPerWord] |= static_cast(GlyphIndex(lines[line][column])) + << ((byte % kGlyphsPerWord) * kBitsPerGlyph); + } + } + return push_constants; +} + +constexpr double kHdrWhiteNits = 200.0; +// scRGB 1.0 is 80 nits +constexpr double kScRgbWhiteNits = 80.0; +// HLG reference white is 75% signal (ITU-R BT.2408) +constexpr float kHlgReferenceWhite = 0.75f; + +// SMPTE ST 2084 (PQ) constants, named as in the standard +constexpr double kPqPeakNits = 10000.0; +constexpr double kPqM1 = 2610.0 / 16384.0; +constexpr double kPqM2 = 2523.0 / 4096.0 * 128.0; +constexpr double kPqC1 = 3424.0 / 4096.0; +constexpr double kPqC2 = 2413.0 / 4096.0 * 32.0; +constexpr double kPqC3 = 2392.0 / 4096.0 * 32.0; + +// SMPTE ST 2084 (PQ) inverse EOTF +[[nodiscard]] static float EncodePq(double nits) { + const double y = std::pow(nits / kPqPeakNits, kPqM1); + return static_cast(std::pow((kPqC1 + (kPqC2 * y)) / (1.0 + (kPqC3 * y)), kPqM2)); +} + +WhiteLevel WhiteForColorSpace(VkColorSpaceKHR color_space) { + switch (color_space) { + case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR: + case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT: + case VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT: + case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT: + case VK_COLOR_SPACE_BT709_LINEAR_EXT: + case VK_COLOR_SPACE_BT709_NONLINEAR_EXT: + case VK_COLOR_SPACE_BT2020_LINEAR_EXT: + case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT: + case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT: + case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT: + return {1.0f, true}; + case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT: + return {static_cast(kHdrWhiteNits / kScRgbWhiteNits), true}; + case VK_COLOR_SPACE_HDR10_ST2084_EXT: + return {EncodePq(kHdrWhiteNits), true}; + case VK_COLOR_SPACE_HDR10_HLG_EXT: + return {kHlgReferenceWhite, true}; + default: + return {1.0f, false}; + } +} + +SwapchainPatch PatchSwapchainCreateInfo(const VkSwapchainCreateInfoKHR &create_info, const LineFlags &lines) { + SwapchainPatch patch; + patch.create_info = create_info; + patch.eligibility = SwapchainOverlayEligibility(create_info); + if (!AnyLineVisible(lines)) { + patch.eligibility.ok = false; + patch.eligibility.reason = nullptr; + } + if (patch.eligibility.ok) { + // Every surface supports color attachment usage, so this is always valid. + patch.create_info.imageUsage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + } + return patch; +} + +Eligibility SwapchainOverlayEligibility(const VkSwapchainCreateInfoKHR &create_info) { + Eligibility eligibility; + if (create_info.presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR || + create_info.presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) { + eligibility.ok = false; + eligibility.reason = "shared present modes are not supported"; + } else if ((create_info.flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) != 0u) { + eligibility.ok = false; + eligibility.reason = "protected swapchains are not supported"; + } + eligibility.deferred = (create_info.flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_KHR) != 0; + return eligibility; +} + +bool ShouldDrawOverlay(VkQueueFlags queue_flags, bool any_overlay_swapchain, bool any_line_visible) { + return ((queue_flags & VK_QUEUE_GRAPHICS_BIT) != 0u) && any_overlay_swapchain && any_line_visible; +} + +bool ImageViewUsageAvailable(uint32_t instance_api_version, uint32_t device_api_version, bool maintenance2_enabled) { + // Patch versions add no functionality + const auto major_minor = [](uint32_t version) { + return VK_MAKE_API_VERSION(0, VK_API_VERSION_MAJOR(version), VK_API_VERSION_MINOR(version), 0); + }; + return maintenance2_enabled || + std::min(major_minor(instance_api_version), major_minor(device_api_version)) >= VK_API_VERSION_1_1; +} + +MonitorSettings ParseSettings(const RawSettings &raw) { + MonitorSettings settings; + + if (raw.position == "TOP_RIGHT") { + settings.position = Position::TopRight; + } else if (raw.position == "BOTTOM_LEFT") { + settings.position = Position::BottomLeft; + } else if (raw.position == "BOTTOM_RIGHT") { + settings.position = Position::BottomRight; + } else { + settings.position = Position::TopLeft; + } + + settings.scale_percent = std::clamp(raw.scale, kMinScalePercent, kMaxScalePercent); + settings.update_interval = std::chrono::milliseconds(std::max(raw.update_interval_ms, kMinUpdateIntervalMs)); + settings.lines.fps = raw.show_fps; + settings.lines.frame_time = raw.show_frame_time; + settings.lines.frame_number = raw.show_frame_number; + settings.log_warnings = raw.log_warnings; + return settings; +} + +} // namespace monitor diff --git a/layersvt/monitor_overlay.h b/layersvt/monitor_overlay.h new file mode 100644 index 0000000000..a24eda213f --- /dev/null +++ b/layersvt/monitor_overlay.h @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace monitor { + +struct StatsSnapshot { + bool valid = false; + double fps = 0.0; + double avg_ms = 0.0; + double min_ms = 0.0; + double max_ms = 0.0; +}; + +// Present-to-present timing for one swapchain. The snapshot is refreshed once per update interval. +struct FrameStats { + StatsSnapshot snapshot; + + bool started = false; + std::chrono::steady_clock::time_point last_present; + std::chrono::steady_clock::time_point interval_start; + uint32_t frame_count = 0; + double total_ms = 0.0; + double min_ms = 0.0; + double max_ms = 0.0; +}; + +void RecordPresent(FrameStats &stats, std::chrono::steady_clock::time_point now, std::chrono::milliseconds interval); + +// Returns the number of the frame being presented. Frame 0 is the first presented image. +[[nodiscard]] uint64_t NextFrameNumber(std::atomic &counter); + +// 5x7 bitmap font. The fragment shader holds a copy of the same table. +inline constexpr int kGlyphWidth = 5; +inline constexpr int kGlyphHeight = 7; +inline constexpr int kGlyphCount = 23; + +// Panel metrics in font pixels. The fragment shader holds a copy of these too. +inline constexpr int kCharAdvance = kGlyphWidth + 1; +inline constexpr int kLineAdvance = kGlyphHeight + 2; +inline constexpr int kPadding = 3; +inline constexpr int kMargin = 4; + +// Characters the font can't draw map to the blank glyph. +[[nodiscard]] uint8_t GlyphIndex(char character); + +// Returns one row of a glyph, top row first. Bit 4 is the leftmost pixel. +[[nodiscard]] uint8_t GlyphRow(uint8_t glyph, int row); + +struct LineFlags { + bool fps = true; + bool frame_time = true; + bool frame_number = true; +}; + +// With every line hidden there is no overlay to draw +[[nodiscard]] bool AnyLineVisible(const LineFlags &flags); + +// What to say about vkCreateSharedSwapchainsKHR swapchains, which never get the overlay. Null with every line hidden. +[[nodiscard]] const char *SharedSwapchainsWarning(const LineFlags &flags); + +// Messages already shown to the user, so each is shown once +using ShownMessages = std::set>; + +// True the first time `message` is seen. Messages seen before cost a lookup, without allocating. +[[nodiscard]] bool FirstTimeShown(ShownMessages &shown, std::string_view message); + +// Text lines of the overlay, top to bottom. Hidden lines are left out. +[[nodiscard]] std::vector FormatOverlayLines(const StatsSnapshot &snapshot, uint64_t frame_number, + const LineFlags &flags); + +// The same, reusing the strings in `lines`, so it doesn't allocate once they have grown to fit. +void FormatOverlayLines(const StatsSnapshot &snapshot, uint64_t frame_number, const LineFlags &flags, + std::vector &lines); + +enum class Position : uint8_t { TopLeft, TopRight, BottomLeft, BottomRight }; + +// {x0, y0, x1, y1}, x1 and y1 exclusive. An array rather than named fields, so it has the shaders' ivec4 layout. +using Rect = std::array; + +struct OverlayLayout { + VkExtent2D visible_extent = {}; // Image extent as the user sees it, after preTransform + Rect visible_rect = {}; // Panel as the user sees it + Rect image_rect = {}; // Panel in swapchain image pixels + uint32_t rotation = 0; // Quarter turns clockwise from visible to image + uint32_t pixel_size = 1; // Image pixels per font pixel + bool transform_warning = false; // preTransform was mirrored or INHERIT and is drawn unmirrored +}; + +[[nodiscard]] OverlayLayout ComputeOverlayLayout(VkExtent2D image_extent, Position position, int scale_percent, + VkSurfaceTransformFlagBitsKHR transform, const std::vector &lines); + +inline constexpr uint32_t kMaxLines = 3; +inline constexpr uint32_t kMaxColumns = 32; + +// Bit layout of the packed push constant fields. The overlay shaders unpack the same layout. +inline constexpr uint32_t kExtentHeightShift = 16; +inline constexpr uint32_t kExtentWidthMask = 0xFFFF; +inline constexpr uint32_t kParamsPixelSizeMask = 0xFF; +inline constexpr uint32_t kParamsRotationShift = 8; +inline constexpr uint32_t kParamsRotationMask = 0x3; +inline constexpr uint32_t kParamsLineCountShift = 10; +inline constexpr uint32_t kParamsOpaqueShift = 12; +inline constexpr uint32_t kGlyphsPerWord = 4; +inline constexpr uint32_t kBitsPerGlyph = 8; + +// maxPushConstantsSize every Vulkan implementation supports +inline constexpr size_t kMinMaxPushConstantsSize = 128; + +// Everything the overlay shaders need. Must match the push constant block in the overlay shaders. +struct OverlayPushConstants { + Rect visible_rect; // Panel as the user sees it + uint32_t visible_extent; // width | height << 16 + uint32_t params; // pixel size (bits 0-7) | rotation (8-9) | line count (10-11) | opaque (12) + float white; // Value of white for the swapchain color space + uint32_t reserved; + std::array glyphs; // Glyph indices, one byte each, kMaxColumns per line +}; +static_assert(sizeof(OverlayPushConstants) == kMinMaxPushConstantsSize, + "Push constants must fit in the minimum maxPushConstantsSize"); + +[[nodiscard]] OverlayPushConstants PackOverlayPushConstants(const OverlayLayout &layout, const std::vector &lines, + float white, bool opaque); + +struct WhiteLevel { + float value = 1.0f; + bool known = true; // False if the color space is not recognized and 1.0 was used +}; + +// Value written for white text, chosen so HDR swapchains show it at about 200 nits. +[[nodiscard]] WhiteLevel WhiteForColorSpace(VkColorSpaceKHR color_space); + +struct Eligibility { + bool ok = true; + const char *reason = nullptr; // Why the overlay can't be drawn, when !ok. Null if the user hid every line. + bool deferred = false; // Image memory is bound on first acquire, so image views must wait until then +}; + +[[nodiscard]] Eligibility SwapchainOverlayEligibility(const VkSwapchainCreateInfoKHR &create_info); + +// The create info a swapchain is created with, and whether the overlay can draw on it +struct SwapchainPatch { + VkSwapchainCreateInfoKHR create_info = {}; + Eligibility eligibility; +}; + +// Returns a copy of the create info that lets the overlay render into the swapchain images, or an unchanged copy if +// the overlay can't draw on them or `lines` hides everything. The pNext chain is shared. +[[nodiscard]] SwapchainPatch PatchSwapchainCreateInfo(const VkSwapchainCreateInfoKHR &create_info, const LineFlags &lines); + +[[nodiscard]] bool ShouldDrawOverlay(VkQueueFlags queue_flags, bool any_overlay_swapchain, bool any_line_visible); + +// Whether VkImageViewUsageCreateInfo can be used. The device version the app may use is the lower of its +// VkApplicationInfo::apiVersion (1.0 if not given) and the physical device's apiVersion. +[[nodiscard]] bool ImageViewUsageAvailable(uint32_t instance_api_version, uint32_t device_api_version, bool maintenance2_enabled); + +inline constexpr int kDefaultScalePercent = 100; +inline constexpr int kMinScalePercent = 50; +inline constexpr int kMaxScalePercent = 400; +inline constexpr int kDefaultUpdateIntervalMs = 500; +inline constexpr int kMinUpdateIntervalMs = 50; + +// Layer settings as read, before validation +struct RawSettings { + std::string position = "TOP_LEFT"; + int32_t scale = kDefaultScalePercent; + int32_t update_interval_ms = kDefaultUpdateIntervalMs; + bool show_fps = true; + bool show_frame_time = true; + bool show_frame_number = true; + bool log_warnings = false; +}; + +struct MonitorSettings { + Position position = Position::TopLeft; + int scale_percent = kDefaultScalePercent; + std::chrono::milliseconds update_interval{kDefaultUpdateIntervalMs}; + LineFlags lines; + bool log_warnings = false; // Say why the overlay isn't shown; off unless the user asks +}; + +[[nodiscard]] MonitorSettings ParseSettings(const RawSettings &raw); + +} // namespace monitor diff --git a/layersvt/monitor_overlay_shaders.h b/layersvt/monitor_overlay_shaders.h new file mode 100644 index 0000000000..ce37bc80b9 --- /dev/null +++ b/layersvt/monitor_overlay_shaders.h @@ -0,0 +1,296 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// *** THIS FILE IS GENERATED - DO NOT EDIT *** +// Generated by scripts/generate_monitor_shaders.py from layersvt/shaders +// Glslang Version: 11:15.4.0 + +#pragma once + +#include +#include + +// Hash of the shader sources this was generated from +inline constexpr uint64_t kMonitorOverlayShaderSourceHash = 0xca956795d3f13586ull; + +// monitor_overlay.vert +inline constexpr std::array kMonitorOverlayVertSpirv = { + 0x07230203, 0x00010000, 0x0008000b, 0x0000008b, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, + 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, + 0x0008000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000c, 0x00000071, 0x0000007c, + 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, 0x6e69616d, 0x00000000, 0x00040005, + 0x00000009, 0x6e726f63, 0x00007265, 0x00060005, 0x0000000c, 0x565f6c67, 0x65747265, 0x646e4978, + 0x00007865, 0x00040005, 0x00000015, 0x69736976, 0x00656c62, 0x00060005, 0x0000001a, 0x68737550, + 0x736e6f43, 0x746e6174, 0x00000073, 0x00070006, 0x0000001a, 0x00000000, 0x69736976, 0x5f656c62, + 0x74636572, 0x00000000, 0x00070006, 0x0000001a, 0x00000001, 0x69736976, 0x5f656c62, 0x65747865, + 0x0000746e, 0x00050006, 0x0000001a, 0x00000002, 0x61726170, 0x0000736d, 0x00050006, 0x0000001a, + 0x00000003, 0x74696877, 0x00000065, 0x00060006, 0x0000001a, 0x00000004, 0x65736572, 0x64657672, + 0x00000000, 0x00050006, 0x0000001a, 0x00000005, 0x70796c67, 0x00007368, 0x00030005, 0x0000001c, + 0x00006370, 0x00060005, 0x0000002a, 0x69736976, 0x5f656c62, 0x65747865, 0x0000746e, 0x00050005, + 0x00000038, 0x61746f72, 0x6e6f6974, 0x00000000, 0x00040005, 0x00000046, 0x67616d69, 0x00000065, + 0x00060005, 0x00000051, 0x67616d69, 0x78655f65, 0x746e6574, 0x00000000, 0x00050005, 0x00000071, + 0x5f74756f, 0x656e6170, 0x0000006c, 0x00060005, 0x0000007a, 0x505f6c67, 0x65567265, 0x78657472, + 0x00000000, 0x00060006, 0x0000007a, 0x00000000, 0x505f6c67, 0x7469736f, 0x006e6f69, 0x00070006, + 0x0000007a, 0x00000001, 0x505f6c67, 0x746e696f, 0x657a6953, 0x00000000, 0x00070006, 0x0000007a, + 0x00000002, 0x435f6c67, 0x4470696c, 0x61747369, 0x0065636e, 0x00070006, 0x0000007a, 0x00000003, + 0x435f6c67, 0x446c6c75, 0x61747369, 0x0065636e, 0x00030005, 0x0000007c, 0x00000000, 0x00040047, + 0x0000000c, 0x0000000b, 0x0000002a, 0x00040047, 0x00000019, 0x00000006, 0x00000004, 0x00030047, + 0x0000001a, 0x00000002, 0x00050048, 0x0000001a, 0x00000000, 0x00000023, 0x00000000, 0x00050048, + 0x0000001a, 0x00000001, 0x00000023, 0x00000010, 0x00050048, 0x0000001a, 0x00000002, 0x00000023, + 0x00000014, 0x00050048, 0x0000001a, 0x00000003, 0x00000023, 0x00000018, 0x00050048, 0x0000001a, + 0x00000004, 0x00000023, 0x0000001c, 0x00050048, 0x0000001a, 0x00000005, 0x00000023, 0x00000020, + 0x00040047, 0x00000071, 0x0000001e, 0x00000000, 0x00030047, 0x0000007a, 0x00000002, 0x00050048, + 0x0000007a, 0x00000000, 0x0000000b, 0x00000000, 0x00050048, 0x0000007a, 0x00000001, 0x0000000b, + 0x00000001, 0x00050048, 0x0000007a, 0x00000002, 0x0000000b, 0x00000003, 0x00050048, 0x0000007a, + 0x00000003, 0x0000000b, 0x00000004, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, + 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000002, 0x00040020, + 0x00000008, 0x00000007, 0x00000007, 0x00040015, 0x0000000a, 0x00000020, 0x00000001, 0x00040020, + 0x0000000b, 0x00000001, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000001, 0x0004002b, + 0x0000000a, 0x0000000e, 0x00000001, 0x00040017, 0x00000016, 0x0000000a, 0x00000004, 0x00040015, + 0x00000017, 0x00000020, 0x00000000, 0x0004002b, 0x00000017, 0x00000018, 0x00000018, 0x0004001c, + 0x00000019, 0x00000017, 0x00000018, 0x0008001e, 0x0000001a, 0x00000016, 0x00000017, 0x00000017, + 0x00000006, 0x00000017, 0x00000019, 0x00040020, 0x0000001b, 0x00000009, 0x0000001a, 0x0004003b, + 0x0000001b, 0x0000001c, 0x00000009, 0x0004002b, 0x0000000a, 0x0000001d, 0x00000000, 0x00040017, + 0x0000001e, 0x0000000a, 0x00000002, 0x00040020, 0x0000001f, 0x00000009, 0x00000016, 0x00040020, + 0x0000002b, 0x00000009, 0x00000017, 0x0004002b, 0x00000017, 0x0000002e, 0x0000ffff, 0x0004002b, + 0x0000000a, 0x00000033, 0x00000010, 0x00040020, 0x00000037, 0x00000007, 0x00000017, 0x0004002b, + 0x0000000a, 0x00000039, 0x00000002, 0x0004002b, 0x0000000a, 0x0000003c, 0x00000008, 0x0004002b, + 0x00000017, 0x0000003e, 0x00000003, 0x0004002b, 0x00000017, 0x00000041, 0x00000001, 0x00020014, + 0x00000042, 0x00040020, 0x00000047, 0x00000007, 0x00000006, 0x0004002b, 0x00000017, 0x0000004d, + 0x00000000, 0x0004002b, 0x00000017, 0x00000056, 0x00000002, 0x00040020, 0x00000070, 0x00000003, + 0x00000007, 0x0004003b, 0x00000070, 0x00000071, 0x00000003, 0x00040017, 0x00000078, 0x00000006, + 0x00000004, 0x0004001c, 0x00000079, 0x00000006, 0x00000041, 0x0006001e, 0x0000007a, 0x00000078, + 0x00000006, 0x00000079, 0x00000079, 0x00040020, 0x0000007b, 0x00000003, 0x0000007a, 0x0004003b, + 0x0000007b, 0x0000007c, 0x00000003, 0x0004002b, 0x00000006, 0x00000080, 0x40000000, 0x0004002b, + 0x00000006, 0x00000082, 0x3f800000, 0x0004002b, 0x00000006, 0x00000085, 0x00000000, 0x00040020, + 0x00000089, 0x00000003, 0x00000078, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, + 0x000200f8, 0x00000005, 0x0004003b, 0x00000008, 0x00000009, 0x00000007, 0x0004003b, 0x00000008, + 0x00000015, 0x00000007, 0x0004003b, 0x00000008, 0x0000002a, 0x00000007, 0x0004003b, 0x00000037, + 0x00000038, 0x00000007, 0x0004003b, 0x00000008, 0x00000046, 0x00000007, 0x0004003b, 0x00000008, + 0x00000051, 0x00000007, 0x0004003d, 0x0000000a, 0x0000000d, 0x0000000c, 0x000500c7, 0x0000000a, + 0x0000000f, 0x0000000d, 0x0000000e, 0x0004006f, 0x00000006, 0x00000010, 0x0000000f, 0x0004003d, + 0x0000000a, 0x00000011, 0x0000000c, 0x000500c3, 0x0000000a, 0x00000012, 0x00000011, 0x0000000e, + 0x0004006f, 0x00000006, 0x00000013, 0x00000012, 0x00050050, 0x00000007, 0x00000014, 0x00000010, + 0x00000013, 0x0003003e, 0x00000009, 0x00000014, 0x00050041, 0x0000001f, 0x00000020, 0x0000001c, + 0x0000001d, 0x0004003d, 0x00000016, 0x00000021, 0x00000020, 0x0007004f, 0x0000001e, 0x00000022, + 0x00000021, 0x00000021, 0x00000000, 0x00000001, 0x0004006f, 0x00000007, 0x00000023, 0x00000022, + 0x00050041, 0x0000001f, 0x00000024, 0x0000001c, 0x0000001d, 0x0004003d, 0x00000016, 0x00000025, + 0x00000024, 0x0007004f, 0x0000001e, 0x00000026, 0x00000025, 0x00000025, 0x00000002, 0x00000003, + 0x0004006f, 0x00000007, 0x00000027, 0x00000026, 0x0004003d, 0x00000007, 0x00000028, 0x00000009, + 0x0008000c, 0x00000007, 0x00000029, 0x00000001, 0x0000002e, 0x00000023, 0x00000027, 0x00000028, + 0x0003003e, 0x00000015, 0x00000029, 0x00050041, 0x0000002b, 0x0000002c, 0x0000001c, 0x0000000e, + 0x0004003d, 0x00000017, 0x0000002d, 0x0000002c, 0x000500c7, 0x00000017, 0x0000002f, 0x0000002d, + 0x0000002e, 0x00040070, 0x00000006, 0x00000030, 0x0000002f, 0x00050041, 0x0000002b, 0x00000031, + 0x0000001c, 0x0000000e, 0x0004003d, 0x00000017, 0x00000032, 0x00000031, 0x000500c2, 0x00000017, + 0x00000034, 0x00000032, 0x00000033, 0x00040070, 0x00000006, 0x00000035, 0x00000034, 0x00050050, + 0x00000007, 0x00000036, 0x00000030, 0x00000035, 0x0003003e, 0x0000002a, 0x00000036, 0x00050041, + 0x0000002b, 0x0000003a, 0x0000001c, 0x00000039, 0x0004003d, 0x00000017, 0x0000003b, 0x0000003a, + 0x000500c2, 0x00000017, 0x0000003d, 0x0000003b, 0x0000003c, 0x000500c7, 0x00000017, 0x0000003f, + 0x0000003d, 0x0000003e, 0x0003003e, 0x00000038, 0x0000003f, 0x0004003d, 0x00000017, 0x00000040, + 0x00000038, 0x000500aa, 0x00000042, 0x00000043, 0x00000040, 0x00000041, 0x000300f7, 0x00000045, + 0x00000000, 0x000400fa, 0x00000043, 0x00000044, 0x00000054, 0x000200f8, 0x00000044, 0x00050041, + 0x00000047, 0x00000048, 0x0000002a, 0x00000041, 0x0004003d, 0x00000006, 0x00000049, 0x00000048, + 0x00050041, 0x00000047, 0x0000004a, 0x00000015, 0x00000041, 0x0004003d, 0x00000006, 0x0000004b, + 0x0000004a, 0x00050083, 0x00000006, 0x0000004c, 0x00000049, 0x0000004b, 0x00050041, 0x00000047, + 0x0000004e, 0x00000015, 0x0000004d, 0x0004003d, 0x00000006, 0x0000004f, 0x0000004e, 0x00050050, + 0x00000007, 0x00000050, 0x0000004c, 0x0000004f, 0x0003003e, 0x00000046, 0x00000050, 0x0004003d, + 0x00000007, 0x00000052, 0x0000002a, 0x0007004f, 0x00000007, 0x00000053, 0x00000052, 0x00000052, + 0x00000001, 0x00000000, 0x0003003e, 0x00000051, 0x00000053, 0x000200f9, 0x00000045, 0x000200f8, + 0x00000054, 0x0004003d, 0x00000017, 0x00000055, 0x00000038, 0x000500aa, 0x00000042, 0x00000057, + 0x00000055, 0x00000056, 0x000300f7, 0x00000059, 0x00000000, 0x000400fa, 0x00000057, 0x00000058, + 0x0000005e, 0x000200f8, 0x00000058, 0x0004003d, 0x00000007, 0x0000005a, 0x0000002a, 0x0004003d, + 0x00000007, 0x0000005b, 0x00000015, 0x00050083, 0x00000007, 0x0000005c, 0x0000005a, 0x0000005b, + 0x0003003e, 0x00000046, 0x0000005c, 0x0004003d, 0x00000007, 0x0000005d, 0x0000002a, 0x0003003e, + 0x00000051, 0x0000005d, 0x000200f9, 0x00000059, 0x000200f8, 0x0000005e, 0x0004003d, 0x00000017, + 0x0000005f, 0x00000038, 0x000500aa, 0x00000042, 0x00000060, 0x0000005f, 0x0000003e, 0x000300f7, + 0x00000062, 0x00000000, 0x000400fa, 0x00000060, 0x00000061, 0x0000006d, 0x000200f8, 0x00000061, + 0x00050041, 0x00000047, 0x00000063, 0x00000015, 0x00000041, 0x0004003d, 0x00000006, 0x00000064, + 0x00000063, 0x00050041, 0x00000047, 0x00000065, 0x0000002a, 0x0000004d, 0x0004003d, 0x00000006, + 0x00000066, 0x00000065, 0x00050041, 0x00000047, 0x00000067, 0x00000015, 0x0000004d, 0x0004003d, + 0x00000006, 0x00000068, 0x00000067, 0x00050083, 0x00000006, 0x00000069, 0x00000066, 0x00000068, + 0x00050050, 0x00000007, 0x0000006a, 0x00000064, 0x00000069, 0x0003003e, 0x00000046, 0x0000006a, + 0x0004003d, 0x00000007, 0x0000006b, 0x0000002a, 0x0007004f, 0x00000007, 0x0000006c, 0x0000006b, + 0x0000006b, 0x00000001, 0x00000000, 0x0003003e, 0x00000051, 0x0000006c, 0x000200f9, 0x00000062, + 0x000200f8, 0x0000006d, 0x0004003d, 0x00000007, 0x0000006e, 0x00000015, 0x0003003e, 0x00000046, + 0x0000006e, 0x0004003d, 0x00000007, 0x0000006f, 0x0000002a, 0x0003003e, 0x00000051, 0x0000006f, + 0x000200f9, 0x00000062, 0x000200f8, 0x00000062, 0x000200f9, 0x00000059, 0x000200f8, 0x00000059, + 0x000200f9, 0x00000045, 0x000200f8, 0x00000045, 0x0004003d, 0x00000007, 0x00000072, 0x00000015, + 0x00050041, 0x0000001f, 0x00000073, 0x0000001c, 0x0000001d, 0x0004003d, 0x00000016, 0x00000074, + 0x00000073, 0x0007004f, 0x0000001e, 0x00000075, 0x00000074, 0x00000074, 0x00000000, 0x00000001, + 0x0004006f, 0x00000007, 0x00000076, 0x00000075, 0x00050083, 0x00000007, 0x00000077, 0x00000072, + 0x00000076, 0x0003003e, 0x00000071, 0x00000077, 0x0004003d, 0x00000007, 0x0000007d, 0x00000046, + 0x0004003d, 0x00000007, 0x0000007e, 0x00000051, 0x00050088, 0x00000007, 0x0000007f, 0x0000007d, + 0x0000007e, 0x0005008e, 0x00000007, 0x00000081, 0x0000007f, 0x00000080, 0x00050050, 0x00000007, + 0x00000083, 0x00000082, 0x00000082, 0x00050083, 0x00000007, 0x00000084, 0x00000081, 0x00000083, + 0x00050051, 0x00000006, 0x00000086, 0x00000084, 0x00000000, 0x00050051, 0x00000006, 0x00000087, + 0x00000084, 0x00000001, 0x00070050, 0x00000078, 0x00000088, 0x00000086, 0x00000087, 0x00000085, + 0x00000082, 0x00050041, 0x00000089, 0x0000008a, 0x0000007c, 0x0000001d, 0x0003003e, 0x0000008a, + 0x00000088, 0x000100fd, 0x00010038, +}; + +// monitor_overlay.frag +inline constexpr std::array kMonitorOverlayFragSpirv = { + 0x07230203, 0x00010000, 0x0008000b, 0x000000ba, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, + 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, + 0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x0000002d, 0x00000039, 0x00030010, + 0x00000004, 0x00000007, 0x00030003, 0x00000002, 0x000001c2, 0x00040005, 0x00000004, 0x6e69616d, + 0x00000000, 0x00050005, 0x00000008, 0x65786970, 0x69735f6c, 0x0000657a, 0x00060005, 0x0000000e, + 0x68737550, 0x736e6f43, 0x746e6174, 0x00000073, 0x00070006, 0x0000000e, 0x00000000, 0x69736976, + 0x5f656c62, 0x74636572, 0x00000000, 0x00070006, 0x0000000e, 0x00000001, 0x69736976, 0x5f656c62, + 0x65747865, 0x0000746e, 0x00050006, 0x0000000e, 0x00000002, 0x61726170, 0x0000736d, 0x00050006, + 0x0000000e, 0x00000003, 0x74696877, 0x00000065, 0x00060006, 0x0000000e, 0x00000004, 0x65736572, + 0x64657672, 0x00000000, 0x00050006, 0x0000000e, 0x00000005, 0x70796c67, 0x00007368, 0x00030005, + 0x00000010, 0x00006370, 0x00050005, 0x00000018, 0x656e696c, 0x756f635f, 0x0000746e, 0x00040005, + 0x00000022, 0x7161706f, 0x00006575, 0x00050005, 0x0000002d, 0x5f74756f, 0x6f6c6f63, 0x00000072, + 0x00040005, 0x00000036, 0x746e6f66, 0x00000000, 0x00050005, 0x00000039, 0x705f6e69, 0x6c656e61, + 0x00000000, 0x00040005, 0x00000052, 0x656e696c, 0x00000000, 0x00040005, 0x00000057, 0x756c6f63, + 0x00006e6d, 0x00030005, 0x0000005c, 0x00000078, 0x00030005, 0x00000060, 0x00000079, 0x00040005, + 0x00000076, 0x65646e69, 0x00000078, 0x00040005, 0x0000007c, 0x70796c67, 0x00000068, 0x00030005, + 0x0000008a, 0x00776f72, 0x00050005, 0x000000a4, 0x65646e69, 0x6c626178, 0x00000065, 0x00040047, + 0x0000000d, 0x00000006, 0x00000004, 0x00030047, 0x0000000e, 0x00000002, 0x00050048, 0x0000000e, + 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x0000000e, 0x00000001, 0x00000023, 0x00000010, + 0x00050048, 0x0000000e, 0x00000002, 0x00000023, 0x00000014, 0x00050048, 0x0000000e, 0x00000003, + 0x00000023, 0x00000018, 0x00050048, 0x0000000e, 0x00000004, 0x00000023, 0x0000001c, 0x00050048, + 0x0000000e, 0x00000005, 0x00000023, 0x00000020, 0x00040047, 0x0000002d, 0x0000001e, 0x00000000, + 0x00040047, 0x00000039, 0x0000001e, 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, + 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040020, 0x00000007, 0x00000007, + 0x00000006, 0x00040015, 0x00000009, 0x00000020, 0x00000001, 0x00040017, 0x0000000a, 0x00000009, + 0x00000004, 0x00030016, 0x0000000b, 0x00000020, 0x0004002b, 0x00000006, 0x0000000c, 0x00000018, + 0x0004001c, 0x0000000d, 0x00000006, 0x0000000c, 0x0008001e, 0x0000000e, 0x0000000a, 0x00000006, + 0x00000006, 0x0000000b, 0x00000006, 0x0000000d, 0x00040020, 0x0000000f, 0x00000009, 0x0000000e, + 0x0004003b, 0x0000000f, 0x00000010, 0x00000009, 0x0004002b, 0x00000009, 0x00000011, 0x00000002, + 0x00040020, 0x00000012, 0x00000009, 0x00000006, 0x0004002b, 0x00000006, 0x00000015, 0x000000ff, + 0x00040020, 0x00000017, 0x00000007, 0x00000009, 0x0004002b, 0x00000009, 0x0000001b, 0x0000000a, + 0x0004002b, 0x00000006, 0x0000001d, 0x00000003, 0x00020014, 0x00000020, 0x00040020, 0x00000021, + 0x00000007, 0x00000020, 0x0004002b, 0x00000009, 0x00000025, 0x0000000c, 0x0004002b, 0x00000006, + 0x00000027, 0x00000001, 0x0004002b, 0x00000006, 0x00000029, 0x00000000, 0x00040017, 0x0000002b, + 0x0000000b, 0x00000004, 0x00040020, 0x0000002c, 0x00000003, 0x0000002b, 0x0004003b, 0x0000002c, + 0x0000002d, 0x00000003, 0x0004002b, 0x0000000b, 0x0000002e, 0x00000000, 0x0004002b, 0x0000000b, + 0x00000030, 0x3f800000, 0x0004002b, 0x0000000b, 0x00000031, 0x3f19999a, 0x00040017, 0x00000034, + 0x00000009, 0x00000002, 0x00040020, 0x00000035, 0x00000007, 0x00000034, 0x00040017, 0x00000037, + 0x0000000b, 0x00000002, 0x00040020, 0x00000038, 0x00000001, 0x00000037, 0x0004003b, 0x00000038, + 0x00000039, 0x00000001, 0x0004002b, 0x00000009, 0x00000041, 0x00000003, 0x0005002c, 0x00000034, + 0x00000042, 0x00000041, 0x00000041, 0x0004002b, 0x00000009, 0x00000046, 0x00000000, 0x0004002b, + 0x00000009, 0x00000055, 0x00000009, 0x0004002b, 0x00000009, 0x0000005a, 0x00000006, 0x0004002b, + 0x00000009, 0x00000068, 0x00000020, 0x0004002b, 0x00000009, 0x0000006c, 0x00000005, 0x0004002b, + 0x00000009, 0x00000070, 0x00000007, 0x0004002b, 0x00000006, 0x0000007e, 0x00000004, 0x0004002b, + 0x00000006, 0x00000084, 0x00000008, 0x0004002b, 0x00000006, 0x00000088, 0x00000016, 0x0004002b, + 0x00000006, 0x0000008b, 0x000000a1, 0x0004001c, 0x0000008c, 0x00000006, 0x0000008b, 0x0004002b, + 0x00000006, 0x0000008d, 0x0000000e, 0x0004002b, 0x00000006, 0x0000008e, 0x00000011, 0x0004002b, + 0x00000006, 0x0000008f, 0x00000013, 0x0004002b, 0x00000006, 0x00000090, 0x00000015, 0x0004002b, + 0x00000006, 0x00000091, 0x00000019, 0x0004002b, 0x00000006, 0x00000092, 0x0000000c, 0x0004002b, + 0x00000006, 0x00000093, 0x00000002, 0x0004002b, 0x00000006, 0x00000094, 0x0000001f, 0x0004002b, + 0x00000006, 0x00000095, 0x00000006, 0x0004002b, 0x00000006, 0x00000096, 0x0000000a, 0x0004002b, + 0x00000006, 0x00000097, 0x00000012, 0x0004002b, 0x00000006, 0x00000098, 0x00000010, 0x0004002b, + 0x00000006, 0x00000099, 0x0000001e, 0x0004002b, 0x00000006, 0x0000009a, 0x0000000f, 0x0004002b, + 0x00000006, 0x0000009b, 0x0000001a, 0x00a4002c, 0x0000008c, 0x0000009c, 0x00000029, 0x00000029, + 0x00000029, 0x00000029, 0x00000029, 0x00000029, 0x00000029, 0x0000008d, 0x0000008e, 0x0000008f, + 0x00000090, 0x00000091, 0x0000008e, 0x0000008d, 0x0000007e, 0x00000092, 0x0000007e, 0x0000007e, + 0x0000007e, 0x0000007e, 0x0000008d, 0x0000008d, 0x0000008e, 0x00000027, 0x00000093, 0x0000007e, + 0x00000084, 0x00000094, 0x00000094, 0x00000093, 0x0000007e, 0x00000093, 0x00000027, 0x0000008e, + 0x0000008d, 0x00000093, 0x00000095, 0x00000096, 0x00000097, 0x00000094, 0x00000093, 0x00000093, + 0x00000094, 0x00000098, 0x00000099, 0x00000027, 0x00000027, 0x0000008e, 0x0000008d, 0x00000095, + 0x00000084, 0x00000098, 0x00000099, 0x0000008e, 0x0000008e, 0x0000008d, 0x00000094, 0x00000027, + 0x00000093, 0x0000007e, 0x00000084, 0x00000084, 0x00000084, 0x0000008d, 0x0000008e, 0x0000008e, + 0x0000008d, 0x0000008e, 0x0000008e, 0x0000008d, 0x0000008d, 0x0000008e, 0x0000008e, 0x0000009a, + 0x00000027, 0x00000093, 0x00000092, 0x00000029, 0x00000029, 0x00000029, 0x00000029, 0x00000029, + 0x00000092, 0x00000092, 0x00000029, 0x00000029, 0x00000029, 0x0000008d, 0x00000029, 0x00000029, + 0x00000029, 0x00000093, 0x0000007e, 0x00000084, 0x00000084, 0x00000084, 0x0000007e, 0x00000093, + 0x00000084, 0x0000007e, 0x00000093, 0x00000093, 0x00000093, 0x0000007e, 0x00000084, 0x00000094, + 0x00000098, 0x00000098, 0x00000099, 0x00000098, 0x00000098, 0x00000098, 0x00000099, 0x0000008e, + 0x0000008e, 0x00000099, 0x00000098, 0x00000098, 0x00000098, 0x0000009a, 0x00000098, 0x00000098, + 0x0000008d, 0x00000027, 0x00000027, 0x00000099, 0x00000029, 0x00000029, 0x0000008d, 0x00000027, + 0x0000009a, 0x0000008e, 0x0000009a, 0x00000029, 0x00000029, 0x0000008d, 0x0000008e, 0x00000094, + 0x00000098, 0x0000008d, 0x00000029, 0x00000029, 0x0000009b, 0x00000090, 0x00000090, 0x0000008e, + 0x0000008e, 0x00000029, 0x00000029, 0x00000088, 0x00000091, 0x00000098, 0x00000098, 0x00000098, + 0x00000029, 0x00000029, 0x0000009a, 0x00000098, 0x0000008d, 0x00000027, 0x00000099, 0x0004002b, + 0x00000006, 0x0000009e, 0x00000007, 0x00040020, 0x000000a3, 0x00000007, 0x0000008c, 0x0004002b, + 0x00000009, 0x000000a8, 0x00000004, 0x00040020, 0x000000b1, 0x00000009, 0x0000000b, 0x0004002b, + 0x00000009, 0x000000b9, 0x00000017, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, + 0x000200f8, 0x00000005, 0x0004003b, 0x00000007, 0x00000008, 0x00000007, 0x0004003b, 0x00000017, + 0x00000018, 0x00000007, 0x0004003b, 0x00000021, 0x00000022, 0x00000007, 0x0004003b, 0x00000035, + 0x00000036, 0x00000007, 0x0004003b, 0x00000017, 0x00000052, 0x00000007, 0x0004003b, 0x00000017, + 0x00000057, 0x00000007, 0x0004003b, 0x00000017, 0x0000005c, 0x00000007, 0x0004003b, 0x00000017, + 0x00000060, 0x00000007, 0x0004003b, 0x00000007, 0x00000076, 0x00000007, 0x0004003b, 0x00000007, + 0x0000007c, 0x00000007, 0x0004003b, 0x00000007, 0x0000008a, 0x00000007, 0x0004003b, 0x000000a3, + 0x000000a4, 0x00000007, 0x00050041, 0x00000012, 0x00000013, 0x00000010, 0x00000011, 0x0004003d, + 0x00000006, 0x00000014, 0x00000013, 0x000500c7, 0x00000006, 0x00000016, 0x00000014, 0x00000015, + 0x0003003e, 0x00000008, 0x00000016, 0x00050041, 0x00000012, 0x00000019, 0x00000010, 0x00000011, + 0x0004003d, 0x00000006, 0x0000001a, 0x00000019, 0x000500c2, 0x00000006, 0x0000001c, 0x0000001a, + 0x0000001b, 0x000500c7, 0x00000006, 0x0000001e, 0x0000001c, 0x0000001d, 0x0004007c, 0x00000009, + 0x0000001f, 0x0000001e, 0x0003003e, 0x00000018, 0x0000001f, 0x00050041, 0x00000012, 0x00000023, + 0x00000010, 0x00000011, 0x0004003d, 0x00000006, 0x00000024, 0x00000023, 0x000500c2, 0x00000006, + 0x00000026, 0x00000024, 0x00000025, 0x000500c7, 0x00000006, 0x00000028, 0x00000026, 0x00000027, + 0x000500ab, 0x00000020, 0x0000002a, 0x00000028, 0x00000029, 0x0003003e, 0x00000022, 0x0000002a, + 0x0004003d, 0x00000020, 0x0000002f, 0x00000022, 0x000600a9, 0x0000000b, 0x00000032, 0x0000002f, + 0x00000030, 0x00000031, 0x00070050, 0x0000002b, 0x00000033, 0x0000002e, 0x0000002e, 0x0000002e, + 0x00000032, 0x0003003e, 0x0000002d, 0x00000033, 0x0004003d, 0x00000037, 0x0000003a, 0x00000039, + 0x0004003d, 0x00000006, 0x0000003b, 0x00000008, 0x00040070, 0x0000000b, 0x0000003c, 0x0000003b, + 0x00050050, 0x00000037, 0x0000003d, 0x0000003c, 0x0000003c, 0x00050088, 0x00000037, 0x0000003e, + 0x0000003a, 0x0000003d, 0x0006000c, 0x00000037, 0x0000003f, 0x00000001, 0x00000008, 0x0000003e, + 0x0004006e, 0x00000034, 0x00000040, 0x0000003f, 0x00050082, 0x00000034, 0x00000043, 0x00000040, + 0x00000042, 0x0003003e, 0x00000036, 0x00000043, 0x00050041, 0x00000017, 0x00000044, 0x00000036, + 0x00000029, 0x0004003d, 0x00000009, 0x00000045, 0x00000044, 0x000500b1, 0x00000020, 0x00000047, + 0x00000045, 0x00000046, 0x000400a8, 0x00000020, 0x00000048, 0x00000047, 0x000300f7, 0x0000004a, + 0x00000000, 0x000400fa, 0x00000048, 0x00000049, 0x0000004a, 0x000200f8, 0x00000049, 0x00050041, + 0x00000017, 0x0000004b, 0x00000036, 0x00000027, 0x0004003d, 0x00000009, 0x0000004c, 0x0000004b, + 0x000500b1, 0x00000020, 0x0000004d, 0x0000004c, 0x00000046, 0x000200f9, 0x0000004a, 0x000200f8, + 0x0000004a, 0x000700f5, 0x00000020, 0x0000004e, 0x00000047, 0x00000005, 0x0000004d, 0x00000049, + 0x000300f7, 0x00000050, 0x00000000, 0x000400fa, 0x0000004e, 0x0000004f, 0x00000050, 0x000200f8, + 0x0000004f, 0x000100fd, 0x000200f8, 0x00000050, 0x00050041, 0x00000017, 0x00000053, 0x00000036, + 0x00000027, 0x0004003d, 0x00000009, 0x00000054, 0x00000053, 0x00050087, 0x00000009, 0x00000056, + 0x00000054, 0x00000055, 0x0003003e, 0x00000052, 0x00000056, 0x00050041, 0x00000017, 0x00000058, + 0x00000036, 0x00000029, 0x0004003d, 0x00000009, 0x00000059, 0x00000058, 0x00050087, 0x00000009, + 0x0000005b, 0x00000059, 0x0000005a, 0x0003003e, 0x00000057, 0x0000005b, 0x00050041, 0x00000017, + 0x0000005d, 0x00000036, 0x00000029, 0x0004003d, 0x00000009, 0x0000005e, 0x0000005d, 0x0005008b, + 0x00000009, 0x0000005f, 0x0000005e, 0x0000005a, 0x0003003e, 0x0000005c, 0x0000005f, 0x00050041, + 0x00000017, 0x00000061, 0x00000036, 0x00000027, 0x0004003d, 0x00000009, 0x00000062, 0x00000061, + 0x0005008b, 0x00000009, 0x00000063, 0x00000062, 0x00000055, 0x0003003e, 0x00000060, 0x00000063, + 0x0004003d, 0x00000009, 0x00000064, 0x00000052, 0x0004003d, 0x00000009, 0x00000065, 0x00000018, + 0x000500af, 0x00000020, 0x00000066, 0x00000064, 0x00000065, 0x0004003d, 0x00000009, 0x00000067, + 0x00000057, 0x000500af, 0x00000020, 0x00000069, 0x00000067, 0x00000068, 0x000500a6, 0x00000020, + 0x0000006a, 0x00000066, 0x00000069, 0x0004003d, 0x00000009, 0x0000006b, 0x0000005c, 0x000500af, + 0x00000020, 0x0000006d, 0x0000006b, 0x0000006c, 0x000500a6, 0x00000020, 0x0000006e, 0x0000006a, + 0x0000006d, 0x0004003d, 0x00000009, 0x0000006f, 0x00000060, 0x000500af, 0x00000020, 0x00000071, + 0x0000006f, 0x00000070, 0x000500a6, 0x00000020, 0x00000072, 0x0000006e, 0x00000071, 0x000300f7, + 0x00000074, 0x00000000, 0x000400fa, 0x00000072, 0x00000073, 0x00000074, 0x000200f8, 0x00000073, + 0x000100fd, 0x000200f8, 0x00000074, 0x0004003d, 0x00000009, 0x00000077, 0x00000052, 0x00050084, + 0x00000009, 0x00000078, 0x00000077, 0x00000068, 0x0004003d, 0x00000009, 0x00000079, 0x00000057, + 0x00050080, 0x00000009, 0x0000007a, 0x00000078, 0x00000079, 0x0004007c, 0x00000006, 0x0000007b, + 0x0000007a, 0x0003003e, 0x00000076, 0x0000007b, 0x0004003d, 0x00000006, 0x0000007d, 0x00000076, + 0x00050086, 0x00000006, 0x0000007f, 0x0000007d, 0x0000007e, 0x00060041, 0x00000012, 0x00000080, + 0x00000010, 0x0000006c, 0x0000007f, 0x0004003d, 0x00000006, 0x00000081, 0x00000080, 0x0004003d, + 0x00000006, 0x00000082, 0x00000076, 0x00050089, 0x00000006, 0x00000083, 0x00000082, 0x0000007e, + 0x00050084, 0x00000006, 0x00000085, 0x00000083, 0x00000084, 0x000500c2, 0x00000006, 0x00000086, + 0x00000081, 0x00000085, 0x000500c7, 0x00000006, 0x00000087, 0x00000086, 0x00000015, 0x0007000c, + 0x00000006, 0x00000089, 0x00000001, 0x00000026, 0x00000087, 0x00000088, 0x0003003e, 0x0000007c, + 0x00000089, 0x0004003d, 0x00000006, 0x0000009d, 0x0000007c, 0x00050084, 0x00000006, 0x0000009f, + 0x0000009d, 0x0000009e, 0x0004003d, 0x00000009, 0x000000a0, 0x00000060, 0x0004007c, 0x00000006, + 0x000000a1, 0x000000a0, 0x00050080, 0x00000006, 0x000000a2, 0x0000009f, 0x000000a1, 0x0003003e, + 0x000000a4, 0x0000009c, 0x00050041, 0x00000007, 0x000000a5, 0x000000a4, 0x000000a2, 0x0004003d, + 0x00000006, 0x000000a6, 0x000000a5, 0x0003003e, 0x0000008a, 0x000000a6, 0x0004003d, 0x00000006, + 0x000000a7, 0x0000008a, 0x0004003d, 0x00000009, 0x000000a9, 0x0000005c, 0x00050082, 0x00000009, + 0x000000aa, 0x000000a8, 0x000000a9, 0x0004007c, 0x00000006, 0x000000ab, 0x000000aa, 0x000500c2, + 0x00000006, 0x000000ac, 0x000000a7, 0x000000ab, 0x000500c7, 0x00000006, 0x000000ad, 0x000000ac, + 0x00000027, 0x000500ab, 0x00000020, 0x000000ae, 0x000000ad, 0x00000029, 0x000300f7, 0x000000b0, + 0x00000000, 0x000400fa, 0x000000ae, 0x000000af, 0x000000b0, 0x000200f8, 0x000000af, 0x00050041, + 0x000000b1, 0x000000b2, 0x00000010, 0x00000041, 0x0004003d, 0x0000000b, 0x000000b3, 0x000000b2, + 0x00050041, 0x000000b1, 0x000000b4, 0x00000010, 0x00000041, 0x0004003d, 0x0000000b, 0x000000b5, + 0x000000b4, 0x00050041, 0x000000b1, 0x000000b6, 0x00000010, 0x00000041, 0x0004003d, 0x0000000b, + 0x000000b7, 0x000000b6, 0x00070050, 0x0000002b, 0x000000b8, 0x000000b3, 0x000000b5, 0x000000b7, + 0x00000030, 0x0003003e, 0x0000002d, 0x000000b8, 0x000200f9, 0x000000b0, 0x000200f8, 0x000000b0, + 0x000100fd, 0x00010038, +}; diff --git a/layersvt/monitor_present.cpp b/layersvt/monitor_present.cpp new file mode 100644 index 0000000000..cb7fef7a49 --- /dev/null +++ b/layersvt/monitor_present.cpp @@ -0,0 +1,601 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "monitor_present.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "monitor_overlay.h" +#include "monitor_renderer.h" +#include "vk_layer_table.h" + +namespace monitor { + +void DestroyOverlayPipelines(VkDevice device, const VkuDeviceDispatchTable &dispatch, OverlayPipelines &pipelines) { + const std::scoped_lock lock(pipelines.lock); + for (auto &entry : pipelines.by_key) { + DestroyOverlayPipeline(device, dispatch, entry.second); + } + pipelines.by_key.clear(); +} + +void SetupSwapchainOverlay(VkDevice device, const VkuDeviceDispatchTable &dispatch, VkSwapchainKHR swapchain, + const SwapchainPatch &patch, OverlaySupport support, OverlayPipelines &pipelines, + SwapchainOverlay &overlay) { + const VkSwapchainCreateInfoKHR &create_info = patch.create_info; + overlay = {}; + overlay.swapchain = swapchain; + overlay.format = create_info.imageFormat; + overlay.color_space = create_info.imageColorSpace; + overlay.extent = create_info.imageExtent; + overlay.transform = create_info.preTransform; + overlay.blend = support.blend; + overlay.view_usage = support.view_usage; + + overlay.deferred = patch.eligibility.deferred; + if (!patch.eligibility.ok) { + overlay.reason = patch.eligibility.reason; + return; + } + + uint32_t count = 0; + std::vector images; + if (dispatch.GetSwapchainImagesKHR(device, swapchain, &count, nullptr) == VK_SUCCESS) { + images.resize(count); + if (dispatch.GetSwapchainImagesKHR(device, swapchain, &count, images.data()) != VK_SUCCESS) { + images.clear(); + } + } + if (images.empty()) { + overlay.reason = "could not get the swapchain images"; + return; + } + + { + const std::scoped_lock lock(pipelines.lock); + const auto key = std::make_pair(overlay.format, overlay.blend); + auto cached = pipelines.by_key.find(key); + if (cached == pipelines.by_key.end()) { + OverlayPipeline pipeline; + if (CreateOverlayPipeline(device, dispatch, overlay.format, overlay.blend, pipeline) != VK_SUCCESS) { + overlay.reason = "could not create the overlay pipeline"; + return; + } + cached = pipelines.by_key.emplace(key, pipeline).first; + } + overlay.pipeline = cached->second; + } + + overlay.images.resize(images.size()); + for (size_t i = 0; i < images.size(); ++i) { + overlay.images[i].image = images[i]; + constexpr VkSemaphoreCreateInfo semaphore_info = {VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; + if (dispatch.CreateSemaphore(device, &semaphore_info, nullptr, &overlay.images[i].present_wait) != VK_SUCCESS) { + overlay.reason = "could not create semaphores"; + return; + } + } + + // Deferred images have no memory until acquired, so their views wait for the first present + if (!overlay.deferred) { + for (uint32_t i = 0; i < overlay.images.size(); ++i) { + if (!PrepareImage(device, dispatch, overlay, i)) { + overlay.reason = "could not create image views"; + return; + } + } + } + overlay.ok = true; +} + +bool PrepareImage(VkDevice device, const VkuDeviceDispatchTable &dispatch, SwapchainOverlay &overlay, uint32_t index) { + if (index >= overlay.images.size()) { + return false; + } + SwapchainImage &image = overlay.images[index]; + if (image.created) { + return true; + } + + // Without this the view inherits every swapchain usage, and some (STORAGE with an sRGB view of a mutable format + // swapchain) aren't valid for the view + constexpr VkImageViewUsageCreateInfo usage_info = {VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO, nullptr, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT}; + VkImageViewCreateInfo view_info = {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + view_info.pNext = overlay.view_usage ? &usage_info : nullptr; + view_info.image = image.image; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = overlay.format; + view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + if (dispatch.CreateImageView(device, &view_info, nullptr, &image.view) != VK_SUCCESS) { + image.view = VK_NULL_HANDLE; + return false; + } + + VkFramebufferCreateInfo framebuffer_info = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; + framebuffer_info.renderPass = overlay.pipeline.render_pass; + framebuffer_info.attachmentCount = 1; + framebuffer_info.pAttachments = &image.view; + framebuffer_info.width = overlay.extent.width; + framebuffer_info.height = overlay.extent.height; + framebuffer_info.layers = 1; + if (dispatch.CreateFramebuffer(device, &framebuffer_info, nullptr, &image.framebuffer) != VK_SUCCESS) { + // Leave nothing behind, since a deferred image is tried again on its next present + dispatch.DestroyImageView(device, image.view, nullptr); + image.view = VK_NULL_HANDLE; + image.framebuffer = VK_NULL_HANDLE; + return false; + } + + image.created = true; + return true; +} + +void DestroySwapchainOverlay(VkDevice device, const VkuDeviceDispatchTable &dispatch, SwapchainOverlay &overlay) { + for (const SwapchainImage &image : overlay.images) { + if (image.framebuffer) { + dispatch.DestroyFramebuffer(device, image.framebuffer, nullptr); + } + if (image.view) { + dispatch.DestroyImageView(device, image.view, nullptr); + } + if (image.present_wait) { + dispatch.DestroySemaphore(device, image.present_wait, nullptr); + } + } + overlay = {}; +} + +void CreateSlotRing(VkDevice device, const VkuDeviceDispatchTable &dispatch, uint32_t queue_family, + PFN_vkSetDeviceLoaderData set_loader_data, uint32_t slot_count, SlotRing &ring) { + ring = {}; + if (slot_count == 0) { + ring.reason = "no overlay, no submission slots"; + return; + } + if (!set_loader_data) { + ring.reason = "no overlay, the loader didn't provide vkSetDeviceLoaderData"; + return; + } + + // Running out of memory may not last, so the objects made so far are freed and the next present tries again + const auto out_of_memory = [&](const char *reason) { + DestroySlotRing(device, dispatch, ring); + ring.reason = reason; + ring.retry = true; + }; + + VkCommandPoolCreateInfo pool_info = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; + pool_info.queueFamilyIndex = queue_family; + if (dispatch.CreateCommandPool(device, &pool_info, nullptr, &ring.pool) != VK_SUCCESS) { + ring.pool = VK_NULL_HANDLE; + out_of_memory("no overlay on some frames, could not create a command pool"); + return; + } + + ring.slots.resize(slot_count); + for (SubmitSlot &slot : ring.slots) { + VkCommandBufferAllocateInfo allocate_info = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + allocate_info.commandPool = ring.pool; + allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocate_info.commandBufferCount = 1; + if (dispatch.AllocateCommandBuffers(device, &allocate_info, &slot.command_buffer) != VK_SUCCESS) { + slot.command_buffer = VK_NULL_HANDLE; + out_of_memory("no overlay on some frames, could not allocate command buffers"); + return; + } + if (set_loader_data(device, slot.command_buffer) != VK_SUCCESS) { + ring.reason = "no overlay, vkSetDeviceLoaderData failed"; + return; + } + + constexpr VkFenceCreateInfo fence_info = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; + if (dispatch.CreateFence(device, &fence_info, nullptr, &slot.fence) != VK_SUCCESS) { + slot.fence = VK_NULL_HANDLE; + out_of_memory("no overlay on some frames, could not create fences"); + return; + } + } + ring.ok = true; +} + +static void WaitForSlot(VkDevice device, const VkuDeviceDispatchTable &dispatch, SubmitSlot &slot) { + if (slot.in_flight) { + dispatch.WaitForFences(device, 1, &slot.fence, VK_TRUE, UINT64_MAX); + slot.in_flight = false; + slot.swapchains.clear(); + } +} + +SubmitSlot &AcquireSlot(VkDevice device, const VkuDeviceDispatchTable &dispatch, SlotRing &ring) { + SubmitSlot &slot = ring.slots[ring.next]; + ring.next = (ring.next + 1) % static_cast(ring.slots.size()); + WaitForSlot(device, dispatch, slot); + return slot; +} + +VkResult SubmitOverlay(VkDevice device, const VkuDeviceDispatchTable &dispatch, VkQueue queue, SubmitSlot &slot, + const std::vector &waits, const std::vector &signals, + const std::vector &swapchains) { + slot.wait_stages.assign(waits.size(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); + VkSubmitInfo submit = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; + submit.waitSemaphoreCount = static_cast(waits.size()); + submit.pWaitSemaphores = waits.data(); + submit.pWaitDstStageMask = slot.wait_stages.data(); + submit.commandBufferCount = 1; + submit.pCommandBuffers = &slot.command_buffer; + submit.signalSemaphoreCount = static_cast(signals.size()); + submit.pSignalSemaphores = signals.data(); + + // The fence is only reset when a submit will signal it again. A failed submit leaves it reset, but not in flight. + VkResult result = dispatch.ResetFences(device, 1, &slot.fence); + if (result != VK_SUCCESS) { + return result; + } + result = dispatch.QueueSubmit(queue, 1, &submit, slot.fence); + if (result == VK_SUCCESS) { + slot.in_flight = true; + slot.swapchains = swapchains; + } + return result; +} + +void WaitForSwapchain(VkDevice device, const VkuDeviceDispatchTable &dispatch, SlotRing &ring, VkSwapchainKHR swapchain) { + for (SubmitSlot &slot : ring.slots) { + if (std::find(slot.swapchains.begin(), slot.swapchains.end(), swapchain) != slot.swapchains.end()) { + WaitForSlot(device, dispatch, slot); + } + } +} + +void DestroySlotRing(VkDevice device, const VkuDeviceDispatchTable &dispatch, SlotRing &ring) { + for (SubmitSlot &slot : ring.slots) { + WaitForSlot(device, dispatch, slot); + if (slot.fence) { + dispatch.DestroyFence(device, slot.fence, nullptr); + } + if (slot.command_buffer) { + dispatch.FreeCommandBuffers(device, ring.pool, 1, &slot.command_buffer); + } + } + if (ring.pool) { + dispatch.DestroyCommandPool(device, ring.pool, nullptr); + } + ring = {}; +} + +// Sizes of the VkPresentInfoKHR extension structs that can come before VkPresentRegionsKHR. To change the regions, +// every struct ahead of them in the chain has to be copied, and only structs of known size can be. +[[nodiscard]] static size_t PresentStructSize(VkStructureType type) { + switch (type) { + case VK_STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR: + return sizeof(VkDisplayPresentInfoKHR); + case VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR: + return sizeof(VkDeviceGroupPresentInfoKHR); + case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE: + return sizeof(VkPresentTimesInfoGOOGLE); + case VK_STRUCTURE_TYPE_PRESENT_ID_KHR: + return sizeof(VkPresentIdKHR); + case VK_STRUCTURE_TYPE_PRESENT_ID_2_KHR: + return sizeof(VkPresentId2KHR); + case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_KHR: + return sizeof(VkSwapchainPresentFenceInfoKHR); + case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_KHR: + return sizeof(VkSwapchainPresentModeInfoKHR); + case VK_STRUCTURE_TYPE_FRAME_BOUNDARY_EXT: + return sizeof(VkFrameBoundaryEXT); + default: + return 0; + } +} + +// Rebuilds the start of the chain with a copy of VkPresentRegionsKHR in which overlay swapchains have no rectangles, +// meaning the whole image changed. Returns the original chain if there are no regions or they can't be reached. +[[nodiscard]] static const void *RewritePresentRegions(const void *chain, const std::vector &overlays, + PresentRewrite &rewrite) { + // The structs are only read through their own type once their sType is known. Until then their headers are copied out. + std::vector &prefix = rewrite.prefix; + prefix.clear(); + const void *node = chain; + for (; node && read_chain_header(node).sType != VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR; node = read_chain_header(node).pNext) { + prefix.push_back(node); + } + if (!node) { + return chain; + } + for (const void *before : prefix) { + if (PresentStructSize(read_chain_header(before).sType) == 0) { + rewrite.regions_unchanged = true; + return chain; + } + } + + rewrite.present_regions = *static_cast(node); + if (rewrite.present_regions.pRegions) { + rewrite.regions.assign(rewrite.present_regions.pRegions, + rewrite.present_regions.pRegions + rewrite.present_regions.swapchainCount); + for (size_t i = 0; i < rewrite.regions.size() && i < overlays.size(); ++i) { + if (overlays[i]) { + rewrite.regions[i].rectangleCount = 0; + rewrite.regions[i].pRectangles = nullptr; + } + } + rewrite.present_regions.pRegions = rewrite.regions.data(); + } + + // Copy the structs ahead of the regions, back to front, each pointing at the next copy. The copies are made and + // relinked with memcpy, which creates the structs in the 8-byte aligned storage without accessing it as another type. + const void *next = &rewrite.present_regions; + rewrite.copies.resize(prefix.size()); + for (size_t i = prefix.size(); i-- > 0;) { + const size_t size = PresentStructSize(read_chain_header(prefix[i]).sType); + std::vector © = rewrite.copies[i]; + copy.resize((size + sizeof(uint64_t) - 1) / sizeof(uint64_t)); + memcpy(copy.data(), prefix[i], size); + memcpy(reinterpret_cast(copy.data()) + offsetof(VkBaseOutStructure, pNext), &next, sizeof(next)); + next = copy.data(); + } + return next; +} + +const VkPresentInfoKHR &RewritePresentInfo(const VkPresentInfoKHR &original, const std::vector &waits, + const std::vector &overlays, PresentRewrite &rewrite) { + // The vectors keep their capacity, so presenting doesn't allocate once warmed up + rewrite.waits.assign(waits.begin(), waits.end()); + rewrite.regions.clear(); + rewrite.regions_unchanged = false; + rewrite.info = original; + rewrite.info.waitSemaphoreCount = static_cast(rewrite.waits.size()); + rewrite.info.pWaitSemaphores = rewrite.waits.data(); + rewrite.info.pNext = RewritePresentRegions(original.pNext, overlays, rewrite); + return rewrite.info; +} + +VkResult UndoOverlaySemaphores(const VkuDeviceDispatchTable &dispatch, VkQueue queue, + const std::vector &overlay_signals, const std::vector &app_waits) { + if (overlay_signals.empty() && app_waits.empty()) { + return VK_SUCCESS; + } + const std::vector stages(overlay_signals.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + VkSubmitInfo submit = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; + submit.waitSemaphoreCount = static_cast(overlay_signals.size()); + submit.pWaitSemaphores = overlay_signals.data(); + submit.pWaitDstStageMask = stages.data(); + submit.signalSemaphoreCount = static_cast(app_waits.size()); + submit.pSignalSemaphores = app_waits.data(); + return dispatch.QueueSubmit(queue, 1, &submit, VK_NULL_HANDLE); +} + +Warn WarnIf(bool enabled, Warn warn) { + if (enabled) { + return warn; + } + return [](const char * /*message*/) {}; +} + +std::unique_ptr ForgetSwapchain(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state, + VkSwapchainKHR swapchain) { + // The waits happen without the device lock, so presents to other swapchains aren't held up. Queue overlays live as + // long as the device, and the app can't present this swapchain while destroying it. + std::unique_ptr overlay; + std::vector queues; + { + const std::scoped_lock lock(state.lock); + auto it = state.swapchains.find(swapchain); + if (it == state.swapchains.end()) { + return nullptr; + } + overlay = std::move(it->second); + state.swapchains.erase(it); + for (auto &queue : state.queues) { + queues.push_back(queue.second.get()); + } + } + for (QueueOverlay *queue : queues) { + const std::scoped_lock queue_lock(queue->lock); + WaitForSwapchain(state.device, dispatch, queue->ring, swapchain); + } + return overlay; +} + +const char *AddSwapchainOverlay(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state, VkSwapchainKHR swapchain, + const SwapchainPatch &patch, bool blend_supported) { + auto overlay = std::make_unique(); + SetupSwapchainOverlay(state.device, dispatch, swapchain, patch, {blend_supported, state.view_usage}, state.pipelines, *overlay); + const char *reason = overlay->ok ? nullptr : overlay->reason; + + const std::scoped_lock lock(state.lock); + state.swapchains[swapchain] = std::move(overlay); + return reason; +} + +void DestroyDeviceOverlay(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state) { + const std::scoped_lock lock(state.lock); + for (auto &swapchain : state.swapchains) { + DestroySwapchainOverlay(state.device, dispatch, *swapchain.second); + } + state.swapchains.clear(); + for (auto &queue : state.queues) { + DestroySlotRing(state.device, dispatch, queue.second->ring); + } + state.queues.clear(); + DestroyOverlayPipelines(state.device, dispatch, state.pipelines); +} + +namespace { +// What the device lock part of a present found +struct PresentTargets { + QueueOverlay *queue = nullptr; // Null if the layer doesn't know the queue + uint32_t family = 0; + VkQueueFlags queue_flags = 0; + bool any_overlay = false; // Some swapchain is ready for the overlay + bool any_eligible = false; // Some swapchain could have the overlay, whatever the queue +}; +} // namespace + +// Finds the queue's state, records statistics for every presented swapchain, and lists the overlays to draw in the +// queue's state. Swapchains being presented can't be destroyed meanwhile, so the overlays stay valid after the device +// lock is released. +[[nodiscard]] static PresentTargets FindPresentTargets(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state, VkQueue queue, + const VkPresentInfoKHR &present_info, const MonitorSettings &settings, + std::chrono::steady_clock::time_point now) { + PresentTargets targets; + const std::scoped_lock lock(state.lock); + const auto found = state.queue_family_index.find(queue); + if (found != state.queue_family_index.end() && found->second < state.queue_families.size()) { + targets.family = found->second; + targets.queue_flags = state.queue_families[targets.family].queueFlags; + std::unique_ptr &entry = state.queues[queue]; + if (!entry) { + entry = std::make_unique(); + } + targets.queue = entry.get(); + targets.queue->overlays.assign(present_info.swapchainCount, nullptr); + } + + for (uint32_t i = 0; i < present_info.swapchainCount; ++i) { + auto it = state.swapchains.find(present_info.pSwapchains[i]); + if (it == state.swapchains.end()) { + continue; + } + RecordPresent(it->second->stats, now, settings.update_interval); + targets.any_eligible |= it->second->ok; + if (targets.queue && it->second->ok && PrepareImage(state.device, dispatch, *it->second, present_info.pImageIndices[i])) { + targets.queue->overlays[i] = it->second.get(); + targets.any_overlay = true; + } + } + return targets; +} + +// Records the overlay of every swapchain in the queue's list, and what the submit then signals and draws on. +static void RecordOverlays(const VkuDeviceDispatchTable &dispatch, QueueOverlay &queue_state, VkCommandBuffer command_buffer, + const VkPresentInfoKHR &present_info, const MonitorSettings &settings, uint64_t frame_number, + Warn warn) { + queue_state.signals.clear(); + queue_state.swapchains.clear(); + for (uint32_t i = 0; i < present_info.swapchainCount; ++i) { + const SwapchainOverlay *overlay = queue_state.overlays[i]; + if (!overlay) { + continue; + } + const SwapchainImage &image = overlay->images[present_info.pImageIndices[i]]; + + FormatOverlayLines(overlay->stats.snapshot, frame_number, settings.lines, queue_state.lines); + const OverlayLayout layout = + ComputeOverlayLayout(overlay->extent, settings.position, settings.scale_percent, overlay->transform, queue_state.lines); + const WhiteLevel white = WhiteForColorSpace(overlay->color_space); + if (layout.transform_warning) { + warn("mirrored swapchain transforms are drawn without the mirror"); + } + if (!white.known) { + warn("unknown swapchain color space, the overlay may be too bright or too dark"); + } + + const OverlayPushConstants push_constants = + PackOverlayPushConstants(layout, queue_state.lines, white.value, !overlay->blend); + RecordOverlay(dispatch, command_buffer, overlay->pipeline, image.framebuffer, overlay->extent, layout.image_rect, + push_constants); + queue_state.signals.push_back(image.present_wait); + queue_state.swapchains.push_back(overlay->swapchain); + } +} + +VkResult PresentWithOverlay(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state, VkQueue queue, + const VkPresentInfoKHR &present_info, const MonitorSettings &settings, uint64_t frame_number, + std::chrono::steady_clock::time_point now, Warn warn) { + const PresentTargets targets = FindPresentTargets(dispatch, state, queue, present_info, settings, now); + QueueOverlay *queue_state = targets.queue; + + const bool any_line = AnyLineVisible(settings.lines); + if (!queue_state) { + if (targets.any_eligible && any_line) { + warn("no overlay when presenting from a queue the layer didn't see from vkGetDeviceQueue or vkGetDeviceQueue2"); + } + return dispatch.QueuePresentKHR(queue, &present_info); + } + if (!ShouldDrawOverlay(targets.queue_flags, targets.any_overlay, any_line)) { + if (targets.any_overlay && any_line && ((targets.queue_flags & VK_QUEUE_GRAPHICS_BIT) == 0u)) { + warn("no overlay when presenting from a queue without graphics"); + } + return dispatch.QueuePresentKHR(queue, &present_info); + } + + std::unique_lock queue_lock(queue_state->lock); + const auto present_without_overlay = [&](const char *why) { + queue_lock.unlock(); + warn(why); + return dispatch.QueuePresentKHR(queue, &present_info); + }; + + SlotRing &ring = queue_state->ring; + if (!ring.ok && (!ring.reason || ring.retry)) { + CreateSlotRing(state.device, dispatch, targets.family, state.set_loader_data, 3, ring); + } + if (!ring.ok) { + return present_without_overlay(ring.reason ? ring.reason : "no overlay, could not create command buffers"); + } + + SubmitSlot &slot = AcquireSlot(state.device, dispatch, ring); + VkCommandBufferBeginInfo begin = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + if (dispatch.BeginCommandBuffer(slot.command_buffer, &begin) != VK_SUCCESS) { + return present_without_overlay("out of memory, some frames are presented without the overlay"); + } + + RecordOverlays(dispatch, *queue_state, slot.command_buffer, present_info, settings, frame_number, warn); + if (dispatch.EndCommandBuffer(slot.command_buffer) != VK_SUCCESS) { + return present_without_overlay("out of memory, some frames are presented without the overlay"); + } + + queue_state->waits.assign(present_info.pWaitSemaphores, present_info.pWaitSemaphores + present_info.waitSemaphoreCount); + const std::vector &signals = queue_state->signals; + VkResult result = SubmitOverlay(state.device, dispatch, queue, slot, queue_state->waits, signals, queue_state->swapchains); + if (result != VK_SUCCESS) { + // A failed submit leaves the app's semaphores alone, so the frame is presented as if the layer weren't there. Even + // after a device loss, the driver's present reports the error and fills in pResults for the application. + const bool out_of_memory = result == VK_ERROR_OUT_OF_HOST_MEMORY || result == VK_ERROR_OUT_OF_DEVICE_MEMORY; + return present_without_overlay(out_of_memory ? "out of memory, some frames are presented without the overlay" + : "the overlay submit failed, some frames are presented without the overlay"); + } + + // The rewritten info lives in the queue's state, which only the next present to this queue changes + const VkPresentInfoKHR &rewritten = RewritePresentInfo(present_info, signals, queue_state->overlays, queue_state->rewrite); + const bool regions_unchanged = queue_state->rewrite.regions_unchanged; + queue_lock.unlock(); + if (regions_unchanged) { + warn("VkPresentRegionsKHR is behind a struct the layer doesn't know, so the overlay may not update"); + } + result = dispatch.QueuePresentKHR(queue, &rewritten); + if (result == VK_ERROR_OUT_OF_HOST_MEMORY || result == VK_ERROR_OUT_OF_DEVICE_MEMORY) { + // The spec says a present failing this way leaves its semaphores untouched, but the overlay submit already waited + // on the application's. Only this present uses the queue's state, since the application synchronizes the queue. + // The present's error is the one the application needs, so a failure here isn't reported. + (void)UndoOverlaySemaphores(dispatch, queue, signals, queue_state->waits); + } + return result; +} + +} // namespace monitor diff --git a/layersvt/monitor_present.h b/layersvt/monitor_present.h new file mode 100644 index 0000000000..c4162e07e1 --- /dev/null +++ b/layersvt/monitor_present.h @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "monitor_overlay.h" +#include "monitor_renderer.h" + +namespace monitor { + +// Per swapchain image objects. The semaphore is what vkQueuePresentKHR waits on for this image; reusing it per image +// index is safe because the image can only be acquired again after the previous present of it has started. +struct SwapchainImage { + VkImage image = VK_NULL_HANDLE; + VkImageView view = VK_NULL_HANDLE; + VkFramebuffer framebuffer = VK_NULL_HANDLE; + VkSemaphore present_wait = VK_NULL_HANDLE; + bool created = false; // View and framebuffer exist +}; + +struct SwapchainOverlay { + VkSwapchainKHR swapchain = VK_NULL_HANDLE; + VkFormat format = VK_FORMAT_UNDEFINED; + VkColorSpaceKHR color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; + VkExtent2D extent = {}; + VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + bool deferred = false; // Image memory is bound on first acquire, so views are made at the first present + bool blend = true; + bool view_usage = false; // Views are limited to color attachment usage + bool ok = false; // The overlay can be drawn + const char *reason = nullptr; // Why not, when !ok + OverlayPipeline pipeline; // Owned by the device's OverlayPipelines + std::vector images; + FrameStats stats; +}; + +// Overlay pipelines by swapchain format and blending. The swapchains of a device share them, so recreating a swapchain, +// as apps do on every resize, doesn't compile the shaders again. `lock` is held while a pipeline is created, so two +// swapchains of a new format don't both compile it; presents never take it. +struct OverlayPipelines { + std::mutex lock; + std::map, OverlayPipeline> by_key; +}; + +// The device must be idle. +void DestroyOverlayPipelines(VkDevice device, const VkuDeviceDispatchTable &dispatch, OverlayPipelines &pipelines); + +// What the device and the swapchain format let the overlay use +struct OverlaySupport { + bool blend = true; // The format supports blending + bool view_usage = false; // VkImageViewUsageCreateInfo can be chained (Vulkan 1.1 or VK_KHR_maintenance2) +}; + +// Sets up everything needed to draw on a swapchain already created from `patch`. On failure `overlay.ok` is false, the swapchain +// still works, and DestroySwapchainOverlay is still the way to clean up. +void SetupSwapchainOverlay(VkDevice device, const VkuDeviceDispatchTable &dispatch, VkSwapchainKHR swapchain, + const SwapchainPatch &patch, OverlaySupport support, OverlayPipelines &pipelines, + SwapchainOverlay &overlay); + +// Makes sure the image view and framebuffer for an acquired image exist. Returns false if they couldn't be created. +[[nodiscard]] bool PrepareImage(VkDevice device, const VkuDeviceDispatchTable &dispatch, SwapchainOverlay &overlay, uint32_t index); + +// The swapchain must not be in use by the GPU (see WaitForSwapchain). +void DestroySwapchainOverlay(VkDevice device, const VkuDeviceDispatchTable &dispatch, SwapchainOverlay &overlay); + +// One overlay submission: a command buffer and the fence that says when it's done. +struct SubmitSlot { + VkCommandBuffer command_buffer = VK_NULL_HANDLE; + VkFence fence = VK_NULL_HANDLE; + bool in_flight = false; // Submitted, so the fence will signal + std::vector swapchains; // Drawn on by that submission + std::vector wait_stages; // Kept to reuse its memory +}; + +// Submission slots for one queue, used round robin. Externally synchronized (QueueOverlay::lock). +struct SlotRing { + VkCommandPool pool = VK_NULL_HANDLE; + std::vector slots; + uint32_t next = 0; + bool ok = false; + const char *reason = nullptr; // Why there's no overlay, when !ok + bool retry = false; // It ran out of memory, so the next present tries again +}; + +// The layer makes its own command buffers, so the loader needs `set_loader_data` to give them a dispatch pointer. +// Without it the ring isn't usable. +void CreateSlotRing(VkDevice device, const VkuDeviceDispatchTable &dispatch, uint32_t queue_family, + PFN_vkSetDeviceLoaderData set_loader_data, uint32_t slot_count, SlotRing &ring); + +// Returns the next slot once its previous submission is done, ready to record. +[[nodiscard]] SubmitSlot &AcquireSlot(VkDevice device, const VkuDeviceDispatchTable &dispatch, SlotRing &ring); + +// Submits the slot's recorded command buffer. The app's semaphores are waited on before the overlay draws, and the +// signal semaphores are what the present then waits on. On failure the slot is left reusable. +[[nodiscard]] VkResult SubmitOverlay(VkDevice device, const VkuDeviceDispatchTable &dispatch, VkQueue queue, SubmitSlot &slot, + const std::vector &waits, const std::vector &signals, + const std::vector &swapchains); + +// Waits until no submission is drawing on the swapchain. +void WaitForSwapchain(VkDevice device, const VkuDeviceDispatchTable &dispatch, SlotRing &ring, VkSwapchainKHR swapchain); + +void DestroySlotRing(VkDevice device, const VkuDeviceDispatchTable &dispatch, SlotRing &ring); + +// Storage for a VkPresentInfoKHR rewritten to wait on the overlay, and the parts of its pNext chain that were copied. +// The rewritten info points into this struct, so it must stay in place until the present is done. There is one per +// queue, which the app keeps from presenting twice at once, and reusing it keeps presents from allocating. +struct PresentRewrite { + VkPresentInfoKHR info = {}; + std::vector waits; + VkPresentRegionsKHR present_regions = {}; + std::vector regions; + std::vector> copies; + std::vector prefix; // Structs ahead of VkPresentRegionsKHR + bool regions_unchanged = false; // VkPresentRegionsKHR was behind a struct that can't be copied +}; + +// The present waits on `waits` instead of the app's semaphores. Swapchains with an overlay in `overlays[i]` report their whole +// image as changed in VkPresentRegionsKHR, so incremental presents still update the overlay. The rest of the pNext +// chain is passed through. +[[nodiscard]] const VkPresentInfoKHR &RewritePresentInfo(const VkPresentInfoKHR &original, const std::vector &waits, + const std::vector &overlays, PresentRewrite &rewrite); + +// Undoes the overlay submit's semaphore operations after the present that followed it failed without being enqueued. It +// waits on `overlay_signals`, so they can be signaled again, and signals `app_waits`, which the overlay submit consumed, so +// the application's semaphores are as it left them. +[[nodiscard]] VkResult UndoOverlaySemaphores(const VkuDeviceDispatchTable &dispatch, VkQueue queue, + const std::vector &overlay_signals, + const std::vector &app_waits); + +// Overlay state of one queue. The app already keeps presents to a queue from overlapping, so only the present in +// progress uses it. `lock` guards just the ring, for ForgetSwapchain, which waits for the submissions of every queue. +struct QueueOverlay { + std::mutex lock; + SlotRing ring; + + // Used by the present in progress on this queue, and kept so presenting doesn't allocate once warmed up + PresentRewrite rewrite; + std::vector overlays; // For each presented swapchain, null if it gets no overlay + std::vector lines; + std::vector waits; + std::vector signals; + std::vector swapchains; +}; + +// Overlay state of one device. The plain fields are set at vkCreateDevice and only read after that. `lock` guards the +// maps; the swapchain and queue overlays in them are only used by presents to them, which the app already keeps from +// overlapping with other uses of the swapchain or queue. +struct DeviceOverlay { + std::mutex lock; + VkDevice device = VK_NULL_HANDLE; + PFN_vkSetDeviceLoaderData set_loader_data = nullptr; + bool view_usage = false; // VkImageViewUsageCreateInfo can be used + std::vector queue_families; + std::unordered_map queue_family_index; + std::unordered_map> swapchains; + OverlayPipelines pipelines; + std::unordered_map> queues; +}; + +// Stops tracking the swapchain and waits until no overlay submission draws on it. Call before the swapchain is destroyed. +// Returns its overlay, or null if it had none, for DestroySwapchainOverlay after the swapchain is gone: a present may +// still be waiting on the overlay's semaphores until then. +[[nodiscard]] std::unique_ptr ForgetSwapchain(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state, + VkSwapchainKHR swapchain); + +// Sets up the overlay of a newly created swapchain and starts tracking it. Returns why the overlay can't be drawn on it, +// or null. The device lock is only held to add it, so presents to other swapchains go on while it's set up. +[[nodiscard]] const char *AddSwapchainOverlay(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state, + VkSwapchainKHR swapchain, const SwapchainPatch &patch, bool blend_supported); + +// Destroys everything the overlay created on the device. The device must be idle. +void DestroyDeviceOverlay(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state); + +// Tells the user why the overlay isn't drawn as asked. Called for every present it applies to; the layer shows each +// distinct message once. +using Warn = void (*)(const char *message); + +// `warn` when the user turned on log_warnings, otherwise a Warn that drops the message +[[nodiscard]] Warn WarnIf(bool enabled, Warn warn); + +// Presents with the overlay drawn on every swapchain that can have it, in one submit that waits for the app's work. +// The present then waits for that submit instead. Without the overlay, the app's present goes through unchanged. +// No lock is held while waiting for earlier overlay submissions or while the driver presents. +[[nodiscard]] VkResult PresentWithOverlay(const VkuDeviceDispatchTable &dispatch, DeviceOverlay &state, VkQueue queue, + const VkPresentInfoKHR &present_info, const MonitorSettings &settings, + uint64_t frame_number, std::chrono::steady_clock::time_point now, Warn warn); + +} // namespace monitor diff --git a/layersvt/monitor_renderer.cpp b/layersvt/monitor_renderer.cpp new file mode 100644 index 0000000000..50745c06cf --- /dev/null +++ b/layersvt/monitor_renderer.cpp @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "monitor_renderer.h" + +#include "monitor_overlay_shaders.h" + +#include +#include +#include +#include + +#include "monitor_overlay.h" + +namespace monitor { + +// The image arrives in PRESENT_SRC_KHR after whatever the app last did to it, and goes back to PRESENT_SRC_KHR. +[[nodiscard]] static VkResult CreateRenderPass(VkDevice device, const VkuDeviceDispatchTable &dispatch, VkFormat format, + VkRenderPass &render_pass) { + VkAttachmentDescription attachment = {}; + attachment.format = format; + attachment.samples = VK_SAMPLE_COUNT_1_BIT; + attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; + attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachment.initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + + constexpr VkAttachmentReference color = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; + VkSubpassDescription subpass = {}; + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.colorAttachmentCount = 1; + subpass.pColorAttachments = &color; + + // ALL_COMMANDS also covers apps that write the image with transfers, or present without a semaphore on the same queue. + std::array dependencies = {}; + dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; + dependencies[0].dstSubpass = 0; + dependencies[0].srcStageMask = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + dependencies[1].srcSubpass = 0; + dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; + dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[1].dstAccessMask = 0; + + VkRenderPassCreateInfo info = {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; + info.attachmentCount = 1; + info.pAttachments = &attachment; + info.subpassCount = 1; + info.pSubpasses = &subpass; + info.dependencyCount = static_cast(dependencies.size()); + info.pDependencies = dependencies.data(); + return dispatch.CreateRenderPass(device, &info, nullptr, &render_pass); +} + +template +[[nodiscard]] static VkResult CreateShaderModule(VkDevice device, const VkuDeviceDispatchTable &dispatch, + const std::array &code, VkShaderModule &module) { + VkShaderModuleCreateInfo info = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + info.codeSize = code.size() * sizeof(uint32_t); + info.pCode = code.data(); + return dispatch.CreateShaderModule(device, &info, nullptr, &module); +} + +[[nodiscard]] static VkResult CreateGraphicsPipeline(VkDevice device, const VkuDeviceDispatchTable &dispatch, bool blend, + OverlayPipeline &pipeline) { + VkShaderModule vert = VK_NULL_HANDLE; + VkShaderModule frag = VK_NULL_HANDLE; + VkResult result = CreateShaderModule(device, dispatch, kMonitorOverlayVertSpirv, vert); + if (result == VK_SUCCESS) { + result = CreateShaderModule(device, dispatch, kMonitorOverlayFragSpirv, frag); + } + + if (result == VK_SUCCESS) { + std::array stages = {}; + stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + stages[0].module = vert; + stages[0].pName = "main"; + stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + stages[1].module = frag; + stages[1].pName = "main"; + + constexpr VkPipelineVertexInputStateCreateInfo vertex_input = {VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + VkPipelineInputAssemblyStateCreateInfo input_assembly = {VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; + input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; + VkPipelineViewportStateCreateInfo viewport = {VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + viewport.viewportCount = 1; + viewport.scissorCount = 1; + VkPipelineRasterizationStateCreateInfo rasterization = {VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; + rasterization.polygonMode = VK_POLYGON_MODE_FILL; + rasterization.cullMode = VK_CULL_MODE_NONE; + rasterization.lineWidth = 1.0f; + VkPipelineMultisampleStateCreateInfo multisample = {VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; + multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + // Alpha is never written, since it can control how the compositor blends the window. + VkPipelineColorBlendAttachmentState attachment = {}; + attachment.blendEnable = blend ? VK_TRUE : VK_FALSE; + attachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; + attachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + attachment.colorBlendOp = VK_BLEND_OP_ADD; + attachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; + attachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + attachment.alphaBlendOp = VK_BLEND_OP_ADD; + attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT; + VkPipelineColorBlendStateCreateInfo color_blend = {VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; + color_blend.attachmentCount = 1; + color_blend.pAttachments = &attachment; + + constexpr std::array dynamic_states = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic = {VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; + dynamic.dynamicStateCount = static_cast(dynamic_states.size()); + dynamic.pDynamicStates = dynamic_states.data(); + + VkGraphicsPipelineCreateInfo info = {VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; + info.stageCount = static_cast(stages.size()); + info.pStages = stages.data(); + info.pVertexInputState = &vertex_input; + info.pInputAssemblyState = &input_assembly; + info.pViewportState = &viewport; + info.pRasterizationState = &rasterization; + info.pMultisampleState = &multisample; + info.pColorBlendState = &color_blend; + info.pDynamicState = &dynamic; + info.layout = pipeline.layout; + info.renderPass = pipeline.render_pass; + result = dispatch.CreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline.pipeline); + } + + if (frag) { + dispatch.DestroyShaderModule(device, frag, nullptr); + } + if (vert) { + dispatch.DestroyShaderModule(device, vert, nullptr); + } + return result; +} + +VkResult CreateOverlayPipeline(VkDevice device, const VkuDeviceDispatchTable &dispatch, VkFormat format, bool blend, + OverlayPipeline &pipeline) { + pipeline = {}; + VkResult result = CreateRenderPass(device, dispatch, format, pipeline.render_pass); + + if (result == VK_SUCCESS) { + constexpr VkPushConstantRange range = {VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(OverlayPushConstants)}; + VkPipelineLayoutCreateInfo info = {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + info.pushConstantRangeCount = 1; + info.pPushConstantRanges = ⦥ + result = dispatch.CreatePipelineLayout(device, &info, nullptr, &pipeline.layout); + } + if (result == VK_SUCCESS) { + result = CreateGraphicsPipeline(device, dispatch, blend, pipeline); + } + + if (result != VK_SUCCESS) { + DestroyOverlayPipeline(device, dispatch, pipeline); + } + return result; +} + +void DestroyOverlayPipeline(VkDevice device, const VkuDeviceDispatchTable &dispatch, OverlayPipeline &pipeline) { + if (pipeline.pipeline) { + dispatch.DestroyPipeline(device, pipeline.pipeline, nullptr); + } + if (pipeline.layout) { + dispatch.DestroyPipelineLayout(device, pipeline.layout, nullptr); + } + if (pipeline.render_pass) { + dispatch.DestroyRenderPass(device, pipeline.render_pass, nullptr); + } + pipeline = {}; +} + +void RecordOverlay(const VkuDeviceDispatchTable &dispatch, VkCommandBuffer command_buffer, const OverlayPipeline &pipeline, + VkFramebuffer framebuffer, VkExtent2D image_extent, const Rect &panel, + const OverlayPushConstants &push_constants) { + // The render area and scissor must stay inside the framebuffer. + const int32_t x0 = std::max(panel[0], 0); + const int32_t y0 = std::max(panel[1], 0); + const int32_t x1 = std::min(panel[2], static_cast(image_extent.width)); + const int32_t y1 = std::min(panel[3], static_cast(image_extent.height)); + if (x1 <= x0 || y1 <= y0) { + return; + } + + // Only the panel is loaded and stored, which keeps the cost on tiled GPUs low. + const VkRect2D area = {{x0, y0}, {static_cast(x1 - x0), static_cast(y1 - y0)}}; + VkRenderPassBeginInfo begin = {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; + begin.renderPass = pipeline.render_pass; + begin.framebuffer = framebuffer; + begin.renderArea = area; + dispatch.CmdBeginRenderPass(command_buffer, &begin, VK_SUBPASS_CONTENTS_INLINE); + + const VkViewport viewport = {0.0f, 0.0f, static_cast(image_extent.width), static_cast(image_extent.height), + 0.0f, 1.0f}; + dispatch.CmdSetViewport(command_buffer, 0, 1, &viewport); + dispatch.CmdSetScissor(command_buffer, 0, 1, &area); + dispatch.CmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.pipeline); + dispatch.CmdPushConstants(command_buffer, pipeline.layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(push_constants), &push_constants); + dispatch.CmdDraw(command_buffer, 4, 1, 0, 0); + dispatch.CmdEndRenderPass(command_buffer); +} + +} // namespace monitor diff --git a/layersvt/monitor_renderer.h b/layersvt/monitor_renderer.h new file mode 100644 index 0000000000..1c7686543f --- /dev/null +++ b/layersvt/monitor_renderer.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "monitor_overlay.h" + +namespace monitor { + +// Draws the overlay into a color attachment that is in VK_IMAGE_LAYOUT_PRESENT_SRC_KHR before and after. +struct OverlayPipeline { + VkRenderPass render_pass = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; +}; + +// Without blending the panel is drawn opaque. Destroys anything it created if it fails. +[[nodiscard]] VkResult CreateOverlayPipeline(VkDevice device, const VkuDeviceDispatchTable &dispatch, VkFormat format, bool blend, + OverlayPipeline &pipeline); + +void DestroyOverlayPipeline(VkDevice device, const VkuDeviceDispatchTable &dispatch, OverlayPipeline &pipeline); + +// Records the overlay render pass. `framebuffer` holds one image view compatible with the pipeline's render pass, and +// `panel` is OverlayLayout::image_rect, clipped to the image. Nothing is recorded if that leaves it empty. +void RecordOverlay(const VkuDeviceDispatchTable &dispatch, VkCommandBuffer command_buffer, const OverlayPipeline &pipeline, + VkFramebuffer framebuffer, VkExtent2D image_extent, const Rect &panel, + const OverlayPushConstants &push_constants); + +} // namespace monitor diff --git a/layersvt/monitor_settings.cpp b/layersvt/monitor_settings.cpp new file mode 100644 index 0000000000..015a5731e2 --- /dev/null +++ b/layersvt/monitor_settings.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "monitor_settings.h" + +#include "monitor_overlay.h" + +namespace monitor { + +template +static void Read(VkuLayerSettingSet settings, const char *key, T &value) { + if (vkuHasLayerSetting(settings, key)) { + vkuGetLayerSettingValue(settings, key, value); + } +} + +RawSettings ReadRawSettings(VkuLayerSettingSet settings) { + RawSettings raw; + if (settings == VK_NULL_HANDLE) { + return raw; + } + Read(settings, "position", raw.position); + Read(settings, "scale", raw.scale); + Read(settings, "update_interval_ms", raw.update_interval_ms); + Read(settings, "show_fps", raw.show_fps); + Read(settings, "show_frame_time", raw.show_frame_time); + Read(settings, "show_frame_number", raw.show_frame_number); + Read(settings, "log_warnings", raw.log_warnings); + return raw; +} + +} // namespace monitor diff --git a/layersvt/monitor_settings.h b/layersvt/monitor_settings.h new file mode 100644 index 0000000000..258d44726a --- /dev/null +++ b/layersvt/monitor_settings.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#include "monitor_overlay.h" + +namespace monitor { + +// Reads the settings declared in VkLayer_monitor.json. Settings that aren't set, or a null setting set, give the defaults. +[[nodiscard]] RawSettings ReadRawSettings(VkuLayerSettingSet settings); + +} // namespace monitor diff --git a/layersvt/screenshot.cpp b/layersvt/screenshot.cpp index 16d5bea53a..26c2e685a5 100755 --- a/layersvt/screenshot.cpp +++ b/layersvt/screenshot.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -75,8 +76,9 @@ std::atomic_bool pauseCapture(false); enum class ColorSpaceFormat { UNDEFINED, UNORM, SNORM, USCALED, SSCALED, UINT, SINT, SRGB }; // unordered map: associates Vulkan dispatchable objects to a dispatch table +// The device's DeviceMapStruct owns it; the map only looks it up for the device and its queues. typedef struct { - VkuDeviceDispatchTable *device_dispatch_table; + std::unique_ptr device_dispatch_table; PFN_vkSetDeviceLoaderData pfn_dev_init; } DispatchMapStruct; static unordered_map dispatchMap; @@ -110,8 +112,9 @@ struct DeviceMapStruct { set queues; unordered_map queueIndexMap; VkPhysicalDevice physicalDevice; + std::unique_ptr dispatch; }; -static unordered_map deviceMap; +static unordered_map> deviceMap; // unordered map: associates a physical device with an instance typedef struct { @@ -382,6 +385,9 @@ static bool memory_type_from_properties(VkPhysicalDeviceMemoryProperties *memory return false; } +// Queues share their device's dispatch table, which dispatchMap finds by the queue's handle +static VkDevice QueueKey(VkQueue queue) { return reinterpret_cast(queue); } + static DispatchMapStruct *get_dispatch_info(VkDevice dev) { auto it = dispatchMap.find(dev); if (it == dispatchMap.end()) @@ -395,7 +401,7 @@ static DeviceMapStruct *get_device_info(VkDevice dev) { if (it == deviceMap.end()) return NULL; else - return it->second; + return it->second.get(); } void screenshotWriterThreadFunc(); @@ -801,9 +807,8 @@ bool prepareScreenshotData(ScreenshotQueueData &data, VkImage image1) { #endif return false; } - VkuDeviceDispatchTable *pTableDevice = dispMap->device_dispatch_table; - VkuDeviceDispatchTable *pTableQueue = - get_dispatch_info(static_cast(static_cast(queue)))->device_dispatch_table; + VkuDeviceDispatchTable *pTableDevice = dispMap->device_dispatch_table.get(); + const VkuDeviceDispatchTable *pTableQueue = get_dispatch_info(QueueKey(queue))->device_dispatch_table.get(); VkuInstanceDispatchTable *pInstanceTable; pInstanceTable = instance_dispatch_table(instance); @@ -1015,7 +1020,7 @@ bool prepareScreenshotData(ScreenshotQueueData &data, VkImage image1) { assert(!err); if (VK_SUCCESS != err) return false; - VkuDeviceDispatchTable *pTableCommandBuffer = dispMap->device_dispatch_table; + const VkuDeviceDispatchTable *pTableCommandBuffer = dispMap->device_dispatch_table.get(); // We have just created a dispatchable object, but the dispatch table has // not been placed in the object yet. When a "normal" application creates @@ -1218,8 +1223,7 @@ static bool queueScreenshot(ScreenshotQueueData &data, VkImage image1, const VkP return false; } - VkuDeviceDispatchTable *pTableQueue = - get_dispatch_info(static_cast(static_cast(queue)))->device_dispatch_table; + const VkuDeviceDispatchTable *pTableQueue = get_dispatch_info(QueueKey(queue))->device_dispatch_table.get(); VkResult err = pTableQueue->QueueSubmit(queue, 1, &submitInfo, data.fence); assert(!err); @@ -1357,7 +1361,7 @@ static void createDeviceRegisterExtensions(const VkDeviceCreateInfo *pCreateInfo uint32_t i; DispatchMapStruct *dispMap = get_dispatch_info(device); DeviceMapStruct *devMap = get_device_info(device); - VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table; + VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table.get(); PFN_vkGetDeviceProcAddr gpa = pDisp->GetDeviceProcAddr; pDisp->CreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)gpa(device, "vkCreateSwapchainKHR"); pDisp->GetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)gpa(device, "vkGetSwapchainImagesKHR"); @@ -1391,15 +1395,17 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice gpu, const VkDevice } assert(deviceMap.find(*pDevice) == deviceMap.end()); - DeviceMapStruct *deviceMapElem = new DeviceMapStruct; - deviceMap[*pDevice] = deviceMapElem; + std::unique_ptr &deviceMapEntry = deviceMap[*pDevice]; + deviceMapEntry = std::make_unique(); + DeviceMapStruct *deviceMapElem = deviceMapEntry.get(); assert(dispatchMap.find(*pDevice) == dispatchMap.end()); - DispatchMapStruct *dispatchMapElem = new DispatchMapStruct; + deviceMapElem->dispatch = std::make_unique(); + DispatchMapStruct *dispatchMapElem = deviceMapElem->dispatch.get(); dispatchMap[*pDevice] = dispatchMapElem; // Setup device dispatch table - dispatchMapElem->device_dispatch_table = new VkuDeviceDispatchTable; - vkuInitDeviceDispatchTable(*pDevice, dispatchMapElem->device_dispatch_table, fpGetDeviceProcAddr); + dispatchMapElem->device_dispatch_table = std::make_unique(); + vkuInitDeviceDispatchTable(*pDevice, dispatchMapElem->device_dispatch_table.get(), fpGetDeviceProcAddr); createDeviceRegisterExtensions(pCreateInfo, *pDevice); // Create a mapping from a device to a physicalDevice @@ -1451,22 +1457,22 @@ VKAPI_ATTR void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCall DeviceMapStruct *devMap = get_device_info(device); assert(dispMap); assert(devMap); - VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table; + const VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table.get(); pDisp->DestroyDevice(device, pAllocator); std::lock_guard lg(globalLock); - delete pDisp; - delete dispMap; - delete devMap; - - deviceMap.erase(device); + // The queues look up the device's dispatch table too, so they go before the device frees it + for (VkQueue queue : devMap->queues) { + dispatchMap.erase(QueueKey(queue)); + } dispatchMap.erase(device); + deviceMap.erase(device); } VKAPI_ATTR void VKAPI_CALL GetDeviceQueue(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue *pQueue) { DispatchMapStruct *dispMap = get_dispatch_info(device); assert(dispMap); - VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table; + const VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table.get(); pDisp->GetDeviceQueue(device, queueFamilyIndex, queueIndex, pQueue); // Save the device queue in a map if we are taking screenshots. @@ -1484,7 +1490,7 @@ VKAPI_ATTR void VKAPI_CALL GetDeviceQueue(VkDevice device, uint32_t queueFamilyI // queues are dispatchable objects. // Create dispatchMap entry with this queue as its key. // Copy the device dispatch table to the new dispatch table. - VkDevice que = static_cast(static_cast(*pQueue)); + VkDevice que = QueueKey(*pQueue); dispatchMap[que] = dispMap; } @@ -1496,7 +1502,7 @@ VKAPI_ATTR VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice device, const VkSwapc const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchain) { DispatchMapStruct *dispMap = get_dispatch_info(device); assert(dispMap); - VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table; + const VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table.get(); // This layer does an image copy later on, and the copy command expects the // transfer src bit to be on. @@ -1586,7 +1592,7 @@ VKAPI_ATTR void DestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, c DispatchMapStruct *dispMap = get_dispatch_info(device); assert(dispMap); - VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table; + const VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table.get(); pDisp->DestroySwapchainKHR(device, swapchain, pAllocator); } @@ -1594,7 +1600,7 @@ VKAPI_ATTR VkResult VKAPI_CALL GetSwapchainImagesKHR(VkDevice device, VkSwapchai VkImage *pSwapchainImages) { DispatchMapStruct *dispMap = get_dispatch_info(device); assert(dispMap); - VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table; + const VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table.get(); VkResult result = pDisp->GetSwapchainImagesKHR(device, swapchain, pCount, pSwapchainImages); return result; } @@ -1734,9 +1740,9 @@ void onQueuePresentKHR(VkQueue queue, VkPresentInfoKHR &presentInfo) { PROFILE_COUNTER("screenshot.QueueSize", screenshotsData.size()); startScreenshotThread(); #ifdef ANDROID - __android_log_print(ANDROID_LOG_INFO, "screenshot", "Queued screeshot for frame: %d", frameNumber); + __android_log_print(ANDROID_LOG_INFO, "screenshot", "Queued screenshot for frame: %d", frameNumber); #else - printf("screenshot: Queued screeshot for frame: %d\n", frameNumber); + printf("screenshot: Queued screenshot for frame: %d\n", frameNumber); fflush(stdout); #endif screenshotQueuedCV.notify_one(); @@ -1747,7 +1753,7 @@ VKAPI_ATTR VkResult VKAPI_CALL QueuePresentKHR(VkQueue queue, const VkPresentInf VkPresentInfoKHR presentInfo = *pPresentInfo; onQueuePresentKHR(queue, presentInfo); DispatchMapStruct *dispMap = get_dispatch_info((VkDevice)queue); - VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table; + const VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table.get(); assert(dispMap); VkResult result = pDisp->QueuePresentKHR(queue, &presentInfo); return result; @@ -1835,7 +1841,7 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL GetDeviceProcAddr(VkDevice dev, const c DispatchMapStruct *dispMap = get_dispatch_info(dev); assert(dispMap); - VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table; + const VkuDeviceDispatchTable *pDisp = dispMap->device_dispatch_table.get(); if (pDisp->GetDeviceProcAddr == NULL) return NULL; return pDisp->GetDeviceProcAddr(dev, funcName); diff --git a/layersvt/shaders/monitor_overlay.frag b/layersvt/shaders/monitor_overlay.frag new file mode 100644 index 0000000000..0f87fc53ad --- /dev/null +++ b/layersvt/shaders/monitor_overlay.frag @@ -0,0 +1,97 @@ +#version 450 +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Draws the monitor overlay text in white over a translucent black panel. +// After changing this file, run scripts/generate_monitor_shaders.py. + +// Must match OverlayPushConstants in monitor_overlay.h +layout(push_constant) uniform PushConstants { + ivec4 visible_rect; + uint visible_extent; + uint params; + float white; + uint reserved; + uint glyphs[24]; +} +pc; + +layout(location = 0) in vec2 in_panel; +layout(location = 0) out vec4 out_color; + +// Same 5x7 font as monitor_overlay.cpp, one row per value, top row first, bit 4 is the leftmost pixel +const uint kFont[161] = uint[]( + 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, // ' ' + 0x0Eu, 0x11u, 0x13u, 0x15u, 0x19u, 0x11u, 0x0Eu, // '0' + 0x04u, 0x0Cu, 0x04u, 0x04u, 0x04u, 0x04u, 0x0Eu, // '1' + 0x0Eu, 0x11u, 0x01u, 0x02u, 0x04u, 0x08u, 0x1Fu, // '2' + 0x1Fu, 0x02u, 0x04u, 0x02u, 0x01u, 0x11u, 0x0Eu, // '3' + 0x02u, 0x06u, 0x0Au, 0x12u, 0x1Fu, 0x02u, 0x02u, // '4' + 0x1Fu, 0x10u, 0x1Eu, 0x01u, 0x01u, 0x11u, 0x0Eu, // '5' + 0x06u, 0x08u, 0x10u, 0x1Eu, 0x11u, 0x11u, 0x0Eu, // '6' + 0x1Fu, 0x01u, 0x02u, 0x04u, 0x08u, 0x08u, 0x08u, // '7' + 0x0Eu, 0x11u, 0x11u, 0x0Eu, 0x11u, 0x11u, 0x0Eu, // '8' + 0x0Eu, 0x11u, 0x11u, 0x0Fu, 0x01u, 0x02u, 0x0Cu, // '9' + 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x0Cu, 0x0Cu, // '.' + 0x00u, 0x00u, 0x00u, 0x0Eu, 0x00u, 0x00u, 0x00u, // '-' + 0x02u, 0x04u, 0x08u, 0x08u, 0x08u, 0x04u, 0x02u, // '(' + 0x08u, 0x04u, 0x02u, 0x02u, 0x02u, 0x04u, 0x08u, // ')' + 0x1Fu, 0x10u, 0x10u, 0x1Eu, 0x10u, 0x10u, 0x10u, // 'F' + 0x1Eu, 0x11u, 0x11u, 0x1Eu, 0x10u, 0x10u, 0x10u, // 'P' + 0x0Fu, 0x10u, 0x10u, 0x0Eu, 0x01u, 0x01u, 0x1Eu, // 'S' + 0x00u, 0x00u, 0x0Eu, 0x01u, 0x0Fu, 0x11u, 0x0Fu, // 'a' + 0x00u, 0x00u, 0x0Eu, 0x11u, 0x1Fu, 0x10u, 0x0Eu, // 'e' + 0x00u, 0x00u, 0x1Au, 0x15u, 0x15u, 0x11u, 0x11u, // 'm' + 0x00u, 0x00u, 0x16u, 0x19u, 0x10u, 0x10u, 0x10u, // 'r' + 0x00u, 0x00u, 0x0Fu, 0x10u, 0x0Eu, 0x01u, 0x1Eu // 's' +); + +// Must match the panel metrics in monitor_overlay.cpp, in font pixels +const int kGlyphWidth = 5; +const int kGlyphHeight = 7; +const int kGlyphCount = 23; +const int kCharAdvance = 6; +const int kLineAdvance = 9; +const int kPadding = 3; +const int kMaxColumns = 32; + +void main() { + const uint pixel_size = pc.params & 0xFFu; + const int line_count = int((pc.params >> 10) & 0x3u); + const bool opaque = ((pc.params >> 12) & 0x1u) != 0u; + + out_color = vec4(0.0, 0.0, 0.0, opaque ? 1.0 : 0.6); + + const ivec2 font = ivec2(floor(in_panel / float(pixel_size))) - ivec2(kPadding); + if (font.x < 0 || font.y < 0) { + return; + } + + const int line = font.y / kLineAdvance; + const int column = font.x / kCharAdvance; + const int x = font.x % kCharAdvance; + const int y = font.y % kLineAdvance; + if (line >= line_count || column >= kMaxColumns || x >= kGlyphWidth || y >= kGlyphHeight) { + return; + } + + const uint index = uint(line * kMaxColumns + column); + const uint glyph = min((pc.glyphs[index / 4u] >> ((index % 4u) * 8u)) & 0xFFu, uint(kGlyphCount - 1)); + const uint row = kFont[glyph * uint(kGlyphHeight) + uint(y)]; + if (((row >> uint(kGlyphWidth - 1 - x)) & 1u) != 0u) { + out_color = vec4(pc.white, pc.white, pc.white, 1.0); + } +} diff --git a/layersvt/shaders/monitor_overlay.vert b/layersvt/shaders/monitor_overlay.vert new file mode 100644 index 0000000000..b197ebd8ca --- /dev/null +++ b/layersvt/shaders/monitor_overlay.vert @@ -0,0 +1,60 @@ +#version 450 +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Draws the monitor overlay panel as a 4 vertex triangle strip, with no vertex buffer. +// After changing this file, run scripts/generate_monitor_shaders.py. + +// Must match OverlayPushConstants in monitor_overlay.h +layout(push_constant) uniform PushConstants { + ivec4 visible_rect; + uint visible_extent; + uint params; + float white; + uint reserved; + uint glyphs[24]; +} +pc; + +// Position inside the panel, in visible (unrotated) pixels +layout(location = 0) out vec2 out_panel; + +void main() { + const vec2 corner = vec2(gl_VertexIndex & 1, gl_VertexIndex >> 1); + const vec2 visible = mix(vec2(pc.visible_rect.xy), vec2(pc.visible_rect.zw), corner); + const vec2 visible_extent = vec2(pc.visible_extent & 0xFFFFu, pc.visible_extent >> 16); + const uint rotation = (pc.params >> 8) & 0x3u; + + // Image content is the visible content rotated clockwise + vec2 image; + vec2 image_extent; + if (rotation == 1u) { + image = vec2(visible_extent.y - visible.y, visible.x); + image_extent = visible_extent.yx; + } else if (rotation == 2u) { + image = visible_extent - visible; + image_extent = visible_extent; + } else if (rotation == 3u) { + image = vec2(visible.y, visible_extent.x - visible.x); + image_extent = visible_extent.yx; + } else { + image = visible; + image_extent = visible_extent; + } + + out_panel = visible - vec2(pc.visible_rect.xy); + gl_Position = vec4(image / image_extent * 2.0 - 1.0, 0.0, 1.0); +} diff --git a/layersvt/test/CMakeLists.txt b/layersvt/test/CMakeLists.txt index 1519e12b48..bdd1065652 100644 --- a/layersvt/test/CMakeLists.txt +++ b/layersvt/test/CMakeLists.txt @@ -32,7 +32,7 @@ function(LayerTest NAME) layer_test_framework.cpp layer_test_framework.h) add_dependencies(${TEST_NAME} VkLayer_${NAME}) - target_link_libraries(${TEST_NAME} Vulkan::Headers Vulkan::Loader GTest::gtest GTest::gtest_main Vulkan::LayerSettings) + target_link_libraries(${TEST_NAME} Vulkan::Headers Vulkan::Loader GTest::gtest_main Vulkan::LayerSettings) target_compile_definitions(${TEST_NAME} PUBLIC LAYER_BINARY_PATH="$") add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME}) diff --git a/layersvt/test/layer_test_helper.cpp b/layersvt/test/layer_test_helper.cpp index 468797b6f4..2cffda3ec5 100644 --- a/layersvt/test/layer_test_helper.cpp +++ b/layersvt/test/layer_test_helper.cpp @@ -42,20 +42,6 @@ void layer_test::UnsetEnvironmentSetting(std::string setting) { #endif } -std::string layer_test::GetAbsolutePath(std::string filepath) { - std::string out; -#ifdef _WIN32 - char abs_path[_MAX_PATH]; - _fullpath(abs_path, filepath.c_str(), _MAX_PATH); - out = abs_path; -#else - char* abs_path = realpath(filepath.c_str(), nullptr); - out = abs_path; - delete[] abs_path; -#endif - return out; -} - VkApplicationInfo layer_test::GetDefaultApplicationInfo() { VkApplicationInfo out{VK_STRUCTURE_TYPE_APPLICATION_INFO}; out.apiVersion = VK_API_VERSION_1_3; diff --git a/layersvt/test/layer_test_helper.h b/layersvt/test/layer_test_helper.h index f1421dbb06..2008c2b518 100644 --- a/layersvt/test/layer_test_helper.h +++ b/layersvt/test/layer_test_helper.h @@ -48,8 +48,6 @@ inline std::string format(const char* message, ...) { void SetEnvironmentSetting(std::string setting, const char* val); void UnsetEnvironmentSetting(std::string setting); -std::string GetAbsolutePath(std::string filepath); - VkApplicationInfo GetDefaultApplicationInfo(); bool IsExtensionSupported(VkPhysicalDevice physical_device, const char* extension_name); diff --git a/layersvt/vk_layer_table.cpp b/layersvt/vk_layer_table.cpp index 8bd9b97e5f..766102dc33 100644 --- a/layersvt/vk_layer_table.cpp +++ b/layersvt/vk_layer_table.cpp @@ -18,6 +18,7 @@ * Author: Tobin Ehlis */ #include +#include #include #include "vulkan/vk_layer.h" #include "vk_layer_table.h" @@ -25,38 +26,32 @@ static device_table_map tableMap; static instance_table_map tableInstanceMap; -dispatch_key get_dispatch_key(const void *object) { return (dispatch_key) * (VkuDeviceDispatchTable **)object; } +// The loader stores its dispatch table pointer in the first bytes of every dispatchable object. It's copied out rather than +// read through a pointer cast, which would break C++'s aliasing rules. +dispatch_key get_dispatch_key(const void *object) { + dispatch_key key = nullptr; + std::memcpy(&key, object, sizeof(key)); + return key; +} // Map lookup must be thread safe VkuDeviceDispatchTable *device_dispatch_table(void *object) { dispatch_key key = get_dispatch_key(object); device_table_map::const_iterator it = tableMap.find((void *)key); assert(it != tableMap.end() && "Not able to find device dispatch entry"); - return it->second; + return it->second.get(); } VkuInstanceDispatchTable *instance_dispatch_table(void *object) { dispatch_key key = get_dispatch_key(object); instance_table_map::const_iterator it = tableInstanceMap.find((void *)key); assert(it != tableInstanceMap.end() && "Not able to find instance dispatch entry"); - return it->second; + return it->second.get(); } -void destroy_dispatch_table(device_table_map &map, dispatch_key key) { - device_table_map::const_iterator it = map.find((void *)key); - if (it != map.end()) { - delete it->second; - map.erase(it); - } -} +void destroy_dispatch_table(device_table_map &map, dispatch_key key) { map.erase(key); } -void destroy_dispatch_table(instance_table_map &map, dispatch_key key) { - instance_table_map::const_iterator it = map.find((void *)key); - if (it != map.end()) { - delete it->second; - map.erase(it); - } -} +void destroy_dispatch_table(instance_table_map &map, dispatch_key key) { map.erase(key); } void destroy_device_dispatch_table(dispatch_key key) { destroy_dispatch_table(tableMap, key); } @@ -66,30 +61,41 @@ VkuDeviceDispatchTable *get_dispatch_table(device_table_map &map, void *object) dispatch_key key = get_dispatch_key(object); device_table_map::const_iterator it = map.find((void *)key); assert(it != map.end() && "Not able to find device dispatch entry"); - return it->second; + return it->second.get(); } VkuInstanceDispatchTable *get_dispatch_table(instance_table_map &map, void *object) { dispatch_key key = get_dispatch_key(object); instance_table_map::const_iterator it = map.find((void *)key); assert(it != map.end() && "Not able to find instance dispatch entry"); - return it->second; + return it->second.get(); } -VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func) { - VkLayerInstanceCreateInfo *chain_info = (VkLayerInstanceCreateInfo *)pCreateInfo->pNext; - while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && chain_info->function == func)) { - chain_info = (VkLayerInstanceCreateInfo *)chain_info->pNext; +// The loader's struct of type `type` for `func` in a create info's pNext chain. The loader expects layers to change it, +// so the const of the chain is cast away. A struct is only accessed as a LayerCreateInfo once its sType says it is one. +template +static LayerCreateInfo *find_layer_create_info(const void *chain, VkStructureType type, VkLayerFunction func) { + for (const void *node = chain; node; node = read_chain_header(node).pNext) { + if (read_chain_header(node).sType == type) { + auto *info = static_cast(const_cast(node)); + if (info->function == func) { + return info; + } + } } + return nullptr; +} + +VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func) { + VkLayerInstanceCreateInfo *chain_info = + find_layer_create_info(pCreateInfo->pNext, VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, func); assert(chain_info != NULL); return chain_info; } VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func) { - VkLayerDeviceCreateInfo *chain_info = (VkLayerDeviceCreateInfo *)pCreateInfo->pNext; - while (chain_info && !(chain_info->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && chain_info->function == func)) { - chain_info = (VkLayerDeviceCreateInfo *)chain_info->pNext; - } + VkLayerDeviceCreateInfo *chain_info = + find_layer_create_info(pCreateInfo->pNext, VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, func); assert(chain_info != NULL); return chain_info; } @@ -102,20 +108,15 @@ VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, V * If use the object themselves as key to map then implies Create entrypoints have to be intercepted * and a new key inserted into map */ VkuInstanceDispatchTable *initInstanceTable(VkInstance instance, const PFN_vkGetInstanceProcAddr gpa, instance_table_map &map) { - VkuInstanceDispatchTable *pTable; - dispatch_key key = get_dispatch_key(instance); - instance_table_map::const_iterator it = map.find((void *)key); - - if (it == map.end()) { - pTable = new VkuInstanceDispatchTable; - map[(void *)key] = pTable; - } else { - // An entry already under this key can only be left over from an instance that is gone, since a - // live one has a key of its own. Returning it as it is would hand the new instance function - // pointers from the old one, into layers that may since have been unloaded, so it is initialised - // again instead. - pTable = it->second; + std::unique_ptr &table = map[get_dispatch_key(instance)]; + // An entry already under this key can only be left over from an instance that is gone, since a + // live one has a key of its own. Returning it as it is would hand the new instance function + // pointers from the old one, into layers that may since have been unloaded, so it is initialised + // again instead. + if (!table) { + table = std::make_unique(); } + VkuInstanceDispatchTable *pTable = table.get(); vkuInitInstanceDispatchTable(instance, pTable, gpa); @@ -131,18 +132,13 @@ VkuInstanceDispatchTable *initInstanceTable(VkInstance instance, const PFN_vkGet } VkuDeviceDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa, device_table_map &map) { - VkuDeviceDispatchTable *pTable; - dispatch_key key = get_dispatch_key(device); - device_table_map::const_iterator it = map.find((void *)key); - - if (it == map.end()) { - pTable = new VkuDeviceDispatchTable; - map[(void *)key] = pTable; - } else { - // See initInstanceTable: an existing entry is a stale one, and is initialised again rather - // than reused, so the new device never calls through the old device's function pointers. - pTable = it->second; + std::unique_ptr &table = map[get_dispatch_key(device)]; + // See initInstanceTable: an existing entry is a stale one, and is initialised again rather + // than reused, so the new device never calls through the old device's function pointers. + if (!table) { + table = std::make_unique(); } + VkuDeviceDispatchTable *pTable = table.get(); vkuInitDeviceDispatchTable(device, pTable, gpa); diff --git a/layersvt/vk_layer_table.h b/layersvt/vk_layer_table.h index fa1be9fbb3..49b35db75b 100644 --- a/layersvt/vk_layer_table.h +++ b/layersvt/vk_layer_table.h @@ -24,9 +24,10 @@ #include "vulkan/vulkan.h" #include #include +#include -typedef std::unordered_map device_table_map; -typedef std::unordered_map instance_table_map; +using device_table_map = std::unordered_map>; +using instance_table_map = std::unordered_map>; VkuDeviceDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa, device_table_map &map); VkuDeviceDispatchTable *initDeviceTable(VkDevice device, const PFN_vkGetDeviceProcAddr gpa); VkuInstanceDispatchTable *initInstanceTable(VkInstance instance, const PFN_vkGetInstanceProcAddr gpa, instance_table_map &map); @@ -47,28 +48,24 @@ VkuInstanceDispatchTable *get_dispatch_table(instance_table_map &map, void *obje VkLayerInstanceCreateInfo *get_chain_info(const VkInstanceCreateInfo *pCreateInfo, VkLayerFunction func); VkLayerDeviceCreateInfo *get_chain_info(const VkDeviceCreateInfo *pCreateInfo, VkLayerFunction func); +// The sType and pNext every struct in a pNext chain starts with. The structs aren't VkBaseInStructure objects, so reading +// them through a VkBaseInStructure pointer breaks C++'s aliasing rules. Copying the bytes out doesn't. +struct chain_header { + VkStructureType sType; + const void *pNext; +}; + +inline chain_header read_chain_header(const void *structure) { + VkBaseInStructure base; + std::memcpy(&base, structure, sizeof(base)); + return {base.sType, base.pNext}; +} + void destroy_device_dispatch_table(dispatch_key key); void destroy_instance_dispatch_table(dispatch_key key); void destroy_dispatch_table(device_table_map &map, dispatch_key key); void destroy_dispatch_table(instance_table_map &map, dispatch_key key); -// For the given data key, look up the layer_data instance from given layer_data_map -template -DATA_T *GetLayerDataPtr(void *data_key, std::unordered_map &layer_data_map) { - DATA_T *debug_data; - /* TODO: We probably should lock here, or have caller lock */ - auto got = layer_data_map.find(data_key); - - if (got == layer_data_map.end()) { - debug_data = new DATA_T; - layer_data_map[(void *)data_key] = debug_data; - } else { - debug_data = got->second; - } - - return debug_data; -} - inline VkResult util_GetExtensionProperties(const uint32_t count, const VkExtensionProperties *layer_extensions, uint32_t *pCount, VkExtensionProperties *pProperties) { if (pProperties == nullptr || layer_extensions == nullptr) { diff --git a/scripts/generate_monitor_shaders.py b/scripts/generate_monitor_shaders.py new file mode 100644 index 0000000000..322f2619c3 --- /dev/null +++ b/scripts/generate_monitor_shaders.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 LunarG, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Compiles the monitor layer overlay shaders to SPIR-V and writes them to +# layersvt/monitor_overlay_shaders.h. The header is checked in, so building the +# layer doesn't need glslang. Run this after changing layersvt/shaders/*. +# +# Usage: python3 scripts/generate_monitor_shaders.py [--glslang ] + +import argparse +import os +import shutil +import struct +import subprocess +import sys +import tempfile + +REPO_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) +SHADER_DIR = os.path.join(REPO_DIR, 'layersvt', 'shaders') +OUTPUT = os.path.join(REPO_DIR, 'layersvt', 'monitor_overlay_shaders.h') + +SHADERS = [ + ('monitor_overlay.vert', 'kMonitorOverlayVertSpirv'), + ('monitor_overlay.frag', 'kMonitorOverlayFragSpirv'), +] + +HEADER = '''\ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// *** THIS FILE IS GENERATED - DO NOT EDIT *** +// Generated by scripts/generate_monitor_shaders.py from layersvt/shaders +// {version} + +#pragma once + +#include +#include +''' + + +def find_glslang(path): + if path: + return path + found = shutil.which('glslangValidator') + if found: + return found + sdk = os.environ.get('VULKAN_SDK') + if sdk: + for name in ('glslangValidator', 'glslangValidator.exe'): + for bin_dir in ('Bin', 'bin'): + candidate = os.path.join(sdk, bin_dir, name) + if os.path.isfile(candidate): + return candidate + sys.exit('glslangValidator not found. Install the Vulkan SDK or pass --glslang.') + + +def glslang_version(glslang): + output = subprocess.run([glslang, '--version'], capture_output=True, text=True, check=True).stdout + lines = output.splitlines() + for line in lines: + if line.startswith('Glslang Version'): + return line.strip() + return lines[0].strip() if lines else 'Glslang Version: unknown' + + +def compile_shader(glslang, source, out_dir): + spv = os.path.join(out_dir, os.path.basename(source) + '.spv') + result = subprocess.run([glslang, '-V', '--target-env', 'vulkan1.0', source, '-o', spv], capture_output=True, text=True) + if result.returncode != 0: + sys.exit(result.stdout + result.stderr) + with open(spv, 'rb') as f: + data = f.read() + return struct.unpack('<%dI' % (len(data) // 4), data) + + +def source_hash(paths): + """FNV-1a over the shader sources with carriage returns dropped, so CRLF checkouts hash the same. + test_monitor_overlay recomputes it to catch shaders changed without regenerating this header.""" + value = 0xcbf29ce484222325 + for path in paths: + with open(path, 'rb') as f: + for byte in f.read().replace(b'\r', b''): + value = ((value ^ byte) * 0x100000001b3) & 0xFFFFFFFFFFFFFFFF + return value + + +def format_array(name, words): + lines = ['inline constexpr std::array %s = {' % (len(words), name)] + for i in range(0, len(words), 8): + lines.append(' ' + ', '.join('0x%08x' % w for w in words[i:i + 8]) + ',') + lines.append('};') + return '\n'.join(lines) + + +def main(): + parser = argparse.ArgumentParser(description='Generate the monitor layer overlay SPIR-V header.') + parser.add_argument('--glslang', help='Path to glslangValidator') + args = parser.parse_args() + + glslang = find_glslang(args.glslang) + parts = [HEADER.format(version=glslang_version(glslang))] + sources = [os.path.join(SHADER_DIR, source) for source, _ in SHADERS] + parts.append('// Hash of the shader sources this was generated from\ninline constexpr uint64_t kMonitorOverlayShaderSourceHash = 0x%016xull;\n' + % source_hash(sources)) + with tempfile.TemporaryDirectory() as out_dir: + for source, name in SHADERS: + words = compile_shader(glslang, os.path.join(SHADER_DIR, source), out_dir) + parts.append('// %s\n%s\n' % (source, format_array(name, words))) + + with open(OUTPUT, 'w', newline='\n') as f: + f.write('\n'.join(parts)) + + +if __name__ == '__main__': + main() diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ca4d291f77..0c2864ab12 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -4,3 +4,8 @@ if (WIN32) endif() execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different ${apidump_test_script} ${CMAKE_CURRENT_BINARY_DIR}) + +# Android builds can't run the tests +if (BUILD_MONITOR AND NOT ANDROID) + add_subdirectory(monitor) +endif() diff --git a/tests/monitor/CMakeLists.txt b/tests/monitor/CMakeLists.txt new file mode 100644 index 0000000000..94254a7d4c --- /dev/null +++ b/tests/monitor/CMakeLists.txt @@ -0,0 +1,35 @@ +# ~~~ +# Copyright (c) 2026 LunarG, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ~~~ + +# Unit tests of the monitor layer. They link the layer's static library and don't need a Vulkan driver, so they also run +# on GitHub's C.I. +set(LAYER_TEST_MAIN "${PROJECT_SOURCE_DIR}/layersvt/test/layer_test_main.cpp") + +function(MonitorTest NAME) + add_executable(${NAME} ${NAME}.cpp ${LAYER_TEST_MAIN}) + target_link_libraries(${NAME} VkLayer_monitor_core GTest::gtest) + add_test(NAME ${NAME} COMMAND ${NAME}) + set_target_properties(${NAME} PROPERTIES FOLDER "layers/monitor/Test") +endfunction() + +MonitorTest(test_monitor_overlay) +target_compile_definitions(test_monitor_overlay PRIVATE MONITOR_SHADER_DIR="${PROJECT_SOURCE_DIR}/layersvt/shaders") + +# Swapchain and present plumbing against a fake device +MonitorTest(test_monitor_present) + +# The layer's entry points, without a loader or driver +MonitorTest(test_monitor_entry_points) diff --git a/tests/monitor/test_monitor_entry_points.cpp b/tests/monitor/test_monitor_entry_points.cpp new file mode 100644 index 0000000000..d0cfa9e8ba --- /dev/null +++ b/tests/monitor/test_monitor_entry_points.cpp @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Tests what the layer's exported entry points return, without a Vulkan loader or driver. + +#include + +#include +#include +#include +#include +#include +#include + +#include "monitor_layer.h" +#include "vk_layer_table.h" + +namespace { + +TEST(MonitorEntryPoints, InstanceHooks) { + EXPECT_EQ(monitor::FindInstanceHook("vkGetInstanceProcAddr"), + reinterpret_cast(monitor::GetInstanceProcAddr)); + EXPECT_EQ(monitor::FindInstanceHook("vkEnumerateInstanceLayerProperties"), + reinterpret_cast(monitor::EnumerateInstanceLayerProperties)); + for (const std::string_view name : + {"vkCreateInstance", "vkDestroyInstance", "vkCreateDevice", "vkGetPhysicalDeviceToolPropertiesEXT", + "vkEnumerateDeviceLayerProperties", "vkEnumerateInstanceExtensionProperties", "vkEnumerateDeviceExtensionProperties"}) { + EXPECT_NE(monitor::FindInstanceHook(name), nullptr) << name; + } +} + +TEST(MonitorEntryPoints, OnlyExactNamesAreHooked) { + EXPECT_EQ(monitor::FindInstanceHook("vkCreateInstanceX"), nullptr); + EXPECT_EQ(monitor::FindInstanceHook("vkCreateInst"), nullptr); + EXPECT_EQ(monitor::FindInstanceHook(""), nullptr); + EXPECT_EQ(monitor::FindDeviceHook("vkQueuePresentKHR2", true), nullptr); +} + +// Device functions are only reached through vkGetDeviceProcAddr +TEST(MonitorEntryPoints, InstanceHooksLeaveDeviceFunctionsAlone) { + EXPECT_EQ(monitor::FindInstanceHook("vkQueuePresentKHR"), nullptr); + EXPECT_EQ(monitor::FindInstanceHook("vkCreateSwapchainKHR"), nullptr); +} + +TEST(MonitorEntryPoints, CoreDeviceFunctionsAreAlwaysHooked) { + EXPECT_EQ(monitor::FindDeviceHook("vkGetDeviceProcAddr", false), + reinterpret_cast(monitor::GetDeviceProcAddr)); + EXPECT_NE(monitor::FindDeviceHook("vkDestroyDevice", false), nullptr); + EXPECT_NE(monitor::FindDeviceHook("vkGetDeviceQueue", false), nullptr); +} + +// Hooking a function the device doesn't have would hand the application a function that calls null +TEST(MonitorEntryPoints, ExtensionFunctionsAreOnlyHookedWhenTheDeviceHasThem) { + for (const std::string_view name : {"vkGetDeviceQueue2", "vkQueuePresentKHR", "vkCreateSwapchainKHR", "vkDestroySwapchainKHR", + "vkCreateSharedSwapchainsKHR"}) { + EXPECT_EQ(monitor::FindDeviceHook(name, false), nullptr) << name; + EXPECT_NE(monitor::FindDeviceHook(name, true), nullptr) << name; + } +} + +TEST(MonitorEntryPoints, ProcAddrWithoutAHandle) { + EXPECT_EQ(monitor::GetInstanceProcAddr(VK_NULL_HANDLE, "vkCreateInstance"), monitor::FindInstanceHook("vkCreateInstance")); + EXPECT_EQ(monitor::GetInstanceProcAddr(VK_NULL_HANDLE, "vkCmdDraw"), nullptr); + EXPECT_EQ(monitor::GetDeviceProcAddr(VK_NULL_HANDLE, "vkDestroyDevice"), monitor::FindDeviceHook("vkDestroyDevice", false)); + EXPECT_EQ(monitor::GetDeviceProcAddr(VK_NULL_HANDLE, "vkQueuePresentKHR"), nullptr); +} + +TEST(MonitorEntryPoints, LayerProperties) { + uint32_t count = 0; + EXPECT_EQ(monitor::EnumerateInstanceLayerProperties(&count, nullptr), VK_SUCCESS); + ASSERT_EQ(count, 1u); + VkLayerProperties properties = {}; + EXPECT_EQ(monitor::EnumerateInstanceLayerProperties(&count, &properties), VK_SUCCESS); + EXPECT_EQ(properties.layerName, monitor::kLayerName); + + VkLayerProperties device_properties = {}; + EXPECT_EQ(monitor::EnumerateDeviceLayerProperties(VK_NULL_HANDLE, &count, &device_properties), VK_SUCCESS); + EXPECT_EQ(device_properties.layerName, monitor::kLayerName); +} + +TEST(MonitorEntryPoints, InstanceExtensions) { + const std::string layer_name(monitor::kLayerName); + uint32_t count = 0; + EXPECT_EQ(monitor::EnumerateInstanceExtensionProperties(layer_name.c_str(), &count, nullptr), VK_SUCCESS); + ASSERT_EQ(count, 1u); + VkExtensionProperties extension = {}; + EXPECT_EQ(monitor::EnumerateInstanceExtensionProperties(layer_name.c_str(), &count, &extension), VK_SUCCESS); + EXPECT_EQ(std::string_view(extension.extensionName), VK_EXT_LAYER_SETTINGS_EXTENSION_NAME); + + EXPECT_EQ(monitor::EnumerateInstanceExtensionProperties("VK_LAYER_KHRONOS_validation", &count, nullptr), + VK_ERROR_LAYER_NOT_PRESENT); + EXPECT_EQ(monitor::EnumerateInstanceExtensionProperties(nullptr, &count, nullptr), VK_ERROR_LAYER_NOT_PRESENT); +} + +TEST(MonitorEntryPoints, DeviceExtensions) { + const std::string layer_name(monitor::kLayerName); + uint32_t count = 0; + EXPECT_EQ(monitor::EnumerateDeviceExtensionProperties(VK_NULL_HANDLE, layer_name.c_str(), &count, nullptr), VK_SUCCESS); + ASSERT_EQ(count, 1u); + // The layer's vkGetPhysicalDeviceToolPropertiesEXT, which loaders without a layer manifest only find out about here + VkExtensionProperties extension = {}; + EXPECT_EQ(monitor::EnumerateDeviceExtensionProperties(VK_NULL_HANDLE, layer_name.c_str(), &count, &extension), VK_SUCCESS); + EXPECT_EQ(std::string_view(extension.extensionName), VK_EXT_TOOLING_INFO_EXTENSION_NAME); + + // Without a physical device there is no driver to ask + EXPECT_EQ(monitor::EnumerateDeviceExtensionProperties(VK_NULL_HANDLE, nullptr, &count, nullptr), VK_ERROR_LAYER_NOT_PRESENT); +} + +// The next layer or driver, with two tools +VKAPI_ATTR VkResult VKAPI_CALL NextTools(VkPhysicalDevice /*physical_device*/, uint32_t* count, + VkPhysicalDeviceToolPropertiesEXT* tools) { + constexpr uint32_t kNextTools = 2; + if (tools == nullptr) { + *count = kNextTools; + return VK_SUCCESS; + } + const uint32_t written = std::min(*count, kNextTools); + for (uint32_t i = 0; i < written; ++i) { + tools[i] = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES_EXT}; + (void)snprintf(tools[i].name, sizeof(tools[i].name), "next %u", i); + } + *count = written; + return written < kNextTools ? VK_INCOMPLETE : VK_SUCCESS; +} + +VkPhysicalDeviceToolPropertiesEXT Tool(const char* name) { + VkPhysicalDeviceToolPropertiesEXT tool = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TOOL_PROPERTIES_EXT}; + (void)snprintf(tool.name, sizeof(tool.name), "%s", name); + return tool; +} + +TEST(MonitorEntryPoints, ToolCountIncludesTheLayer) { + uint32_t count = 0; + EXPECT_EQ(monitor::PrependToolProperties(Tool("monitor"), VK_NULL_HANDLE, NextTools, &count, nullptr), VK_SUCCESS); + EXPECT_EQ(count, 3u); + EXPECT_EQ(monitor::PrependToolProperties(Tool("monitor"), VK_NULL_HANDLE, nullptr, &count, nullptr), VK_SUCCESS); + EXPECT_EQ(count, 1u); +} + +TEST(MonitorEntryPoints, ToolsFitInTheApplicationsArray) { + std::array tools = {Tool("unwritten"), Tool("unwritten"), Tool("unwritten")}; + + // An empty array is valid, and has no room for any tool + uint32_t count = 0; + EXPECT_EQ(monitor::PrependToolProperties(Tool("monitor"), VK_NULL_HANDLE, NextTools, &count, tools.data()), VK_INCOMPLETE); + EXPECT_EQ(count, 0u); + EXPECT_EQ(std::string_view(tools[0].name), "unwritten"); + + // Room for the layer's tool only + count = 1; + EXPECT_EQ(monitor::PrependToolProperties(Tool("monitor"), VK_NULL_HANDLE, NextTools, &count, tools.data()), VK_INCOMPLETE); + EXPECT_EQ(count, 1u); + EXPECT_EQ(std::string_view(tools[0].name), "monitor"); + EXPECT_EQ(std::string_view(tools[1].name), "unwritten"); + + // Room for one of the next tools + count = 2; + EXPECT_EQ(monitor::PrependToolProperties(Tool("monitor"), VK_NULL_HANDLE, NextTools, &count, tools.data()), VK_INCOMPLETE); + EXPECT_EQ(count, 2u); + EXPECT_EQ(std::string_view(tools[1].name), "next 0"); + + count = 3; + EXPECT_EQ(monitor::PrependToolProperties(Tool("monitor"), VK_NULL_HANDLE, NextTools, &count, tools.data()), VK_SUCCESS); + EXPECT_EQ(count, 3u); + EXPECT_EQ(std::string_view(tools[0].name), "monitor"); + EXPECT_EQ(std::string_view(tools[2].name), "next 1"); +} + +TEST(MonitorEntryPoints, ToolsWithoutANextFunction) { + VkPhysicalDeviceToolPropertiesEXT tool = Tool("unwritten"); + uint32_t count = 1; + EXPECT_EQ(monitor::PrependToolProperties(Tool("monitor"), VK_NULL_HANDLE, nullptr, &count, &tool), VK_SUCCESS); + EXPECT_EQ(count, 1u); + EXPECT_EQ(std::string_view(tool.name), "monitor"); +} + +// The loader's link info can come after structs of other types, which must only be read as what they are +TEST(MonitorEntryPoints, ChainInfoIsFoundBehindOtherStructs) { + VkLayerInstanceLink link = {}; + VkLayerInstanceCreateInfo loader_data = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO}; + loader_data.function = VK_LOADER_DATA_CALLBACK; + VkLayerInstanceCreateInfo link_info = {VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO, &loader_data}; + link_info.function = VK_LAYER_LINK_INFO; + link_info.u.pLayerInfo = &link; + VkLayerSettingsCreateInfoEXT settings = {VK_STRUCTURE_TYPE_LAYER_SETTINGS_CREATE_INFO_EXT, &link_info}; + VkInstanceCreateInfo create_info = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, &settings}; + + EXPECT_EQ(get_chain_info(&create_info, VK_LAYER_LINK_INFO), &link_info); + EXPECT_EQ(get_chain_info(&create_info, VK_LOADER_DATA_CALLBACK), &loader_data); + + const chain_header header = read_chain_header(&settings); + EXPECT_EQ(header.sType, VK_STRUCTURE_TYPE_LAYER_SETTINGS_CREATE_INFO_EXT); + EXPECT_EQ(header.pNext, &link_info); +} + +// The loader puts its dispatch table pointer at the start of every dispatchable object +TEST(MonitorEntryPoints, DispatchKeyIsTheLoadersDispatchPointer) { + int dispatch_table = 0; + void* object = &dispatch_table; + EXPECT_EQ(get_dispatch_key(&object), &dispatch_table); +} + +} // namespace diff --git a/tests/monitor/test_monitor_overlay.cpp b/tests/monitor/test_monitor_overlay.cpp new file mode 100644 index 0000000000..d8f1c284d7 --- /dev/null +++ b/tests/monitor/test_monitor_overlay.cpp @@ -0,0 +1,780 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "monitor_overlay.h" +#include "monitor_overlay_shaders.h" +#include "monitor_settings.h" + +using namespace std::chrono_literals; +using Clock = std::chrono::steady_clock; + +// Feeds `count` presents spaced `delta` apart, starting at `start`. Returns the time of the last present. +static Clock::time_point Present(monitor::FrameStats& stats, Clock::time_point start, Clock::duration delta, int count, + std::chrono::milliseconds interval = 500ms) { + Clock::time_point now = start; + for (int i = 0; i < count; ++i) { + monitor::RecordPresent(stats, now, interval); + now += delta; + } + return now - delta; +} + +TEST(MonitorOverlay, StatsAt144HzAfterFirstInterval) { + monitor::FrameStats stats; + const auto delta = std::chrono::duration_cast(std::chrono::duration(1.0 / 144.0)); + + Present(stats, Clock::time_point{}, delta, 10); + EXPECT_FALSE(stats.snapshot.valid); + + Present(stats, Clock::time_point{} + 10 * delta, delta, 144); + ASSERT_TRUE(stats.snapshot.valid); + EXPECT_NEAR(stats.snapshot.fps, 144.0, 0.5); + EXPECT_NEAR(stats.snapshot.avg_ms, 1000.0 / 144.0, 0.01); +} + +TEST(MonitorOverlay, StatsUseSubSecondIntervals) { + // A one-second clock would report 0 or a whole number of frames here. + monitor::FrameStats stats; + const auto delta = std::chrono::duration_cast(std::chrono::duration(1.0 / 60.0)); + + Present(stats, Clock::time_point{}, delta, 17, 250ms); + ASSERT_TRUE(stats.snapshot.valid); + EXPECT_NEAR(stats.snapshot.fps, 60.0, 0.1); +} + +TEST(MonitorOverlay, StatsReportHitchAsMaxFrameTime) { + monitor::FrameStats stats; + const auto delta = std::chrono::duration_cast(std::chrono::duration(1.0 / 60.0)); + + Clock::time_point last = Present(stats, Clock::time_point{}, delta, 10, 2000ms); + last = Present(stats, last + 1000ms, delta, 120, 2000ms); + + ASSERT_TRUE(stats.snapshot.valid); + EXPECT_NEAR(stats.snapshot.max_ms, 1000.0, 0.01); + EXPECT_NEAR(stats.snapshot.min_ms, 1000.0 / 60.0, 0.01); + EXPECT_GT(stats.snapshot.avg_ms, 1000.0 / 60.0); +} + +TEST(MonitorOverlay, FrameNumbersStartAtZero) { + std::atomic counter{0}; + EXPECT_EQ(monitor::NextFrameNumber(counter), 0u); + EXPECT_EQ(monitor::NextFrameNumber(counter), 1u); + EXPECT_EQ(monitor::NextFrameNumber(counter), 2u); +} + +TEST(MonitorOverlay, FrameNumbersAreUniqueAcrossThreads) { + std::atomic counter{0}; + constexpr int kPerThread = 10000; + std::vector first_frames; + std::vector second_frames; + first_frames.reserve(kPerThread); + second_frames.reserve(kPerThread); + + std::thread first_thread([&] { + for (int i = 0; i < kPerThread; ++i) { + first_frames.push_back(monitor::NextFrameNumber(counter)); + } + }); + std::thread second_thread([&] { + for (int i = 0; i < kPerThread; ++i) { + second_frames.push_back(monitor::NextFrameNumber(counter)); + } + }); + first_thread.join(); + second_thread.join(); + + std::set all(first_frames.begin(), first_frames.end()); + all.insert(second_frames.begin(), second_frames.end()); + EXPECT_EQ(all.size(), 2u * kPerThread); + EXPECT_EQ(*all.rbegin(), (2u * kPerThread) - 1); +} + +namespace { +struct GlyphArt { + char character; + const char* rows[monitor::kGlyphHeight]; +}; +} // namespace + +constexpr GlyphArt kExpectedGlyphs[] = { + {' ', {".....", ".....", ".....", ".....", ".....", ".....", "....."}}, + {'0', {".###.", "#...#", "#..##", "#.#.#", "##..#", "#...#", ".###."}}, + {'1', {"..#..", ".##..", "..#..", "..#..", "..#..", "..#..", ".###."}}, + {'2', {".###.", "#...#", "....#", "...#.", "..#..", ".#...", "#####"}}, + {'3', {"#####", "...#.", "..#..", "...#.", "....#", "#...#", ".###."}}, + {'4', {"...#.", "..##.", ".#.#.", "#..#.", "#####", "...#.", "...#."}}, + {'5', {"#####", "#....", "####.", "....#", "....#", "#...#", ".###."}}, + {'6', {"..##.", ".#...", "#....", "####.", "#...#", "#...#", ".###."}}, + {'7', {"#####", "....#", "...#.", "..#..", ".#...", ".#...", ".#..."}}, + {'8', {".###.", "#...#", "#...#", ".###.", "#...#", "#...#", ".###."}}, + {'9', {".###.", "#...#", "#...#", ".####", "....#", "...#.", ".##.."}}, + {'.', {".....", ".....", ".....", ".....", ".....", ".##..", ".##.."}}, + {'-', {".....", ".....", ".....", ".###.", ".....", ".....", "....."}}, + {'(', {"...#.", "..#..", ".#...", ".#...", ".#...", "..#..", "...#."}}, + {')', {".#...", "..#..", "...#.", "...#.", "...#.", "..#..", ".#..."}}, + {'F', {"#####", "#....", "#....", "####.", "#....", "#....", "#...."}}, + {'P', {"####.", "#...#", "#...#", "####.", "#....", "#....", "#...."}}, + {'S', {".####", "#....", "#....", ".###.", "....#", "....#", "####."}}, + {'a', {".....", ".....", ".###.", "....#", ".####", "#...#", ".####"}}, + {'e', {".....", ".....", ".###.", "#...#", "#####", "#....", ".###."}}, + {'m', {".....", ".....", "##.#.", "#.#.#", "#.#.#", "#...#", "#...#"}}, + {'r', {".....", ".....", "#.##.", "##..#", "#....", "#....", "#...."}}, + {'s', {".....", ".....", ".####", "#....", ".###.", "....#", "####."}}, +}; + +static std::string GlyphRowArt(uint8_t glyph, int row) { + std::string art; + const uint8_t bits = monitor::GlyphRow(glyph, row); + for (int x = 0; x < monitor::kGlyphWidth; ++x) { + art += ((bits & (1u << (monitor::kGlyphWidth - 1 - x))) != 0u) ? '#' : '.'; + } + return art; +} + +TEST(MonitorOverlay, FontDrawsEveryGlyph) { + std::set indices; + for (const GlyphArt& expected : kExpectedGlyphs) { + const uint8_t glyph = monitor::GlyphIndex(expected.character); + indices.insert(glyph); + for (int row = 0; row < monitor::kGlyphHeight; ++row) { + EXPECT_EQ(GlyphRowArt(glyph, row), expected.rows[row]) << "glyph '" << expected.character << "' row " << row; + } + } + EXPECT_EQ(indices.size(), std::size(kExpectedGlyphs)); + EXPECT_EQ(static_cast(monitor::kGlyphCount), std::size(kExpectedGlyphs)); +} + +TEST(MonitorOverlay, FontDrawsUnknownCharactersBlank) { + EXPECT_EQ(monitor::GlyphIndex('?'), monitor::GlyphIndex(' ')); + EXPECT_EQ(monitor::GlyphIndex('Z'), monitor::GlyphIndex(' ')); + EXPECT_EQ(monitor::GlyphIndex('\0'), monitor::GlyphIndex(' ')); +} + +static monitor::StatsSnapshot Snapshot(double fps, double avg_ms, double min_ms, double max_ms) { + monitor::StatsSnapshot snapshot; + snapshot.valid = true; + snapshot.fps = fps; + snapshot.avg_ms = avg_ms; + snapshot.min_ms = min_ms; + snapshot.max_ms = max_ms; + return snapshot; +} + +TEST(MonitorOverlay, TextShowsAllLines) { + const auto lines = monitor::FormatOverlayLines(Snapshot(143.24, 6.981, 6.1, 9.4), 123456, monitor::LineFlags{}); + const std::vector expected = {"FPS 143.2", "6.98 ms (6.10-9.40)", "Frame 123456"}; + EXPECT_EQ(lines, expected); +} + +TEST(MonitorOverlay, TextShowsPlaceholdersBeforeFirstInterval) { + const auto lines = monitor::FormatOverlayLines(monitor::StatsSnapshot{}, 0, monitor::LineFlags{}); + const std::vector expected = {"FPS -", "- ms", "Frame 0"}; + EXPECT_EQ(lines, expected); +} + +TEST(MonitorOverlay, TextOmitsHiddenLines) { + monitor::LineFlags flags; + flags.fps = false; + flags.frame_time = false; + EXPECT_EQ(monitor::FormatOverlayLines(Snapshot(60, 16.67, 16, 17), 42, flags), std::vector{"Frame 42"}); + + flags = monitor::LineFlags{}; + flags.frame_number = false; + EXPECT_EQ(monitor::FormatOverlayLines(Snapshot(60, 16.67, 16, 17), 42, flags).size(), 2u); + + flags.fps = false; + flags.frame_time = false; + EXPECT_TRUE(monitor::FormatOverlayLines(Snapshot(60, 16.67, 16, 17), 42, flags).empty()); +} + +static const std::vector kThreeLines = {"FPS 143.2", "6.98 ms (6.10-9.40)", "Frame 123456"}; + +TEST(MonitorOverlay, LayoutTopLeftAtDefaultScale) { + const auto layout = monitor::ComputeOverlayLayout({1920, 1080}, monitor::Position::TopLeft, 100, + VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, kThreeLines); + // 2 image pixels per font pixel, 4 font pixels of margin, 19 characters by 3 lines plus padding. + EXPECT_EQ(layout.pixel_size, 2u); + EXPECT_EQ(layout.visible_rect, (monitor::Rect{8, 8, 8 + 238, 8 + 62})); + EXPECT_EQ(layout.image_rect, layout.visible_rect); + EXPECT_EQ(layout.rotation, 0u); + EXPECT_FALSE(layout.transform_warning); +} + +TEST(MonitorOverlay, LayoutPlacesEachCorner) { + constexpr VkExtent2D extent = {1920, 1080}; + const auto top_left = + monitor::ComputeOverlayLayout(extent, monitor::Position::TopLeft, 100, VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, kThreeLines); + const int32_t w = top_left.visible_rect[2] - top_left.visible_rect[0]; + const int32_t h = top_left.visible_rect[3] - top_left.visible_rect[1]; + + const auto top_right = + monitor::ComputeOverlayLayout(extent, monitor::Position::TopRight, 100, VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, kThreeLines); + EXPECT_EQ(top_right.visible_rect, (monitor::Rect{1920 - 8 - w, 8, 1920 - 8, 8 + h})); + + const auto bottom_left = monitor::ComputeOverlayLayout(extent, monitor::Position::BottomLeft, 100, + VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, kThreeLines); + EXPECT_EQ(bottom_left.visible_rect, (monitor::Rect{8, 1080 - 8 - h, 8 + w, 1080 - 8})); + + const auto bottom_right = monitor::ComputeOverlayLayout(extent, monitor::Position::BottomRight, 100, + VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, kThreeLines); + EXPECT_EQ(bottom_right.visible_rect, (monitor::Rect{1920 - 8 - w, 1080 - 8 - h, 1920 - 8, 1080 - 8})); +} + +TEST(MonitorOverlay, LayoutClampsScale) { + const auto layout = [](int scale) { + return monitor::ComputeOverlayLayout({1920, 1080}, monitor::Position::TopLeft, scale, VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, + kThreeLines); + }; + EXPECT_EQ(layout(10).pixel_size, 1u); + EXPECT_EQ(layout(50).pixel_size, 1u); + EXPECT_EQ(layout(75).pixel_size, 2u); + EXPECT_EQ(layout(200).pixel_size, 4u); + EXPECT_EQ(layout(400).pixel_size, 8u); + EXPECT_EQ(layout(1000).pixel_size, 8u); +} + +TEST(MonitorOverlay, LayoutGrowsWithResolution) { + const auto pixel_size = [](VkExtent2D extent, int scale, VkSurfaceTransformFlagBitsKHR transform) { + return monitor::ComputeOverlayLayout(extent, monitor::Position::TopLeft, scale, transform, kThreeLines).pixel_size; + }; + const VkSurfaceTransformFlagBitsKHR identity = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + EXPECT_EQ(pixel_size({500, 500}, 100, identity), 2u); + EXPECT_EQ(pixel_size({1920, 1080}, 100, identity), 2u); + EXPECT_EQ(pixel_size({3072, 1728}, 100, identity), 3u); + EXPECT_EQ(pixel_size({3840, 2160}, 100, identity), 4u); + + // The shorter side counts, so a tall portrait image doesn't get huge text + EXPECT_EQ(pixel_size({1080, 2400}, 100, identity), 2u); + EXPECT_EQ(pixel_size({1080, 2400}, 100, VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR), 2u); + + // The scale setting applies on top + EXPECT_EQ(pixel_size({1920, 1080}, 50, identity), 1u); + EXPECT_EQ(pixel_size({3840, 2160}, 200, identity), 8u); +} + +TEST(MonitorOverlay, LayoutStaysOnScreenWhenPanelIsTooBig) { + const auto layout = monitor::ComputeOverlayLayout({64, 32}, monitor::Position::BottomRight, 400, + VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, kThreeLines); + EXPECT_GE(layout.visible_rect[0], 0); + EXPECT_GE(layout.visible_rect[1], 0); +} + +TEST(MonitorOverlay, LayoutClipsPanelToTheImage) { + // The image rect becomes a scissor, which must stay inside the image. + for (const VkSurfaceTransformFlagBitsKHR transform : + {VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR, VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR, + VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR}) { + constexpr VkExtent2D image = {48, 100}; + const auto layout = monitor::ComputeOverlayLayout(image, monitor::Position::TopLeft, 400, transform, kThreeLines); + EXPECT_LE(layout.visible_rect[2], static_cast(layout.visible_extent.width)) << transform; + EXPECT_LE(layout.visible_rect[3], static_cast(layout.visible_extent.height)) << transform; + EXPECT_GE(layout.image_rect[0], 0) << transform; + EXPECT_GE(layout.image_rect[1], 0) << transform; + EXPECT_LE(layout.image_rect[2], static_cast(image.width)) << transform; + EXPECT_LE(layout.image_rect[3], static_cast(image.height)) << transform; + } +} + +// Image content is the visible content rotated clockwise by the swapchain's preTransform. +TEST(MonitorOverlay, LayoutRotatesIntoImageSpace) { + struct Case { + VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + uint32_t rotation = 0; + monitor::Rect image_rect = {}; + }; + // Portrait-native 1080x2400 image shown in landscape; visible panel is {8, 8, 246, 70}. + const Case cases[] = { + {VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR, 1, {1080 - 70, 8, 1080 - 8, 246}}, + {VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR, 3, {8, 2400 - 246, 70, 2400 - 8}}, + }; + for (const Case& test_case : cases) { + const auto layout = + monitor::ComputeOverlayLayout({1080, 2400}, monitor::Position::TopLeft, 100, test_case.transform, kThreeLines); + EXPECT_EQ(layout.visible_extent.width, 2400u); + EXPECT_EQ(layout.visible_extent.height, 1080u); + EXPECT_EQ(layout.visible_rect, (monitor::Rect{8, 8, 246, 70})); + EXPECT_EQ(layout.rotation, test_case.rotation); + EXPECT_EQ(layout.image_rect, test_case.image_rect); + EXPECT_FALSE(layout.transform_warning); + } + + const auto upside_down = monitor::ComputeOverlayLayout({1920, 1080}, monitor::Position::TopLeft, 100, + VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR, kThreeLines); + EXPECT_EQ(upside_down.rotation, 2u); + EXPECT_EQ(upside_down.image_rect, (monitor::Rect{1920 - 246, 1080 - 70, 1920 - 8, 1080 - 8})); +} + +TEST(MonitorOverlay, LayoutDrawsMirrorAndInheritTransformsUnmirrored) { + struct Case { + VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + uint32_t rotation = 0; + }; + const Case cases[] = { + {VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR, 0}, + {VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR, 1}, + {VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR, 2}, + {VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR, 3}, + {VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR, 0}, + }; + for (const Case& test_case : cases) { + const auto layout = + monitor::ComputeOverlayLayout({1920, 1080}, monitor::Position::TopLeft, 100, test_case.transform, kThreeLines); + EXPECT_EQ(layout.rotation, test_case.rotation) << test_case.transform; + EXPECT_TRUE(layout.transform_warning) << test_case.transform; + } +} + +// Glyph k of line i is byte (i * kMaxColumns + k) of glyphs[], little-endian within each uint32_t. +static uint8_t PackedGlyph(const monitor::OverlayPushConstants& push_constants, uint32_t line, uint32_t column) { + const uint32_t byte = (line * monitor::kMaxColumns) + column; + return static_cast(push_constants.glyphs[byte / 4] >> ((byte % 4) * 8)); +} + +TEST(MonitorOverlay, PushConstantsFitTheGuaranteedLimit) { EXPECT_EQ(sizeof(monitor::OverlayPushConstants), 128u); } + +TEST(MonitorOverlay, PushConstantsEncodeLayout) { + const auto layout = monitor::ComputeOverlayLayout({1080, 2400}, monitor::Position::TopLeft, 200, + VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR, kThreeLines); + const auto push_constants = monitor::PackOverlayPushConstants(layout, kThreeLines, 2.5f, true); + + EXPECT_EQ(push_constants.visible_rect, layout.visible_rect); + EXPECT_EQ(push_constants.visible_extent & 0xFFFF, 2400u); + EXPECT_EQ(push_constants.visible_extent >> 16, 1080u); + EXPECT_EQ(push_constants.params & 0xFF, 4u); // pixel size + EXPECT_EQ((push_constants.params >> 8) & 0x3, 1u); // rotation + EXPECT_EQ((push_constants.params >> 10) & 0x3, 3u); // line count + EXPECT_EQ((push_constants.params >> 12) & 0x1, 1u); // opaque + EXPECT_FLOAT_EQ(push_constants.white, 2.5f); + + const auto blended = monitor::PackOverlayPushConstants(layout, kThreeLines, 1.0f, false); + EXPECT_EQ((blended.params >> 12) & 0x1, 0u); +} + +TEST(MonitorOverlay, PushConstantsEncodeGlyphs) { + const auto layout = monitor::ComputeOverlayLayout({1920, 1080}, monitor::Position::TopLeft, 100, + VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, kThreeLines); + const auto push_constants = monitor::PackOverlayPushConstants(layout, kThreeLines, 1.0f, false); + + for (uint32_t line = 0; line < kThreeLines.size(); ++line) { + for (uint32_t column = 0; column < monitor::kMaxColumns; ++column) { + const char expected = column < kThreeLines[line].size() ? kThreeLines[line][column] : ' '; + EXPECT_EQ(PackedGlyph(push_constants, line, column), monitor::GlyphIndex(expected)) + << "line " << line << " column " << column; + } + } +} + +TEST(MonitorOverlay, PushConstantsTruncateLongText) { + const std::vector lines = {std::string(40, '1'), "2", "3", "4"}; + const auto layout = + monitor::ComputeOverlayLayout({1920, 1080}, monitor::Position::TopLeft, 100, VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, lines); + const auto push_constants = monitor::PackOverlayPushConstants(layout, lines, 1.0f, false); + + EXPECT_EQ((push_constants.params >> 10) & 0x3, 3u); + EXPECT_EQ(PackedGlyph(push_constants, 0, monitor::kMaxColumns - 1), monitor::GlyphIndex('1')); + EXPECT_EQ(PackedGlyph(push_constants, 1, 0), monitor::GlyphIndex('2')); + EXPECT_EQ(PackedGlyph(push_constants, 2, 0), monitor::GlyphIndex('3')); + + // The panel is sized for the text that is actually drawn. + const std::vector drawn = {std::string(monitor::kMaxColumns, '1'), "2", "3"}; + const auto drawn_layout = + monitor::ComputeOverlayLayout({1920, 1080}, monitor::Position::TopLeft, 100, VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, drawn); + EXPECT_EQ(layout.visible_rect, drawn_layout.visible_rect); +} + +TEST(MonitorOverlay, WhiteIsOneForSdrColorSpaces) { + constexpr VkColorSpaceKHR sdr[] = { + VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT, VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT, + VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT, VK_COLOR_SPACE_BT709_LINEAR_EXT, VK_COLOR_SPACE_BT709_NONLINEAR_EXT, + VK_COLOR_SPACE_BT2020_LINEAR_EXT, VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT, VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT, + VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT, + }; + for (const VkColorSpaceKHR color_space : sdr) { + const auto white = monitor::WhiteForColorSpace(color_space); + EXPECT_FLOAT_EQ(white.value, 1.0f) << color_space; + EXPECT_TRUE(white.known) << color_space; + } +} + +TEST(MonitorOverlay, WhiteIsAbout200NitsForHdrColorSpaces) { + const auto scrgb = monitor::WhiteForColorSpace(VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT); + EXPECT_FLOAT_EQ(scrgb.value, 2.5f); // 1.0 is 80 nits + EXPECT_TRUE(scrgb.known); + + const auto pq_white = monitor::WhiteForColorSpace(VK_COLOR_SPACE_HDR10_ST2084_EXT); + EXPECT_NEAR(pq_white.value, 0.5791f, 0.0001f); // ST 2084 encoding of 200 nits + EXPECT_TRUE(pq_white.known); + + const auto hlg = monitor::WhiteForColorSpace(VK_COLOR_SPACE_HDR10_HLG_EXT); + EXPECT_FLOAT_EQ(hlg.value, 0.75f); // BT.2408 reference white + EXPECT_TRUE(hlg.known); +} + +TEST(MonitorOverlay, WhiteFallsBackToOneForUnknownColorSpaces) { + for (const VkColorSpaceKHR color_space : + {VK_COLOR_SPACE_PASS_THROUGH_EXT, VK_COLOR_SPACE_DISPLAY_NATIVE_AMD, static_cast(0x7FFF0000)}) { + const auto white = monitor::WhiteForColorSpace(color_space); + EXPECT_FLOAT_EQ(white.value, 1.0f) << color_space; + EXPECT_FALSE(white.known) << color_space; + } +} + +static VkSwapchainCreateInfoKHR SwapchainInfo() { + VkSwapchainCreateInfoKHR info = {VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; + info.imageFormat = VK_FORMAT_B8G8R8A8_SRGB; + info.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; + info.imageExtent = {1920, 1080}; + info.imageArrayLayers = 1; + info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + info.presentMode = VK_PRESENT_MODE_FIFO_KHR; + return info; +} + +TEST(MonitorOverlay, PatchAddsColorAttachmentUsage) { + VkImageFormatListCreateInfo format_list = {VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.pNext = &format_list; + info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; + + const VkSwapchainCreateInfoKHR patched = monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}).create_info; + EXPECT_EQ(patched.imageUsage, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + EXPECT_EQ(patched.pNext, &format_list); + EXPECT_EQ(patched.imageFormat, info.imageFormat); + EXPECT_EQ(patched.presentMode, info.presentMode); + EXPECT_EQ(info.imageUsage, VK_IMAGE_USAGE_TRANSFER_DST_BIT); // The app's struct is untouched +} + +// vkCreateSharedSwapchainsKHR swapchains never get the overlay; that's only worth saying if there was one to draw +TEST(MonitorOverlay, SharedSwapchainsWarningOnlyWhenALineIsVisible) { + const char* warning = monitor::SharedSwapchainsWarning(monitor::LineFlags{}); + ASSERT_NE(warning, nullptr); + EXPECT_NE(std::string(warning).find("vkCreateSharedSwapchainsKHR"), std::string::npos); + EXPECT_EQ(monitor::SharedSwapchainsWarning(monitor::LineFlags{false, false, false}), nullptr); +} + +// With every line hidden nothing is drawn, so the app's swapchain stays as it asked for, and there's nothing to warn about +TEST(MonitorOverlay, PatchLeavesSwapchainsAloneWhenEveryLineIsHidden) { + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; + const monitor::LineFlags hidden = {false, false, false}; + EXPECT_FALSE(monitor::AnyLineVisible(hidden)); + EXPECT_TRUE(monitor::AnyLineVisible(monitor::LineFlags{})); + + const monitor::SwapchainPatch patch = monitor::PatchSwapchainCreateInfo(info, hidden); + EXPECT_FALSE(patch.eligibility.ok); + EXPECT_EQ(patch.eligibility.reason, nullptr); + EXPECT_EQ(patch.create_info.imageUsage, VK_IMAGE_USAGE_TRANSFER_DST_BIT); + + const monitor::LineFlags frame_number_only = {false, false, true}; + EXPECT_TRUE(monitor::PatchSwapchainCreateInfo(info, frame_number_only).eligibility.ok); + + // Not even the reasons the overlay couldn't be drawn are worth a message then + info.presentMode = VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR; + EXPECT_EQ(monitor::PatchSwapchainCreateInfo(info, hidden).eligibility.reason, nullptr); +} + +TEST(MonitorOverlay, PatchLeavesSwapchainsTheOverlayCantDrawOnAlone) { + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; + info.presentMode = VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR; + + const monitor::SwapchainPatch patch = monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}); + EXPECT_FALSE(patch.eligibility.ok); + EXPECT_EQ(patch.create_info.imageUsage, VK_IMAGE_USAGE_TRANSFER_DST_BIT); +} + +TEST(MonitorOverlay, EligibleForRegularSwapchains) { + const auto eligibility = monitor::SwapchainOverlayEligibility(SwapchainInfo()); + EXPECT_TRUE(eligibility.ok); + EXPECT_FALSE(eligibility.deferred); +} + +TEST(MonitorOverlay, NotEligibleForSharedPresentModes) { + for (const VkPresentModeKHR mode : {VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR, VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR}) { + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.presentMode = mode; + const auto eligibility = monitor::SwapchainOverlayEligibility(info); + EXPECT_FALSE(eligibility.ok); + EXPECT_NE(eligibility.reason, nullptr); + } +} + +TEST(MonitorOverlay, NotEligibleForProtectedSwapchains) { + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.flags = VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR; + const auto eligibility = monitor::SwapchainOverlayEligibility(info); + EXPECT_FALSE(eligibility.ok); + EXPECT_NE(eligibility.reason, nullptr); +} + +TEST(MonitorOverlay, EligibleWithDeferredMemoryAllocation) { + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.flags = VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_KHR; + const auto eligibility = monitor::SwapchainOverlayEligibility(info); + EXPECT_TRUE(eligibility.ok); + EXPECT_TRUE(eligibility.deferred); +} + +TEST(MonitorOverlay, DrawsOnlyOnGraphicsQueuesWithSomethingToShow) { + EXPECT_TRUE(monitor::ShouldDrawOverlay(VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, true, true)); + EXPECT_FALSE(monitor::ShouldDrawOverlay(VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, true, true)); + EXPECT_FALSE(monitor::ShouldDrawOverlay(VK_QUEUE_GRAPHICS_BIT, false, true)); + EXPECT_FALSE(monitor::ShouldDrawOverlay(VK_QUEUE_GRAPHICS_BIT, true, false)); +} + +TEST(MonitorOverlay, SettingsDefaults) { + const monitor::MonitorSettings settings = monitor::ParseSettings(monitor::RawSettings{}); + EXPECT_EQ(settings.position, monitor::Position::TopLeft); + EXPECT_EQ(settings.scale_percent, 100); + EXPECT_EQ(settings.update_interval, 500ms); + EXPECT_TRUE(settings.lines.fps); + EXPECT_TRUE(settings.lines.frame_time); + EXPECT_TRUE(settings.lines.frame_number); +} + +TEST(MonitorOverlay, SettingsParsePositions) { + const std::pair cases[] = { + {"TOP_LEFT", monitor::Position::TopLeft}, {"TOP_RIGHT", monitor::Position::TopRight}, + {"BOTTOM_LEFT", monitor::Position::BottomLeft}, {"BOTTOM_RIGHT", monitor::Position::BottomRight}, + {"MIDDLE", monitor::Position::TopLeft}, {"", monitor::Position::TopLeft}, + }; + for (const auto& test_case : cases) { + monitor::RawSettings raw; + raw.position = test_case.first; + EXPECT_EQ(monitor::ParseSettings(raw).position, test_case.second) << test_case.first; + } +} + +TEST(MonitorOverlay, SettingsClampNumbers) { + monitor::RawSettings raw; + raw.scale = 10; + raw.update_interval_ms = 1; + monitor::MonitorSettings settings = monitor::ParseSettings(raw); + EXPECT_EQ(settings.scale_percent, 50); + EXPECT_EQ(settings.update_interval, 50ms); + + raw.scale = 1000; + raw.update_interval_ms = -5; + settings = monitor::ParseSettings(raw); + EXPECT_EQ(settings.scale_percent, 400); + EXPECT_EQ(settings.update_interval, 50ms); + + raw.scale = 150; + raw.update_interval_ms = 2000; + settings = monitor::ParseSettings(raw); + EXPECT_EQ(settings.scale_percent, 150); + EXPECT_EQ(settings.update_interval, 2000ms); +} + +TEST(MonitorOverlay, SettingsLogWarningsOnlyWhenAsked) { + monitor::RawSettings raw; + EXPECT_FALSE(monitor::ParseSettings(raw).log_warnings); + raw.log_warnings = true; + EXPECT_TRUE(monitor::ParseSettings(raw).log_warnings); +} + +TEST(MonitorOverlay, SettingsHideLines) { + monitor::RawSettings raw; + raw.show_fps = false; + raw.show_frame_number = false; + const monitor::MonitorSettings settings = monitor::ParseSettings(raw); + EXPECT_FALSE(settings.lines.fps); + EXPECT_TRUE(settings.lines.frame_time); + EXPECT_FALSE(settings.lines.frame_number); +} + +// The fragment shader has its own copy of the font, as "const uint kFont[...] = uint[](...)" with one row per value. +TEST(MonitorOverlay, ShaderFontMatchesFont) { + std::ifstream file(MONITOR_SHADER_DIR "/monitor_overlay.frag"); + ASSERT_TRUE(file.is_open()); + const std::string source((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + + const size_t begin = source.find("uint[]("); + ASSERT_NE(begin, std::string::npos); + const size_t end = source.find(");", begin); + ASSERT_NE(end, std::string::npos); + + std::vector rows; + const std::string values = source.substr(begin + 7, end - begin - 7); + for (size_t i = 0; i < values.size();) { + if (std::isdigit(static_cast(values[i])) != 0) { + size_t length = 0; + rows.push_back(static_cast(std::stoul(values.substr(i), &length, 0))); + i += length; + } else if (values.compare(i, 2, "//") == 0) { + i = values.find('\n', i); + } else { + ++i; + } + } + + ASSERT_EQ(rows.size(), static_cast(monitor::kGlyphCount * monitor::kGlyphHeight)); + for (int glyph = 0; glyph < monitor::kGlyphCount; ++glyph) { + for (int row = 0; row < monitor::kGlyphHeight; ++row) { + EXPECT_EQ(rows[static_cast((glyph * monitor::kGlyphHeight) + row)], + monitor::GlyphRow(static_cast(glyph), row)) + << "glyph " << glyph << " row " << row; + } + } +} + +// The fragment shader repeats the panel metrics as "const int kName = value;". +TEST(MonitorOverlay, ShaderMetricsMatchLayout) { + std::ifstream file(MONITOR_SHADER_DIR "/monitor_overlay.frag"); + ASSERT_TRUE(file.is_open()); + const std::string source((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + + const auto shader_constant = [&](const std::string& name) -> int { + const std::string declaration = "const int " + name + " = "; + const size_t pos = source.find(declaration); + if (pos == std::string::npos) { + ADD_FAILURE() << name << " not found in the shader"; + return -1; + } + return std::stoi(source.substr(pos + declaration.size())); + }; + + EXPECT_EQ(shader_constant("kGlyphWidth"), monitor::kGlyphWidth); + EXPECT_EQ(shader_constant("kGlyphHeight"), monitor::kGlyphHeight); + EXPECT_EQ(shader_constant("kGlyphCount"), monitor::kGlyphCount); + EXPECT_EQ(shader_constant("kCharAdvance"), monitor::kCharAdvance); + EXPECT_EQ(shader_constant("kLineAdvance"), monitor::kLineAdvance); + EXPECT_EQ(shader_constant("kPadding"), monitor::kPadding); + EXPECT_EQ(shader_constant("kMaxColumns"), static_cast(monitor::kMaxColumns)); +} + +// FNV-1a over the shader sources with carriage returns dropped, the same as scripts/generate_monitor_shaders.py. +// The files are hashed in the order of SHADERS in that script. Returns false if a source can't be read. +static bool HashShaderSources(uint64_t& hash) { + hash = 0xcbf29ce484222325ull; + for (const char* name : {"/monitor_overlay.vert", "/monitor_overlay.frag"}) { + std::ifstream file(std::string(MONITOR_SHADER_DIR) + name, std::ios::binary); + if (!file.is_open()) { + ADD_FAILURE() << "can't read " << name; + return false; + } + for (std::istreambuf_iterator it(file), end; it != end; ++it) { + if (*it != '\r') { + hash = (hash ^ static_cast(*it)) * 0x100000001b3ull; + } + } + } + return true; +} + +// The SPIR-V is checked in; a shader edited without running the generator leaves it stale. +TEST(MonitorOverlay, ShaderSpirvMatchesTheShaderSources) { + uint64_t hash = 0; + ASSERT_TRUE(HashShaderSources(hash)); + EXPECT_EQ(hash, kMonitorOverlayShaderSourceHash) << "Run scripts/generate_monitor_shaders.py after changing layersvt/shaders"; +} + +// The device can use what both the app's VkApplicationInfo::apiVersion and the physical device support. +TEST(MonitorOverlay, ImageViewUsageNeedsVulkan11OrMaintenance2) { + EXPECT_FALSE(monitor::ImageViewUsageAvailable(VK_API_VERSION_1_0, VK_API_VERSION_1_3, false)); + EXPECT_TRUE(monitor::ImageViewUsageAvailable(VK_API_VERSION_1_0, VK_API_VERSION_1_3, true)); + EXPECT_FALSE(monitor::ImageViewUsageAvailable(VK_API_VERSION_1_3, VK_API_VERSION_1_0, false)); + EXPECT_TRUE(monitor::ImageViewUsageAvailable(VK_API_VERSION_1_1, VK_API_VERSION_1_2, false)); + EXPECT_TRUE(monitor::ImageViewUsageAvailable(VK_MAKE_API_VERSION(0, 1, 1, 0), VK_MAKE_API_VERSION(0, 1, 4, 321), false)); +} + +// Only a line that wouldn't fit loses its decimals +TEST(MonitorOverlay, LongFrameTimesFitOnTheLine) { + const auto lines = monitor::FormatOverlayLines(Snapshot(0.01, 100000.0, 100000.0, 100000.0), 0, monitor::LineFlags{}); + ASSERT_EQ(lines.size(), 3u); + EXPECT_EQ(lines[1], "100000 ms (100000-100000)"); + + const auto fits = monitor::FormatOverlayLines(Snapshot(0.1, 10000.0, 10000.0, 10000.0), 0, monitor::LineFlags{}); + EXPECT_EQ(fits[1], "10000.00 ms (10000.00-10000.00)"); + EXPECT_LE(fits[1].size(), monitor::kMaxColumns); +} + +TEST(MonitorOverlay, TextUsesOnlyDrawableCharacters) { + const auto lines = monitor::FormatOverlayLines(Snapshot(1234.5, 0.81, 0.5, 12345.67), UINT64_MAX, monitor::LineFlags{}); + for (const std::string& line : lines) { + for (const char character : line) { + EXPECT_TRUE(character == ' ' || monitor::GlyphIndex(character) != monitor::GlyphIndex(' ')) + << "'" << character << "' in " << line; + } + } +} + +// Settings as an application would pass them with VK_EXT_layer_settings +static monitor::RawSettings ReadSettings(const std::vector& layer_settings) { + VkLayerSettingsCreateInfoEXT settings_info = {VK_STRUCTURE_TYPE_LAYER_SETTINGS_CREATE_INFO_EXT}; + settings_info.settingCount = static_cast(layer_settings.size()); + settings_info.pSettings = layer_settings.data(); + VkuLayerSettingSet settings = VK_NULL_HANDLE; + vkuCreateLayerSettingSet("VK_LAYER_LUNARG_monitor", &settings_info, nullptr, nullptr, &settings); + const monitor::RawSettings raw = monitor::ReadRawSettings(settings); + vkuDestroyLayerSettingSet(settings, nullptr); + return raw; +} + +TEST(MonitorOverlay, SettingsDefaultWithoutASettingSet) { + // What the layer gets if the layer settings library couldn't create a setting set + const monitor::RawSettings raw = monitor::ReadRawSettings(VK_NULL_HANDLE); + const monitor::RawSettings defaults; + EXPECT_EQ(raw.position, defaults.position); + EXPECT_EQ(raw.scale, defaults.scale); + EXPECT_EQ(raw.update_interval_ms, defaults.update_interval_ms); + EXPECT_EQ(raw.show_fps, defaults.show_fps); + EXPECT_EQ(raw.show_frame_time, defaults.show_frame_time); + EXPECT_EQ(raw.show_frame_number, defaults.show_frame_number); + EXPECT_FALSE(raw.log_warnings); // Nothing is printed unless the user asks +} + +TEST(MonitorOverlay, SettingsAreReadFromTheApplication) { + constexpr const char* position = "BOTTOM_RIGHT"; + constexpr int32_t scale = 200; + constexpr int32_t interval = 1000; + constexpr VkBool32 off = VK_FALSE; + constexpr VkBool32 enabled = VK_TRUE; + const std::vector layer_settings = { + {"VK_LAYER_LUNARG_monitor", "position", VK_LAYER_SETTING_TYPE_STRING_EXT, 1, static_cast(&position)}, + {"VK_LAYER_LUNARG_monitor", "scale", VK_LAYER_SETTING_TYPE_INT32_EXT, 1, &scale}, + {"VK_LAYER_LUNARG_monitor", "update_interval_ms", VK_LAYER_SETTING_TYPE_INT32_EXT, 1, &interval}, + {"VK_LAYER_LUNARG_monitor", "show_fps", VK_LAYER_SETTING_TYPE_BOOL32_EXT, 1, &off}, + {"VK_LAYER_LUNARG_monitor", "show_frame_time", VK_LAYER_SETTING_TYPE_BOOL32_EXT, 1, &off}, + {"VK_LAYER_LUNARG_monitor", "show_frame_number", VK_LAYER_SETTING_TYPE_BOOL32_EXT, 1, &off}, + {"VK_LAYER_LUNARG_monitor", "log_warnings", VK_LAYER_SETTING_TYPE_BOOL32_EXT, 1, &enabled}, + }; + const monitor::RawSettings raw = ReadSettings(layer_settings); + EXPECT_EQ(raw.position, "BOTTOM_RIGHT"); + EXPECT_EQ(raw.scale, 200); + EXPECT_EQ(raw.update_interval_ms, 1000); + EXPECT_FALSE(raw.show_fps); + EXPECT_FALSE(raw.show_frame_time); + EXPECT_FALSE(raw.show_frame_number); + EXPECT_TRUE(raw.log_warnings); +} diff --git a/tests/monitor/test_monitor_present.cpp b/tests/monitor/test_monitor_present.cpp new file mode 100644 index 0000000000..35eef14880 --- /dev/null +++ b/tests/monitor/test_monitor_present.cpp @@ -0,0 +1,1223 @@ +/* + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Tests the swapchain and present plumbing against a fake device: a dispatch table of stubs that count every object +// created and destroyed, record submissions, and fail on request. No Vulkan driver is needed. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "monitor_overlay.h" +#include "monitor_present.h" +#include "vk_layer_table.h" + +namespace { + +struct FakeDevice; +FakeDevice* fake = nullptr; + +template +T MakeHandle(uint64_t value) { + static_assert(sizeof(T) == sizeof(uint64_t), "non-dispatchable handles are 64 bits"); + T handle{}; + memcpy(static_cast(&handle), &value, sizeof(T)); + return handle; +} + +template +uint64_t HandleValue(T handle) { + uint64_t value = 0; + memcpy(&value, static_cast(&handle), sizeof(value)); + return value; +} + +struct Submission { + std::vector waits; + std::vector wait_stages; + std::vector signals; + uint32_t command_buffer_count = 0; + VkFence fence = VK_NULL_HANDLE; +}; + +struct FakeDevice { + std::map created; + std::map destroyed; + std::map attempts; + std::map fail_at; // Fail the Nth create attempt (1-based) of a kind of object + uint64_t next_handle = 0x1000; + uint32_t image_count = 3; + + // Fences are signaled by a successful submit. Waiting on one that is unsignaled and was never submitted would hang. + std::map fence_signaled; + std::set fences_waited; + int hung_waits = 0; + VkResult submit_result = VK_SUCCESS; + std::vector submissions; + + // vkQueuePresentKHR calls that reached the driver + struct Present { + std::vector waits; + std::vector swapchains; + }; + std::vector presents; + VkResult present_result = VK_SUCCESS; + int draws = 0; + + // Command buffers are dispatchable, so they get real memory for the loader's dispatch pointer. + std::vector> command_buffers; + int loader_data_calls = 0; + + // Usage of each image view from a chained VkImageViewUsageCreateInfo, 0 if there was none + std::vector view_usages; + + FakeDevice() { fake = this; } + ~FakeDevice() { fake = nullptr; } + FakeDevice(const FakeDevice&) = delete; + FakeDevice& operator=(const FakeDevice&) = delete; + FakeDevice(FakeDevice&&) = delete; + FakeDevice& operator=(FakeDevice&&) = delete; + + int Live(const std::string& kind) { return created[kind] - destroyed[kind]; } + + // Counts an attempt to create `kind`, and says whether it should fail + bool Fails(const std::string& kind) { + const int attempt = ++attempts[kind]; + const auto it = fail_at.find(kind); + return it != fail_at.end() && it->second == attempt; + } + + template + VkResult Create(const std::string& kind, T* out) { + if (Fails(kind)) { + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + ++created[kind]; + *out = MakeHandle(next_handle++); + return VK_SUCCESS; + } + + template + void Destroy(const std::string& kind, T handle) { + if (HandleValue(handle) != 0) { + ++destroyed[kind]; + } + } + + static VkuDeviceDispatchTable Dispatch(); +}; + +#define STUB_CREATE(Name, Info, Type, kind) \ + VKAPI_ATTR VkResult VKAPI_CALL Stub##Name(VkDevice, const Info*, const VkAllocationCallbacks*, Type* out) { \ + return fake->Create(kind, out); \ + } +#define STUB_DESTROY(Name, Type, kind) \ + VKAPI_ATTR void VKAPI_CALL Stub##Name(VkDevice, Type handle, const VkAllocationCallbacks*) { fake->Destroy(kind, handle); } + +STUB_DESTROY(DestroyImageView, VkImageView, "view") +STUB_CREATE(CreateFramebuffer, VkFramebufferCreateInfo, VkFramebuffer, "framebuffer") +STUB_DESTROY(DestroyFramebuffer, VkFramebuffer, "framebuffer") +STUB_CREATE(CreateSemaphore, VkSemaphoreCreateInfo, VkSemaphore, "semaphore") +STUB_DESTROY(DestroySemaphore, VkSemaphore, "semaphore") +STUB_CREATE(CreateRenderPass, VkRenderPassCreateInfo, VkRenderPass, "render pass") +STUB_DESTROY(DestroyRenderPass, VkRenderPass, "render pass") +STUB_CREATE(CreatePipelineLayout, VkPipelineLayoutCreateInfo, VkPipelineLayout, "pipeline layout") +STUB_DESTROY(DestroyPipelineLayout, VkPipelineLayout, "pipeline layout") +STUB_CREATE(CreateShaderModule, VkShaderModuleCreateInfo, VkShaderModule, "shader module") +STUB_DESTROY(DestroyShaderModule, VkShaderModule, "shader module") +STUB_DESTROY(DestroyPipeline, VkPipeline, "pipeline") +STUB_CREATE(CreateCommandPool, VkCommandPoolCreateInfo, VkCommandPool, "command pool") +STUB_DESTROY(DestroyCommandPool, VkCommandPool, "command pool") +STUB_DESTROY(DestroyFence, VkFence, "fence") + +VKAPI_ATTR VkResult VKAPI_CALL StubCreateImageView(VkDevice /*device*/, const VkImageViewCreateInfo* info, + const VkAllocationCallbacks* /*pAllocator*/, VkImageView* out) { + VkImageUsageFlags usage = 0; + for (const void* node = info->pNext; node; node = read_chain_header(node).pNext) { + if (read_chain_header(node).sType == VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO) { + usage = static_cast(node)->usage; + } + } + fake->view_usages.push_back(usage); + return fake->Create("view", out); +} + +VKAPI_ATTR VkResult VKAPI_CALL StubCreateGraphicsPipelines(VkDevice /*device*/, VkPipelineCache /*pipelineCache*/, uint32_t count, + const VkGraphicsPipelineCreateInfo* /*pCreateInfos*/, + const VkAllocationCallbacks* /*pAllocator*/, VkPipeline* out) { + for (uint32_t i = 0; i < count; ++i) { + const VkResult result = fake->Create("pipeline", &out[i]); + if (result != VK_SUCCESS) { + return result; + } + } + return VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL StubGetSwapchainImagesKHR(VkDevice /*device*/, VkSwapchainKHR /*swapchain*/, uint32_t* count, + VkImage* images) { + if (!images) { + *count = fake->image_count; + return VK_SUCCESS; + } + for (uint32_t i = 0; i < *count && i < fake->image_count; ++i) { + images[i] = MakeHandle(0x100 + i); + } + return VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL StubCreateFence(VkDevice /*device*/, const VkFenceCreateInfo* info, + const VkAllocationCallbacks* /*pAllocator*/, VkFence* out) { + const VkResult result = fake->Create("fence", out); + if (result == VK_SUCCESS) { + fake->fence_signaled[HandleValue(*out)] = (info->flags & VK_FENCE_CREATE_SIGNALED_BIT) != 0; + } + return result; +} + +VKAPI_ATTR VkResult VKAPI_CALL StubWaitForFences(VkDevice /*device*/, uint32_t count, const VkFence* fences, VkBool32 /*waitAll*/, + uint64_t /*timeout*/) { + for (uint32_t i = 0; i < count; ++i) { + fake->fences_waited.insert(HandleValue(fences[i])); + if (!fake->fence_signaled[HandleValue(fences[i])]) { + ++fake->hung_waits; + } + } + return VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL StubResetFences(VkDevice /*device*/, uint32_t count, const VkFence* fences) { + for (uint32_t i = 0; i < count; ++i) { + fake->fence_signaled[HandleValue(fences[i])] = false; + } + return VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL StubAllocateCommandBuffers(VkDevice /*device*/, const VkCommandBufferAllocateInfo* info, + VkCommandBuffer* out) { + for (uint32_t i = 0; i < info->commandBufferCount; ++i) { + if (fake->Fails("command buffer")) { + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + fake->command_buffers.push_back(std::make_unique(0)); + out[i] = reinterpret_cast(fake->command_buffers.back().get()); + ++fake->created["command buffer"]; + } + return VK_SUCCESS; +} + +VKAPI_ATTR void VKAPI_CALL StubFreeCommandBuffers(VkDevice /*device*/, VkCommandPool /*commandPool*/, uint32_t count, + const VkCommandBuffer* buffers) { + for (uint32_t i = 0; i < count; ++i) { + if (buffers[i]) { + ++fake->destroyed["command buffer"]; + } + } +} + +VKAPI_ATTR VkResult VKAPI_CALL StubQueueSubmit(VkQueue /*queue*/, uint32_t count, const VkSubmitInfo* submits, VkFence fence) { + if (fake->submit_result != VK_SUCCESS) { + return fake->submit_result; + } + for (uint32_t i = 0; i < count; ++i) { + Submission submission; + submission.waits.assign(submits[i].pWaitSemaphores, submits[i].pWaitSemaphores + submits[i].waitSemaphoreCount); + submission.wait_stages.assign(submits[i].pWaitDstStageMask, submits[i].pWaitDstStageMask + submits[i].waitSemaphoreCount); + submission.signals.assign(submits[i].pSignalSemaphores, submits[i].pSignalSemaphores + submits[i].signalSemaphoreCount); + submission.command_buffer_count = submits[i].commandBufferCount; + submission.fence = fence; + fake->submissions.push_back(submission); + } + if (fence) { + fake->fence_signaled[HandleValue(fence)] = true; + } + return VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL StubBeginCommandBuffer(VkCommandBuffer /*commandBuffer*/, + const VkCommandBufferBeginInfo* /*pBeginInfo*/) { + return VK_SUCCESS; +} +VKAPI_ATTR VkResult VKAPI_CALL StubEndCommandBuffer(VkCommandBuffer /*commandBuffer*/) { return VK_SUCCESS; } + +VKAPI_ATTR void VKAPI_CALL StubCmdBeginRenderPass(VkCommandBuffer /*commandBuffer*/, const VkRenderPassBeginInfo* /*pBegin*/, + VkSubpassContents /*contents*/) {} +VKAPI_ATTR void VKAPI_CALL StubCmdEndRenderPass(VkCommandBuffer /*commandBuffer*/) {} +VKAPI_ATTR void VKAPI_CALL StubCmdSetViewport(VkCommandBuffer /*commandBuffer*/, uint32_t /*first*/, uint32_t /*count*/, + const VkViewport* /*pViewports*/) {} +VKAPI_ATTR void VKAPI_CALL StubCmdSetScissor(VkCommandBuffer /*commandBuffer*/, uint32_t /*first*/, uint32_t /*count*/, + const VkRect2D* /*pScissors*/) {} +VKAPI_ATTR void VKAPI_CALL StubCmdBindPipeline(VkCommandBuffer /*commandBuffer*/, VkPipelineBindPoint /*bindPoint*/, + VkPipeline /*pipeline*/) {} +VKAPI_ATTR void VKAPI_CALL StubCmdPushConstants(VkCommandBuffer /*commandBuffer*/, VkPipelineLayout /*layout*/, + VkShaderStageFlags /*stages*/, uint32_t /*offset*/, uint32_t /*size*/, + const void* /*pValues*/) {} +VKAPI_ATTR void VKAPI_CALL StubCmdDraw(VkCommandBuffer /*commandBuffer*/, uint32_t /*vertexCount*/, uint32_t /*instanceCount*/, + uint32_t /*firstVertex*/, uint32_t /*firstInstance*/) { + ++fake->draws; +} + +VKAPI_ATTR VkResult VKAPI_CALL StubQueuePresentKHR(VkQueue /*queue*/, const VkPresentInfoKHR* info) { + FakeDevice::Present present; + present.waits.assign(info->pWaitSemaphores, info->pWaitSemaphores + info->waitSemaphoreCount); + present.swapchains.assign(info->pSwapchains, info->pSwapchains + info->swapchainCount); + fake->presents.push_back(present); + return fake->present_result; +} + +VkuDeviceDispatchTable FakeDevice::Dispatch() { + VkuDeviceDispatchTable dispatch = {}; + dispatch.CreateImageView = StubCreateImageView; + dispatch.DestroyImageView = StubDestroyImageView; + dispatch.CreateFramebuffer = StubCreateFramebuffer; + dispatch.DestroyFramebuffer = StubDestroyFramebuffer; + dispatch.CreateSemaphore = StubCreateSemaphore; + dispatch.DestroySemaphore = StubDestroySemaphore; + dispatch.CreateRenderPass = StubCreateRenderPass; + dispatch.DestroyRenderPass = StubDestroyRenderPass; + dispatch.CreatePipelineLayout = StubCreatePipelineLayout; + dispatch.DestroyPipelineLayout = StubDestroyPipelineLayout; + dispatch.CreateShaderModule = StubCreateShaderModule; + dispatch.DestroyShaderModule = StubDestroyShaderModule; + dispatch.CreateGraphicsPipelines = StubCreateGraphicsPipelines; + dispatch.DestroyPipeline = StubDestroyPipeline; + dispatch.GetSwapchainImagesKHR = StubGetSwapchainImagesKHR; + dispatch.CreateCommandPool = StubCreateCommandPool; + dispatch.DestroyCommandPool = StubDestroyCommandPool; + dispatch.AllocateCommandBuffers = StubAllocateCommandBuffers; + dispatch.FreeCommandBuffers = StubFreeCommandBuffers; + dispatch.CreateFence = StubCreateFence; + dispatch.DestroyFence = StubDestroyFence; + dispatch.WaitForFences = StubWaitForFences; + dispatch.ResetFences = StubResetFences; + dispatch.QueueSubmit = StubQueueSubmit; + dispatch.BeginCommandBuffer = StubBeginCommandBuffer; + dispatch.EndCommandBuffer = StubEndCommandBuffer; + dispatch.CmdBeginRenderPass = StubCmdBeginRenderPass; + dispatch.CmdEndRenderPass = StubCmdEndRenderPass; + dispatch.CmdSetViewport = StubCmdSetViewport; + dispatch.CmdSetScissor = StubCmdSetScissor; + dispatch.CmdBindPipeline = StubCmdBindPipeline; + dispatch.CmdPushConstants = StubCmdPushConstants; + dispatch.CmdDraw = StubCmdDraw; + dispatch.QueuePresentKHR = StubQueuePresentKHR; + return dispatch; +} + +uint64_t device_object = 0; +uint64_t queue_object = 0; +const VkDevice kDevice = reinterpret_cast(&device_object); +const VkQueue kQueue = reinterpret_cast(&queue_object); + +VkSwapchainCreateInfoKHR SwapchainInfo() { + VkSwapchainCreateInfoKHR info = {VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; + info.imageFormat = VK_FORMAT_B8G8R8A8_SRGB; + info.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; + info.imageExtent = {1920, 1080}; + info.imageArrayLayers = 1; + info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + info.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; + info.presentMode = VK_PRESENT_MODE_FIFO_KHR; + return info; +} + +// A blendable format, on a device without VkImageViewUsageCreateInfo +constexpr monitor::OverlaySupport kBlend = {true, false}; + +constexpr const char* kKinds[] = {"view", "framebuffer", "semaphore", "render pass", "pipeline layout", + "pipeline", "shader module", "command pool", "command buffer", "fence"}; + +void ExpectNothingLive(FakeDevice& device) { + for (const char* kind : kKinds) { + EXPECT_EQ(device.Live(kind), 0) << kind; + } +} + +TEST(MonitorPresent, SwapchainSetupCreatesObjectsPerImageAndTeardownFreesThem) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::OverlayPipelines pipelines; + monitor::SwapchainOverlay overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x50), + monitor::PatchSwapchainCreateInfo(SwapchainInfo(), monitor::LineFlags{}), kBlend, pipelines, + overlay); + + EXPECT_TRUE(overlay.ok); + EXPECT_EQ(overlay.images.size(), 3u); + EXPECT_EQ(device.Live("view"), 3); + EXPECT_EQ(device.Live("framebuffer"), 3); + EXPECT_EQ(device.Live("semaphore"), 3); + EXPECT_EQ(device.Live("pipeline"), 1); + EXPECT_EQ(device.Live("shader module"), 0); + + monitor::DestroySwapchainOverlay(kDevice, dispatch, overlay); + monitor::DestroyOverlayPipelines(kDevice, dispatch, pipelines); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, RecreatedSwapchainReusesTheOverlayPipeline) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::OverlayPipelines pipelines; + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + + // A resize destroys the swapchain and creates a new one with the same format + monitor::SwapchainOverlay old_overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x50), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), kBlend, pipelines, old_overlay); + monitor::DestroySwapchainOverlay(kDevice, dispatch, old_overlay); + monitor::SwapchainOverlay new_overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x60), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), kBlend, pipelines, new_overlay); + EXPECT_TRUE(new_overlay.ok); + EXPECT_EQ(device.created["pipeline"], 1); + + // Another format, or no blending, needs its own pipeline + info.imageFormat = VK_FORMAT_R8G8B8A8_UNORM; + monitor::SwapchainOverlay other_format; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x70), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), kBlend, pipelines, other_format); + monitor::SwapchainOverlay opaque; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x80), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), {false, false}, pipelines, + opaque); + EXPECT_EQ(device.created["pipeline"], 3); + + for (monitor::SwapchainOverlay* overlay : {&new_overlay, &other_format, &opaque}) { + monitor::DestroySwapchainOverlay(kDevice, dispatch, *overlay); + } + EXPECT_EQ(device.Live("pipeline"), 3); // Kept for the next swapchain + monitor::DestroyOverlayPipelines(kDevice, dispatch, pipelines); + ExpectNothingLive(device); +} + +// The view inherits the swapchain's usage otherwise, and usage like STORAGE can make it invalid for the view format. +TEST(MonitorPresent, ViewsAreLimitedToColorAttachmentUsageWhenTheDeviceAllowsIt) { + for (const bool view_usage : {true, false}) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::OverlayPipelines pipelines; + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.imageUsage |= VK_IMAGE_USAGE_STORAGE_BIT; + monitor::SwapchainOverlay overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x50), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), {true, view_usage}, pipelines, + overlay); + + ASSERT_EQ(device.view_usages.size(), 3u); + for (const VkImageUsageFlags usage : device.view_usages) { + EXPECT_EQ(usage, view_usage ? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT : 0u) << "view_usage " << view_usage; + } + monitor::DestroySwapchainOverlay(kDevice, dispatch, overlay); + monitor::DestroyOverlayPipelines(kDevice, dispatch, pipelines); + ExpectNothingLive(device); + } +} + +// The swapchain is created and its overlay set up from one decision, so the two can't disagree. +TEST(MonitorPresent, SetupFollowsTheDecisionTheSwapchainWasCreatedWith) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::OverlayPipelines pipelines; + monitor::SwapchainPatch patch = monitor::PatchSwapchainCreateInfo(SwapchainInfo(), monitor::LineFlags{}); + patch.eligibility.ok = false; + patch.eligibility.reason = "decided at create time"; + monitor::SwapchainOverlay overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x50), patch, kBlend, pipelines, overlay); + + EXPECT_FALSE(overlay.ok); + EXPECT_STREQ(overlay.reason, "decided at create time"); + EXPECT_EQ(device.created["view"], 0); +} + +TEST(MonitorPresent, DeferredSwapchainCreatesViewsOnFirstPresentOfEachImage) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.flags = VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_KHR; + monitor::OverlayPipelines pipelines; + monitor::SwapchainOverlay overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x50), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), kBlend, pipelines, overlay); + + EXPECT_TRUE(overlay.ok); + EXPECT_EQ(device.Live("semaphore"), 3); + EXPECT_EQ(device.Live("view"), 0); // The images may have no memory yet + + EXPECT_TRUE(monitor::PrepareImage(kDevice, dispatch, overlay, 2)); + EXPECT_EQ(device.Live("view"), 1); + EXPECT_TRUE(monitor::PrepareImage(kDevice, dispatch, overlay, 2)); + EXPECT_EQ(device.Live("view"), 1); + EXPECT_TRUE(monitor::PrepareImage(kDevice, dispatch, overlay, 0)); + EXPECT_TRUE(monitor::PrepareImage(kDevice, dispatch, overlay, 1)); + EXPECT_EQ(device.Live("view"), 3); + EXPECT_EQ(device.Live("framebuffer"), 3); + EXPECT_FALSE(monitor::PrepareImage(kDevice, dispatch, overlay, 3)); + + monitor::DestroySwapchainOverlay(kDevice, dispatch, overlay); + monitor::DestroyOverlayPipelines(kDevice, dispatch, pipelines); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, FailedSwapchainSetupDisablesOverlayWithoutLeaking) { + // Fail part way through the per image objects, or the one-off pipeline objects + const std::pair failures[] = { + {"view", 2}, {"framebuffer", 2}, {"semaphore", 2}, {"render pass", 1}, {"pipeline", 1}}; + for (const auto& failure : failures) { + const char* kind = failure.first; + FakeDevice device; + device.fail_at[kind] = failure.second; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::OverlayPipelines pipelines; + monitor::SwapchainOverlay overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x50), + monitor::PatchSwapchainCreateInfo(SwapchainInfo(), monitor::LineFlags{}), kBlend, pipelines, + overlay); + + EXPECT_FALSE(overlay.ok) << kind; + EXPECT_NE(overlay.reason, nullptr) << kind; + monitor::DestroySwapchainOverlay(kDevice, dispatch, overlay); + monitor::DestroyOverlayPipelines(kDevice, dispatch, pipelines); + ExpectNothingLive(device); + } +} + +TEST(MonitorPresent, IneligibleSwapchainCreatesNothing) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.presentMode = VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR; + monitor::OverlayPipelines pipelines; + monitor::SwapchainOverlay overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x50), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), kBlend, pipelines, overlay); + + EXPECT_FALSE(overlay.ok); + EXPECT_NE(overlay.reason, nullptr); + for (const char* kind : kKinds) { + EXPECT_EQ(device.created[kind], 0) << kind; + } +} + +VKAPI_ATTR VkResult VKAPI_CALL SetLoaderData(VkDevice /*device*/, void* object) { + ++fake->loader_data_calls; + *static_cast(object) = 0x10ADE7; // Where the loader keeps its dispatch pointer + return VK_SUCCESS; +} + +VKAPI_ATTR VkResult VKAPI_CALL FailLoaderData(VkDevice /*device*/, void* /*object*/) { + ++fake->loader_data_calls; + return VK_ERROR_INITIALIZATION_FAILED; +} + +constexpr uint32_t kSlots = 3; + +std::vector warnings; +void RecordWarning(const char* message) { warnings.emplace_back(message); } + +// A device with one graphics queue family and kQueue in it, the way the layer sets it up at vkCreateDevice. +// Also forgets the warnings of earlier tests. +void SetUpGraphicsDevice(monitor::DeviceOverlay& state) { + warnings.clear(); + state.device = kDevice; + state.set_loader_data = SetLoaderData; + state.queue_families = {{VK_QUEUE_GRAPHICS_BIT, 2, 0, {1, 1, 1}}}; + state.queue_family_index[kQueue] = 0; +} + +// Adds a swapchain the way vkCreateSwapchainKHR does +monitor::SwapchainOverlay& AddSwapchain(const VkuDeviceDispatchTable& dispatch, monitor::DeviceOverlay& state, + VkSwapchainKHR swapchain) { + EXPECT_EQ(monitor::AddSwapchainOverlay(dispatch, state, swapchain, + monitor::PatchSwapchainCreateInfo(SwapchainInfo(), monitor::LineFlags{}), true), + nullptr); + return *state.swapchains.at(swapchain); +} + +// An app present of one image of each swapchain, after its rendering signaled `rendered` +struct AppPresentInfo { + std::vector swapchains; + std::vector indices; + VkSemaphore rendered = MakeHandle(0xA1); + VkPresentInfoKHR info = {VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; + + AppPresentInfo(std::vector presented, std::vector image_indices) + : swapchains(std::move(presented)), indices(std::move(image_indices)) { + info.waitSemaphoreCount = 1; + info.pWaitSemaphores = &rendered; + info.swapchainCount = static_cast(swapchains.size()); + info.pSwapchains = swapchains.data(); + info.pImageIndices = indices.data(); + } + AppPresentInfo(const AppPresentInfo&) = delete; + AppPresentInfo& operator=(const AppPresentInfo&) = delete; + AppPresentInfo(AppPresentInfo&&) = delete; + AppPresentInfo& operator=(AppPresentInfo&&) = delete; + ~AppPresentInfo() = default; +}; + +VkResult PresentWithOverlay(const VkuDeviceDispatchTable& dispatch, monitor::DeviceOverlay& state, const VkPresentInfoKHR& info, + VkQueue queue = kQueue) { + return monitor::PresentWithOverlay(dispatch, state, queue, info, monitor::MonitorSettings{}, 7, + std::chrono::steady_clock::now(), RecordWarning); +} + +TEST(MonitorPresent, PresentDrawsTheOverlayBetweenTheAppAndThePresent) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + const monitor::SwapchainOverlay& overlay = AddSwapchain(dispatch, state, MakeHandle(0x50)); + + // The second swapchain was never seen by the layer, so it's passed through without an overlay + const AppPresentInfo app({MakeHandle(0x50), MakeHandle(0x99)}, {1, 0}); + ASSERT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_SUCCESS); + + ASSERT_EQ(device.submissions.size(), 1u); + EXPECT_EQ(device.submissions[0].waits, std::vector{app.rendered}); + EXPECT_EQ(device.submissions[0].signals, std::vector{overlay.images[1].present_wait}); + EXPECT_EQ(device.draws, 1); + ASSERT_EQ(device.presents.size(), 1u); + EXPECT_EQ(device.presents[0].waits, std::vector{overlay.images[1].present_wait}); + EXPECT_EQ(device.presents[0].swapchains, app.swapchains); + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, QueuesOfOneFamilyDoNotWaitForEachOther) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + uint64_t second_queue_object = 0; + auto* const second_queue = reinterpret_cast(&second_queue_object); + state.queue_family_index[second_queue] = 0; + AddSwapchain(dispatch, state, MakeHandle(0x50)); + AddSwapchain(dispatch, state, MakeHandle(0x60)); + + for (uint32_t i = 0; i < kSlots; ++i) { + const AppPresentInfo app({MakeHandle(0x50)}, {i}); + ASSERT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_SUCCESS); + } + const AppPresentInfo other({MakeHandle(0x60)}, {0}); + ASSERT_EQ(PresentWithOverlay(dispatch, state, other.info, second_queue), VK_SUCCESS); + EXPECT_TRUE(device.fences_waited.empty()); + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, ForgettingASwapchainWaitsForItsOverlayOnEveryQueue) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + const monitor::SwapchainOverlay& overlay = AddSwapchain(dispatch, state, MakeHandle(0x50)); + const VkSemaphore present_wait = overlay.images[0].present_wait; + + const AppPresentInfo app({MakeHandle(0x50)}, {0}); + ASSERT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_SUCCESS); + const std::unique_ptr forgotten = + monitor::ForgetSwapchain(dispatch, state, MakeHandle(0x50)); + + EXPECT_EQ(device.fences_waited.size(), 1u); + EXPECT_EQ(device.hung_waits, 0); + EXPECT_TRUE(state.swapchains.empty()); + // The present may still wait on the overlay's semaphores until the swapchain is destroyed, so they outlive the call + ASSERT_NE(forgotten, nullptr); + EXPECT_GT(device.Live("semaphore"), 0) << HandleValue(present_wait); + monitor::DestroySwapchainOverlay(kDevice, dispatch, *forgotten); + EXPECT_EQ(device.Live("semaphore"), 0) << HandleValue(present_wait); + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, PresentWithoutKnownSwapchainsGoesStraightThrough) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + + const AppPresentInfo app({MakeHandle(0x99)}, {0}); + ASSERT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_SUCCESS); + + EXPECT_TRUE(device.submissions.empty()); + ASSERT_EQ(device.presents.size(), 1u); + EXPECT_EQ(device.presents[0].waits, std::vector{app.rendered}); + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, SlotRingGivesEveryCommandBufferLoaderDispatch) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, kSlots, ring); + + EXPECT_TRUE(ring.ok); + EXPECT_EQ(device.Live("command buffer"), static_cast(kSlots)); + EXPECT_EQ(device.loader_data_calls, static_cast(kSlots)); + for (const monitor::SubmitSlot& slot : ring.slots) { + EXPECT_EQ(*reinterpret_cast(slot.command_buffer), 0x10ADE7u); + } + + monitor::DestroySlotRing(kDevice, dispatch, ring); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, SlotRingIsDisabledWithoutLoaderDispatch) { + for (PFN_vkSetDeviceLoaderData set_loader_data : {static_cast(nullptr), FailLoaderData}) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, set_loader_data, kSlots, ring); + + EXPECT_FALSE(ring.ok); + EXPECT_NE(ring.reason, nullptr); + EXPECT_FALSE(ring.retry); // The loader won't change, so there's no point trying again + monitor::DestroySlotRing(kDevice, dispatch, ring); + ExpectNothingLive(device); + } +} + +// Running out of memory may not last, so the ring frees what it made and can be created again +TEST(MonitorPresent, SlotRingCanBeRetriedAfterRunningOutOfMemory) { + const std::pair failures[] = {{"command pool", 1}, {"command buffer", 2}, {"fence", 2}}; + for (const auto& failure : failures) { + const char* kind = failure.first; + FakeDevice device; + device.fail_at[kind] = failure.second; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, kSlots, ring); + + EXPECT_FALSE(ring.ok) << kind; + EXPECT_NE(ring.reason, nullptr) << kind; + EXPECT_TRUE(ring.retry) << kind; + ExpectNothingLive(device); + + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, kSlots, ring); + EXPECT_TRUE(ring.ok) << kind; + monitor::DestroySlotRing(kDevice, dispatch, ring); + ExpectNothingLive(device); + } +} + +// Takes the next slot and submits it with no semaphores, as one present would. +VkResult Present(monitor::SlotRing& ring, const VkuDeviceDispatchTable& dispatch, VkSwapchainKHR swapchain) { + monitor::SubmitSlot& slot = monitor::AcquireSlot(kDevice, dispatch, ring); + return monitor::SubmitOverlay(kDevice, dispatch, kQueue, slot, {}, {}, {swapchain}); +} + +TEST(MonitorPresent, SlotRingOnlyWaitsForSubmittedWork) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, kSlots, ring); + auto* const swapchain = MakeHandle(0x50); + + // The first trip around the ring has nothing to wait for + for (uint32_t i = 0; i < kSlots; ++i) { + ASSERT_EQ(Present(ring, dispatch, swapchain), VK_SUCCESS); + } + EXPECT_TRUE(device.fences_waited.empty()); + + // Then each slot waits for its previous submission + ASSERT_EQ(Present(ring, dispatch, swapchain), VK_SUCCESS); + EXPECT_EQ(device.fences_waited.size(), 1u); + EXPECT_EQ(device.hung_waits, 0); + + monitor::DestroySlotRing(kDevice, dispatch, ring); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, FailedSubmitDoesNotLeaveAFenceToWaitOnForever) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, kSlots, ring); + auto* const swapchain = MakeHandle(0x50); + + for (uint32_t i = 0; i < kSlots; ++i) { + ASSERT_EQ(Present(ring, dispatch, swapchain), VK_SUCCESS); + } + device.submit_result = VK_ERROR_OUT_OF_DEVICE_MEMORY; + EXPECT_EQ(Present(ring, dispatch, swapchain), VK_ERROR_OUT_OF_DEVICE_MEMORY); + device.submit_result = VK_SUCCESS; + + for (uint32_t i = 0; i < kSlots + 1; ++i) { + ASSERT_EQ(Present(ring, dispatch, swapchain), VK_SUCCESS); + } + EXPECT_EQ(device.hung_waits, 0); + + monitor::DestroySlotRing(kDevice, dispatch, ring); + EXPECT_EQ(device.hung_waits, 0); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, WaitForSwapchainOnlyWaitsForItsOwnSubmissions) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, kSlots, ring); + auto* const first = MakeHandle(0x50); + auto* const second = MakeHandle(0x60); + + ASSERT_EQ(Present(ring, dispatch, first), VK_SUCCESS); + ASSERT_EQ(Present(ring, dispatch, second), VK_SUCCESS); + monitor::WaitForSwapchain(kDevice, dispatch, ring, first); + + EXPECT_EQ(device.fences_waited.size(), 1u); + EXPECT_EQ(device.fences_waited.count(HandleValue(ring.slots[0].fence)), 1u); + EXPECT_EQ(device.hung_waits, 0); + + monitor::DestroySlotRing(kDevice, dispatch, ring); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, SubmitWaitsForTheAppAndSignalsThePresent) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, kSlots, ring); + const std::vector app = {MakeHandle(0xA1), MakeHandle(0xA2)}; + const std::vector ours = {MakeHandle(0xB1)}; + + monitor::SubmitSlot& slot = monitor::AcquireSlot(kDevice, dispatch, ring); + ASSERT_EQ(monitor::SubmitOverlay(kDevice, dispatch, kQueue, slot, app, ours, {MakeHandle(0x50)}), VK_SUCCESS); + + ASSERT_EQ(device.submissions.size(), 1u); + const Submission& submission = device.submissions[0]; + EXPECT_EQ(submission.waits, app); + EXPECT_EQ(submission.wait_stages, std::vector(2, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)); + EXPECT_EQ(submission.signals, ours); + EXPECT_EQ(submission.command_buffer_count, 1u); + EXPECT_EQ(HandleValue(submission.fence), HandleValue(slot.fence)); + + monitor::DestroySlotRing(kDevice, dispatch, ring); + ExpectNothingLive(device); +} + +// The overlays RewritePresentInfo gets: one per presented swapchain, null where none is drawn +std::vector Drawn(std::initializer_list drawn) { + static monitor::SwapchainOverlay overlay; + std::vector overlays; + for (const bool is_drawn : drawn) { + overlays.push_back(is_drawn ? &overlay : nullptr); + } + return overlays; +} + +struct AppPresent { + VkSwapchainKHR swapchains[2] = {MakeHandle(0x50), MakeHandle(0x60)}; + uint32_t indices[2] = {1, 2}; + VkResult results[2] = {}; + VkSemaphore waits[1] = {MakeHandle(0xA1)}; + VkRectLayerKHR rects[2] = {{{0, 0}, {16, 16}, 0}, {{32, 32}, {8, 8}, 0}}; + VkPresentRegionKHR regions[2] = {{1, &rects[0]}, {1, &rects[1]}}; + VkPresentRegionsKHR present_regions = {VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR, nullptr, 2, regions}; + VkPresentInfoKHR info = {VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; + + AppPresent() { + info.waitSemaphoreCount = 1; + info.pWaitSemaphores = waits; + info.swapchainCount = 2; + info.pSwapchains = swapchains; + info.pImageIndices = indices; + info.pResults = results; + } +}; + +const VkPresentRegionsKHR* FindRegions(const void* chain) { + for (const void* node = chain; node; node = read_chain_header(node).pNext) { + if (read_chain_header(node).sType == VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR) { + return static_cast(node); + } + } + return nullptr; +} + +TEST(MonitorPresent, PresentWaitsOnTheOverlayInsteadOfTheApp) { + const AppPresent app; + const std::vector ours = {MakeHandle(0xB1), MakeHandle(0xB2)}; + monitor::PresentRewrite rewrite; + const VkPresentInfoKHR& info = monitor::RewritePresentInfo(app.info, ours, Drawn({true, true}), rewrite); + + ASSERT_EQ(info.waitSemaphoreCount, 2u); + EXPECT_EQ(HandleValue(info.pWaitSemaphores[0]), 0xB1u); + EXPECT_EQ(HandleValue(info.pWaitSemaphores[1]), 0xB2u); + EXPECT_EQ(info.swapchainCount, 2u); + EXPECT_EQ(info.pSwapchains, app.swapchains); + EXPECT_EQ(info.pImageIndices, app.indices); + EXPECT_EQ(info.pResults, app.results); + EXPECT_EQ(info.pNext, nullptr); + EXPECT_EQ(app.info.pWaitSemaphores, app.waits); // The app's struct is untouched +} + +TEST(MonitorPresent, PresentRegionsCoverTheWholeImageWhenTheOverlayIsDrawn) { + AppPresent app; + VkPresentIdKHR present_id = {VK_STRUCTURE_TYPE_PRESENT_ID_KHR, nullptr, 2, nullptr}; + VkDisplayPresentInfoKHR display = {VK_STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR, &app.present_regions}; + app.present_regions.pNext = &present_id; + app.info.pNext = &display; + + monitor::PresentRewrite rewrite; + const VkPresentInfoKHR& info = + monitor::RewritePresentInfo(app.info, {MakeHandle(0xB1)}, Drawn({false, true}), rewrite); + + // The display struct before the regions is still there, and so is the present ID after them + ASSERT_NE(info.pNext, nullptr); + EXPECT_EQ(read_chain_header(info.pNext).sType, VK_STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR); + const VkPresentRegionsKHR* regions = FindRegions(info.pNext); + ASSERT_NE(regions, nullptr); + EXPECT_NE(regions, &app.present_regions); + EXPECT_EQ(regions->pNext, &present_id); + + // Only the swapchain with the overlay reports the whole image as changed + ASSERT_EQ(regions->swapchainCount, 2u); + EXPECT_EQ(regions->pRegions[0].rectangleCount, 1u); + EXPECT_EQ(regions->pRegions[0].pRectangles, &app.rects[0]); + EXPECT_EQ(regions->pRegions[1].rectangleCount, 0u); + EXPECT_FALSE(rewrite.regions_unchanged); + + // The app's structs are untouched + EXPECT_EQ(app.regions[1].rectangleCount, 1u); + EXPECT_EQ(display.pNext, &app.present_regions); +} + +struct UnknownStruct { + VkStructureType sType = VK_STRUCTURE_TYPE_MAX_ENUM; + const void* pNext = nullptr; +}; + +TEST(MonitorPresent, PresentRegionsAreLeftAloneBehindAnUnknownStruct) { + AppPresent app; + UnknownStruct unknown = {static_cast(0x7FFF0001), &app.present_regions}; + app.info.pNext = &unknown; + + monitor::PresentRewrite rewrite; + const VkPresentInfoKHR& info = + monitor::RewritePresentInfo(app.info, {MakeHandle(0xB1)}, Drawn({true, true}), rewrite); + + EXPECT_EQ(info.pNext, &unknown); + EXPECT_TRUE(rewrite.regions_unchanged); +} + +TEST(MonitorPresent, PresentRewriteCanBeReused) { + AppPresent with_regions; + with_regions.info.pNext = &with_regions.present_regions; + AppPresent without_regions; + UnknownStruct unknown = {static_cast(0x7FFF0001), &without_regions.present_regions}; + without_regions.info.pNext = &unknown; + + monitor::PresentRewrite rewrite; + (void)monitor::RewritePresentInfo(without_regions.info, {MakeHandle(0xB1)}, Drawn({true, true}), rewrite); + EXPECT_TRUE(rewrite.regions_unchanged); + + const VkPresentInfoKHR& info = + monitor::RewritePresentInfo(with_regions.info, {MakeHandle(0xC1)}, Drawn({true, false}), rewrite); + EXPECT_FALSE(rewrite.regions_unchanged); + ASSERT_EQ(info.waitSemaphoreCount, 1u); + EXPECT_EQ(HandleValue(info.pWaitSemaphores[0]), 0xC1u); + const VkPresentRegionsKHR* regions = FindRegions(info.pNext); + ASSERT_NE(regions, nullptr); + EXPECT_EQ(regions->pRegions[0].rectangleCount, 0u); + EXPECT_EQ(regions->pRegions[1].rectangleCount, 1u); + + const AppPresent no_chain; + const VkPresentInfoKHR& plain = monitor::RewritePresentInfo(no_chain.info, {}, Drawn({true, true}), rewrite); + EXPECT_EQ(plain.pNext, nullptr); + EXPECT_EQ(plain.waitSemaphoreCount, 0u); +} + +TEST(MonitorPresent, RetryingAFailedImageDoesNotLeak) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.flags = VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_KHR; + monitor::OverlayPipelines pipelines; + monitor::SwapchainOverlay overlay; + monitor::SetupSwapchainOverlay(kDevice, dispatch, MakeHandle(0x50), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), kBlend, pipelines, overlay); + + device.fail_at["framebuffer"] = 1; + EXPECT_FALSE(monitor::PrepareImage(kDevice, dispatch, overlay, 0)); + EXPECT_TRUE(monitor::PrepareImage(kDevice, dispatch, overlay, 0)); + EXPECT_EQ(device.Live("view"), 1); + + monitor::DestroySwapchainOverlay(kDevice, dispatch, overlay); + monitor::DestroyOverlayPipelines(kDevice, dispatch, pipelines); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, SlotRingNeedsAtLeastOneSlot) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, 0, ring); + EXPECT_FALSE(ring.ok); + monitor::DestroySlotRing(kDevice, dispatch, ring); + ExpectNothingLive(device); +} + +VKAPI_ATTR VkResult VKAPI_CALL FailResetFences(VkDevice /*device*/, uint32_t /*fenceCount*/, const VkFence* /*pFences*/) { + return VK_ERROR_OUT_OF_DEVICE_MEMORY; +} + +TEST(MonitorPresent, SubmitIsSkippedIfTheFenceCantBeReset) { + FakeDevice device; + VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::SlotRing ring; + monitor::CreateSlotRing(kDevice, dispatch, 0, SetLoaderData, kSlots, ring); + + dispatch.ResetFences = FailResetFences; + EXPECT_EQ(Present(ring, dispatch, MakeHandle(0x50)), VK_ERROR_OUT_OF_DEVICE_MEMORY); + EXPECT_TRUE(device.submissions.empty()); + EXPECT_FALSE(ring.slots[0].in_flight); + + monitor::DestroySlotRing(kDevice, dispatch, ring); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, UndoWithNoSemaphoresSubmitsNothing) { + const FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + EXPECT_EQ(monitor::UndoOverlaySemaphores(dispatch, kQueue, {}, {}), VK_SUCCESS); + EXPECT_TRUE(device.submissions.empty()); +} + +TEST(MonitorPresent, UndoUnsignalsTheOverlaySemaphoresAndSignalsTheAppsAgain) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + const std::vector ours = {MakeHandle(0xB1), MakeHandle(0xB2)}; + const std::vector apps = {MakeHandle(0xA1)}; + EXPECT_EQ(monitor::UndoOverlaySemaphores(dispatch, kQueue, ours, apps), VK_SUCCESS); + + ASSERT_EQ(device.submissions.size(), 1u); + EXPECT_EQ(device.submissions[0].waits, ours); + EXPECT_EQ(device.submissions[0].wait_stages, std::vector(2, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)); + EXPECT_EQ(device.submissions[0].command_buffer_count, 0u); + EXPECT_EQ(device.submissions[0].signals, apps); +} + +// A present that fails with an out of memory error must leave the app's semaphores as they were, but the overlay submit +// already waited on them. +TEST(MonitorPresent, PresentOutOfMemoryGivesTheAppItsSemaphoresBack) { + for (const VkResult error : {VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY}) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + const monitor::SwapchainOverlay& overlay = AddSwapchain(dispatch, state, MakeHandle(0x50)); + + device.present_result = error; + const AppPresentInfo app({MakeHandle(0x50)}, {1}); + EXPECT_EQ(PresentWithOverlay(dispatch, state, app.info), error); + + ASSERT_EQ(device.submissions.size(), 2u) << error; + const std::vector ours = {overlay.images[1].present_wait}; + EXPECT_EQ(device.submissions[1].waits, ours) << error; + EXPECT_EQ(device.submissions[1].signals, std::vector{app.rendered}) << error; + EXPECT_EQ(device.submissions[1].command_buffer_count, 0u) << error; + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); + } +} + +// A queue whose command pool couldn't be created the first time gets the overlay on a later present +TEST(MonitorPresent, PresentRetriesTheQueueAfterRunningOutOfMemory) { + FakeDevice device; + device.fail_at["command pool"] = 1; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + AddSwapchain(dispatch, state, MakeHandle(0x50)); + + const AppPresentInfo app({MakeHandle(0x50)}, {1}); + EXPECT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_SUCCESS); + EXPECT_TRUE(device.submissions.empty()); + EXPECT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_SUCCESS); + EXPECT_EQ(device.submissions.size(), 1u); + EXPECT_EQ(device.draws, 1); + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +// Whatever the overlay submit fails with, the app's semaphores are untouched, so the driver still gets the app's present. +// That is also what fills in the app's pResults. +TEST(MonitorPresent, FailedSubmitStillPresentsTheAppsFrame) { + for (const VkResult error : {VK_ERROR_OUT_OF_DEVICE_MEMORY, VK_ERROR_DEVICE_LOST}) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + AddSwapchain(dispatch, state, MakeHandle(0x50)); + + device.submit_result = error; + device.present_result = error; + const AppPresentInfo app({MakeHandle(0x50)}, {1}); + EXPECT_EQ(PresentWithOverlay(dispatch, state, app.info), error); + + ASSERT_EQ(device.presents.size(), 1u) << error; + EXPECT_EQ(device.presents[0].waits, std::vector{app.rendered}) << error; + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); + } +} + +// Other errors mean the present was enqueued, so its waits happened and there is nothing to undo +TEST(MonitorPresent, PresentOutOfDateUndoesNothing) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + AddSwapchain(dispatch, state, MakeHandle(0x50)); + + device.present_result = VK_ERROR_OUT_OF_DATE_KHR; + const AppPresentInfo app({MakeHandle(0x50)}, {1}); + EXPECT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_ERROR_OUT_OF_DATE_KHR); + EXPECT_EQ(device.submissions.size(), 1u); + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +// The present only updates the app's dirty rectangles then, so the overlay may not update; say so once. +TEST(MonitorPresent, PresentWarnsWhenPresentRegionsCantCoverTheOverlay) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + AddSwapchain(dispatch, state, MakeHandle(0x50)); + + AppPresentInfo app({MakeHandle(0x50)}, {0}); + constexpr VkRectLayerKHR rect = {{0, 0}, {16, 16}, 0}; + const VkPresentRegionKHR region = {1, &rect}; + VkPresentRegionsKHR regions = {VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR, nullptr, 1, ®ion}; + UnknownStruct unknown = {static_cast(0x7FFF0001), ®ions}; + app.info.pNext = &unknown; + ASSERT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_SUCCESS); + ASSERT_EQ(warnings.size(), 1u); + EXPECT_NE(warnings[0].find("VkPresentRegionsKHR"), std::string::npos) << warnings[0]; + + // Presents the layer can rewrite don't warn + warnings.clear(); + app.info.pNext = ®ions; + ASSERT_EQ(PresentWithOverlay(dispatch, state, app.info), VK_SUCCESS); + EXPECT_TRUE(warnings.empty()); + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +// A queue the layer never saw retrieved isn't one without graphics, so the message has to say which it is. +TEST(MonitorPresent, PresentFromAnUnknownQueueSaysSo) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + AddSwapchain(dispatch, state, MakeHandle(0x50)); + uint64_t unknown_queue_object = 0; + auto* const unknown_queue = reinterpret_cast(&unknown_queue_object); + + const AppPresentInfo app({MakeHandle(0x50)}, {0}); + ASSERT_EQ(PresentWithOverlay(dispatch, state, app.info, unknown_queue), VK_SUCCESS); + EXPECT_TRUE(device.submissions.empty()); + ASSERT_EQ(device.presents.size(), 1u); + ASSERT_EQ(warnings.size(), 1u); + EXPECT_NE(warnings[0].find("queue"), std::string::npos) << warnings[0]; + EXPECT_EQ(warnings[0].find("graphics"), std::string::npos) << warnings[0]; + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +TEST(MonitorPresent, PresentFromAQueueWithoutGraphicsSaysSo) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + state.queue_families.push_back({VK_QUEUE_COMPUTE_BIT, 1, 0, {1, 1, 1}}); + uint64_t compute_queue_object = 0; + auto* const compute_queue = reinterpret_cast(&compute_queue_object); + state.queue_family_index[compute_queue] = 1; + AddSwapchain(dispatch, state, MakeHandle(0x50)); + + const AppPresentInfo app({MakeHandle(0x50)}, {0}); + ASSERT_EQ(PresentWithOverlay(dispatch, state, app.info, compute_queue), VK_SUCCESS); + EXPECT_TRUE(device.submissions.empty()); + ASSERT_EQ(warnings.size(), 1u); + EXPECT_NE(warnings[0].find("without graphics"), std::string::npos) << warnings[0]; + + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); +} + +// Whether views can be limited to color attachment usage is decided once per device +TEST(MonitorPresent, SwapchainsUseTheDevicesImageViewUsageSupport) { + for (const bool view_usage : {true, false}) { + FakeDevice device; + const VkuDeviceDispatchTable dispatch = FakeDevice::Dispatch(); + monitor::DeviceOverlay state; + SetUpGraphicsDevice(state); + state.view_usage = view_usage; + VkSwapchainCreateInfoKHR info = SwapchainInfo(); + info.imageUsage |= VK_IMAGE_USAGE_STORAGE_BIT; + EXPECT_EQ(monitor::AddSwapchainOverlay(dispatch, state, MakeHandle(0x50), + monitor::PatchSwapchainCreateInfo(info, monitor::LineFlags{}), true), + nullptr); + + ASSERT_EQ(device.view_usages.size(), 3u); + for (const VkImageUsageFlags usage : device.view_usages) { + EXPECT_EQ(usage, view_usage ? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT : 0u) << "view_usage " << view_usage; + } + monitor::DestroyDeviceOverlay(dispatch, state); + ExpectNothingLive(device); + } +} + +// The layer shows each warning once +TEST(MonitorPresent, EachMessageIsShownOnce) { + monitor::ShownMessages shown; + EXPECT_TRUE(monitor::FirstTimeShown(shown, "mirrored swapchain transforms are drawn without the mirror")); + EXPECT_FALSE(monitor::FirstTimeShown(shown, "mirrored swapchain transforms are drawn without the mirror")); + EXPECT_TRUE(monitor::FirstTimeShown(shown, "unknown swapchain color space, the overlay may be too bright or too dark")); +} + +// Warnings are only passed on when the user turned on log_warnings +TEST(MonitorPresent, WarningsOnlyReachTheUserWhenAsked) { + warnings.clear(); + monitor::WarnIf(false, RecordWarning)("dropped"); + EXPECT_TRUE(warnings.empty()); + monitor::WarnIf(true, RecordWarning)("shown"); + EXPECT_EQ(warnings, std::vector{"shown"}); +} + +} // namespace diff --git a/vkconfig_cmd/main_layers.cpp b/vkconfig_cmd/main_layers.cpp index d1daeccfcf..81b3ea3a83 100644 --- a/vkconfig_cmd/main_layers.cpp +++ b/vkconfig_cmd/main_layers.cpp @@ -24,6 +24,7 @@ #include "../vkconfig_core/configuration.h" #include "../vkconfig_core/layer_manager.h" +#include #include static int RunLayersOverride(Configurator& configurator, const CommandLine& command_line) { @@ -87,21 +88,40 @@ static int RunLayersSurrender(Configurator& configurator, const CommandLine& com } static int RunLayersPath(Configurator& configurator, const CommandLine& command_line) { - printf("vkconfig: [INFO] Vulkan Layers paths:\n"); + const std::array, LAYERS_PATHS_COUNT>& paths = configurator.layers.BuildLayersSearchPaths(); - const std::set& layer_display_list = configurator.layers.BuildLayerDisplayList(); + for (std::size_t group_index = 0, group_count = paths.size(); group_index < group_count; ++group_index) { + const LayersPaths layers_paths = static_cast(group_index); - for (auto it = layer_display_list.begin(), end = layer_display_list.end(); it != end; ++it) { - const Layer* layer = configurator.layers.FindFromManifest(it->id.manifest_path, true); - if (layer == nullptr) { + const std::vector& paths_group = paths[group_index]; + + printf("%s (%s layers):\n", ::GetLabel(layers_paths), ::GetToken(::GetLayerType(layers_paths))); + if (paths_group.empty()) { + printf(" - None\n"); continue; } - const std::string status = layer->status == STATUS_STABLE ? "" : format(" (%s)", ::GetToken(layer->status)); - const std::string text = format("%s - %s%s, %s layer", layer->key.c_str(), layer->api_version.str().c_str(), status.c_str(), - ::GetToken(layer->type)); + // Some locations are layer manifest files, only print their directory once + std::vector printed_dirs; + for (std::size_t i = 0, n = paths_group.size(); i < n; ++i) { + const Path& path = paths_group[i]; + const std::string dir = path.IsFile() ? path.AbsoluteDir() : path.AbsolutePath(); + + if (std::find(printed_dirs.begin(), printed_dirs.end(), dir) != printed_dirs.end()) { + continue; + } + printed_dirs.push_back(dir); + + printf(" - %s\n", dir.c_str()); - printf(" - %s\n", text.c_str()); + const std::vector& layers = configurator.layers.available_layers; + for (std::size_t j = 0, m = layers.size(); j < m; ++j) { + if (layers[j].manifest_path.AbsoluteDir() == dir) { + printf(" * %s - %s (%s)\n", layers[j].key.c_str(), layers[j].api_version.str().c_str(), + layers[j].manifest_path.Filename().c_str()); + } + } + } } return 0; diff --git a/vkconfig_core/command_line.cpp b/vkconfig_core/command_line.cpp index 1ba79a3e5c..a5260777a6 100644 --- a/vkconfig_core/command_line.cpp +++ b/vkconfig_core/command_line.cpp @@ -130,10 +130,9 @@ struct CommandLayersDesc { static const CommandLayersDesc command_layers_desc[] = { {COMMAND_LAYERS_LIST, "--list"}, {COMMAND_LAYERS_LIST, "-l"}, + {COMMAND_LAYERS_VERBOSE, "--list-verbose"}, {COMMAND_LAYERS_PATH, "--path"}, {COMMAND_LAYERS_PATH, "-p"}, - {COMMAND_LAYERS_VERBOSE, "--list-verbose"}, - {COMMAND_LAYERS_VERBOSE, "-lv"}, {COMMAND_LAYERS_OVERRIDE, "--override"}, {COMMAND_LAYERS_OVERRIDE, "-o"}, {COMMAND_LAYERS_SURRENDER, "--surrender"}, @@ -380,7 +379,9 @@ CommandLine::CommandLine(int argc, char* argv[]) arg_offset += 2; } break; case COMMAND_LAYERS_SURRENDER: - case COMMAND_LAYERS_LIST: { + case COMMAND_LAYERS_PATH: + case COMMAND_LAYERS_LIST: + case COMMAND_LAYERS_VERBOSE: { ++arg_offset; } break; } @@ -677,7 +678,7 @@ void CommandLine::usage() const { printf("\n"); printf("Synopsis\n"); printf("\tvkconfig layers (--list | -l)\n"); - printf("\tvkconfig layers (--list-verbose | -lv)\n"); + printf("\tvkconfig layers --list-verbose\n"); printf("\tvkconfig layers (--path | -p)\n"); printf("\tvkconfig layers (--override | -o) \n"); printf("\tvkconfig layers (--surrender | -s)\n"); @@ -686,11 +687,11 @@ void CommandLine::usage() const { printf("\tvkconfig layers (--list | -l)\n"); printf("\t\tList the Vulkan layers found by %s on the system.\n", VKCONFIG_NAME); printf("\n"); - printf("\tvkconfig layers (--list-version | -lv)\n"); + printf("\tvkconfig layers --list-verbose\n"); printf("\t\tList the Vulkan layers found by %s on the system with locations and versions.\n", VKCONFIG_NAME); printf("\n"); printf("\tvkconfig layers (--path | -p)\n"); - printf("\t\tList the Vulkan layers locations found by %s on the system.\n", VKCONFIG_NAME); + printf("\t\tList the locations %s searches for Vulkan layers.\n", VKCONFIG_NAME); printf("\n"); printf("\tvkconfig layers (--override | -o) \n"); printf("\t\tOverride the Vulkan layers using generated by %s.\n", VKCONFIG_NAME); diff --git a/vkconfig_core/configurations/Portability.json b/vkconfig_core/configurations/Portability.json index 28c35a8a4e..c558c7e553 100644 --- a/vkconfig_core/configurations/Portability.json +++ b/vkconfig_core/configurations/Portability.json @@ -2,7 +2,7 @@ "file_format_version": "3.0.0", "configuration": { "name": "Portability", - "version": 2, + "version": 3, "platforms": [ "WINDOWS", "LINUX", @@ -37,7 +37,7 @@ { "key": "profile_name", "type": "ENUM", - "value": "VP_LUNARG_desktop_baseline_2023" + "value": "VP_LUNARG_desktop_baseline_2026" } ], "control": "on", diff --git a/vkconfig_core/configurator.cpp b/vkconfig_core/configurator.cpp index 04f7b9ce92..99af0c2f2a 100644 --- a/vkconfig_core/configurator.cpp +++ b/vkconfig_core/configurator.cpp @@ -75,6 +75,8 @@ Configurator& Configurator::Get() { void Configurator::Release() { ::configurator.reset(); } Configurator::Configurator() : mode(init_mode) { + this->layers.validate_manifests = true; + #ifdef SDK_VERSION const Version sdk_version(SDK_VERSION); if (sdk_version != Version::NONE) { @@ -1167,6 +1169,12 @@ bool Configurator::Load() { this->layers.gui_added_layers_paths.insert(json_paths[i].toString().toStdString()); } } + if (json_object.value("hide_validation_messages") != QJsonValue::Undefined) { + const QJsonArray& json_paths = json_object.value("hide_validation_messages").toArray(); + for (std::size_t i = 0, n = json_paths.size(); i < n; ++i) { + this->layers.hide_validation_message_paths.insert(json_paths[i].toString().toStdString()); + } + } } // TAB_DRIVERS @@ -1411,8 +1419,15 @@ bool Configurator::Save() const { json_paths.append(it->AbsolutePath().c_str()); } + QJsonArray json_hide_validation_messages; + for (auto it = this->layers.hide_validation_message_paths.begin(); + it != this->layers.hide_validation_message_paths.end(); ++it) { + json_hide_validation_messages.append(it->AbsolutePath().c_str()); + } + QJsonObject json_object; json_object.insert("paths", json_paths); + json_object.insert("hide_validation_messages", json_hide_validation_messages); json_object.insert("layers", json_layers); json_object.insert("validate_manifests", this->layers.validate_manifests); json_object.insert("last_driver_dir", this->layers.last_layers_dir.AbsolutePath().c_str()); diff --git a/vkconfig_core/layer.cpp b/vkconfig_core/layer.cpp index 03537cc4f6..2c0df5861f 100644 --- a/vkconfig_core/layer.cpp +++ b/vkconfig_core/layer.cpp @@ -111,12 +111,17 @@ LayerControl Layer::GetActualControl() const { } int Layer::FindPresetIndex(const SettingDataSet& settings) const { - for (std::size_t i = 0, n = this->presets.size(); i < n; ++i) { + // Search the layer presets before the default preset, the default values may match a layer preset + for (std::size_t i = DEFAULT_PRESET + 1, n = this->presets.size(); i < n; ++i) { if (::HasPreset(settings, this->presets[i].settings)) { return static_cast(i); } } + if (!this->presets.empty() && ::HasPreset(settings, this->presets[DEFAULT_PRESET].settings)) { + return DEFAULT_PRESET; + } + return NO_PRESET; } @@ -435,6 +440,7 @@ void CollectDefaultSettingData(const SettingMetaSet& meta_set, SettingDataSet& d if (!setting_found) { SettingData* setting_data = setting_meta->Instantiate(); + setting_data->ResetExpanded(*setting_meta); data_set.push_back(setting_data); } diff --git a/vkconfig_core/layer_manager.cpp b/vkconfig_core/layer_manager.cpp index 6dc76f9d92..ac09763b55 100644 --- a/vkconfig_core/layer_manager.cpp +++ b/vkconfig_core/layer_manager.cpp @@ -27,13 +27,14 @@ #include #include #include +#include -static std::vector GetEnvVariablePaths(const char *variable_name, LayerType type) { +static std::vector GetEnvVariablePaths(const char* variable_name, LayerType type) { std::vector result; - const char *SEPARATOR = GetToken(PARSE_ENV_VAR); + const char* SEPARATOR = GetToken(PARSE_ENV_VAR); - const std::vector &paths = UniqueStrings(Split(qgetenv(variable_name).toStdString(), SEPARATOR)); + const std::vector& paths = UniqueStrings(Split(qgetenv(variable_name).toStdString(), SEPARATOR)); result.resize(paths.size()); for (std::size_t i = 0, n = paths.size(); i < n; ++i) { result[i] = paths[i]; @@ -46,21 +47,21 @@ static std::vector GetImplicitLayerPaths() { std::vector result; #if VKC_ENV == VKC_ENV_WIN32 - const std::vector &admin_registry_paths = + const std::vector& admin_registry_paths = LoadRegistrySoftwareLayers("HKEY_LOCAL_MACHINE\\Software\\Khronos\\Vulkan\\ImplicitLayers", LAYER_TYPE_IMPLICIT); result.insert(result.begin(), admin_registry_paths.begin(), admin_registry_paths.end()); - const std::vector &user_registry_paths = + const std::vector& user_registry_paths = LoadRegistrySoftwareLayers("HKEY_CURRENT_USER\\Software\\Khronos\\Vulkan\\ImplicitLayers", LAYER_TYPE_IMPLICIT); result.insert(result.begin(), user_registry_paths.begin(), user_registry_paths.end()); // Search for drivers specific layers - const std::vector &drivers_registry_paths = + const std::vector& drivers_registry_paths = LoadRegistrySystemLayers("HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Class\\...\\VulkanImplicitLayers"); result.insert(result.begin(), drivers_registry_paths.begin(), drivers_registry_paths.end()); #else if (VKC_PLATFORM == PLATFORM_MACOS) { - static const char *LAYERS_PATHS[] = { + static const char* LAYERS_PATHS[] = { "/usr/local/share/vulkan/implicit_layer.d", ".local/share/vulkan/implicit_layer.d", }; @@ -69,7 +70,7 @@ static std::vector GetImplicitLayerPaths() { result.push_back(LAYERS_PATHS[i]); } } else { - static const char *LAYERS_PATHS[] = { + static const char* LAYERS_PATHS[] = { "/usr/local/etc/vulkan/implicit_layer.d", "/usr/local/share/vulkan/implicit_layer.d", "/etc/vulkan/implicit_layer.d", @@ -98,21 +99,21 @@ std::vector GetExplicitLayerPaths() { std::vector result; #if VKC_ENV == VKC_ENV_WIN32 - const std::vector &admin_registry_paths = + const std::vector& admin_registry_paths = LoadRegistrySoftwareLayers("HKEY_LOCAL_MACHINE\\Software\\Khronos\\Vulkan\\ExplicitLayers", LAYER_TYPE_EXPLICIT); result.insert(result.begin(), admin_registry_paths.begin(), admin_registry_paths.end()); - const std::vector &user_registry_paths = + const std::vector& user_registry_paths = LoadRegistrySoftwareLayers("HKEY_CURRENT_USER\\Software\\Khronos\\Vulkan\\ExplicitLayers", LAYER_TYPE_EXPLICIT); result.insert(result.begin(), user_registry_paths.begin(), user_registry_paths.end()); // Search for drivers specific layers - const std::vector &drivers_registry_paths = + const std::vector& drivers_registry_paths = LoadRegistrySystemLayers("HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Class\\...\\VulkanExplicitLayers"); result.insert(result.begin(), drivers_registry_paths.begin(), drivers_registry_paths.end()); #else if (VKC_PLATFORM == PLATFORM_MACOS) { - static const char *LAYERS_PATHS[] = { + static const char* LAYERS_PATHS[] = { "/usr/local/share/vulkan/explicit_layer.d", ".local/share/vulkan/explicit_layer.d", }; @@ -121,7 +122,7 @@ std::vector GetExplicitLayerPaths() { result.push_back(LAYERS_PATHS[i]); } } else { - static const char *LAYERS_PATHS[] = { + static const char* LAYERS_PATHS[] = { "/usr/local/etc/vulkan/explicit_layer.d", "/usr/local/share/vulkan/explicit_layer.d", "/etc/vulkan/explicit_layer.d", @@ -148,12 +149,12 @@ std::vector GetExplicitLayerPaths() { LayerManager::LayerManager() {} -bool LayerManager::Load(const QJsonObject &json_root_object, ConfiguratorMode configurator_mode) { +bool LayerManager::Load(const QJsonObject& json_root_object, ConfiguratorMode configurator_mode) { this->available_layers.clear(); // LAYERS_PATHS_GUI if (json_root_object.value("layers") != QJsonValue::Undefined) { - const QJsonObject &json_layers_object = json_root_object.value("layers").toObject(); + const QJsonObject& json_layers_object = json_root_object.value("layers").toObject(); if (json_layers_object.value("last_layers_dir") != QJsonValue::Undefined) { this->last_layers_dir = json_layers_object.value("last_layers_dir").toString().toStdString(); @@ -164,11 +165,11 @@ bool LayerManager::Load(const QJsonObject &json_root_object, ConfiguratorMode co } if (json_layers_object.value("found") != QJsonValue::Undefined) { - const QJsonObject &json_layers_found_object = json_layers_object.value("found").toObject(); - const QStringList &json_layers_found_keys = json_layers_found_object.keys(); + const QJsonObject& json_layers_found_object = json_layers_object.value("found").toObject(); + const QStringList& json_layers_found_keys = json_layers_found_object.keys(); for (int i = 0, n = json_layers_found_keys.length(); i < n; ++i) { - const QJsonObject &json_status_object = json_layers_found_object.value(json_layers_found_keys[i]).toObject(); + const QJsonObject& json_status_object = json_layers_found_object.value(json_layers_found_keys[i]).toObject(); LayerDisplay layer; layer.id.manifest_path = json_layers_found_keys[i].toStdString(); @@ -187,7 +188,7 @@ bool LayerManager::Load(const QJsonObject &json_root_object, ConfiguratorMode co return true; } -bool LayerManager::Save(QJsonObject &json_root_object) const { +bool LayerManager::Save(QJsonObject& json_root_object) const { QJsonObject json_layers_object; json_layers_object.insert("validate_manifests", this->validate_manifests); json_layers_object.insert("last_layers_dir", this->last_layers_dir.RelativePath().c_str()); @@ -202,7 +203,7 @@ std::string LayerManager::Log() const { std::string log; for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { - const Layer *layer = &this->available_layers[i]; + const Layer* layer = &this->available_layers[i]; if (layer->type == LAYER_TYPE_IMPLICIT) { log += format(" * %s - %s (Auto: %s)", layer->key.c_str(), layer->api_version.str().c_str(), @@ -221,12 +222,12 @@ std::string LayerManager::Log() const { if (layer->type == LAYER_TYPE_IMPLICIT) { if (!layer->disable_env.empty()) { - const std::string &value = qEnvironmentVariableIsSet(layer->disable_env.c_str()) ? "set" : "not set"; + const std::string& value = qEnvironmentVariableIsSet(layer->disable_env.c_str()) ? "set" : "not set"; log += format(" '%s' is %s\n", layer->disable_env.c_str(), value.c_str()); } if (!layer->enable_env.empty()) { if (qEnvironmentVariableIsSet(layer->enable_env.c_str())) { - const std::string &value = qgetenv(layer->enable_env.c_str()).toStdString(); + const std::string& value = qgetenv(layer->enable_env.c_str()).toStdString(); log += format(" '%s' is set to '%s'\n", layer->enable_env.c_str(), value.c_str()); } else { log += format(" '%s' is not set to '%s'\n", layer->enable_env.c_str(), layer->enable_value.c_str()); @@ -246,7 +247,7 @@ bool LayerManager::Empty() const { return this->available_layers.empty(); } std::size_t LayerManager::Size() const { return this->available_layers.size(); } -std::vector LayerManager::GatherManifests(const std::string &layer_key) const { +std::vector LayerManager::GatherManifests(const std::string& layer_key) const { std::vector result; for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { @@ -266,7 +267,7 @@ std::vector LayerManager::GatherManifests(const std::string &layer_key) co return result; } -std::vector LayerManager::GatherVersions(const std::string &layer_key) const { +std::vector LayerManager::GatherVersions(const std::string& layer_key) const { std::vector result; for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { @@ -286,9 +287,9 @@ std::vector LayerManager::GatherVersions(const std::string &layer_key) return result; } -const Layer *LayerManager::Find(LayerId id, bool enable_only) const { +const Layer* LayerManager::Find(LayerId id, bool enable_only) const { for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { - const Layer &layer = this->available_layers[i]; + const Layer& layer = this->available_layers[i]; if (!layer.descriptor.enabled && enable_only) { continue; @@ -314,9 +315,9 @@ const Layer *LayerManager::Find(LayerId id, bool enable_only) const { return nullptr; } -Layer *LayerManager::Find(LayerId id, bool enable_only) { +Layer* LayerManager::Find(LayerId id, bool enable_only) { for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { - Layer &layer = this->available_layers[i]; + Layer& layer = this->available_layers[i]; if (!layer.descriptor.enabled && enable_only) { continue; @@ -342,9 +343,9 @@ Layer *LayerManager::Find(LayerId id, bool enable_only) { return nullptr; } -const Layer *LayerManager::Find(const std::string &layer_name, const Version &layer_version) const { +const Layer* LayerManager::Find(const std::string& layer_name, const Version& layer_version) const { if (layer_version == Version::LATEST) { - const std::vector &version = this->GatherVersions(layer_name); + const std::vector& version = this->GatherVersions(layer_name); if (version.empty()) { return nullptr; } @@ -361,7 +362,7 @@ const Layer *LayerManager::Find(const std::string &layer_name, const Version &la return this->Find(layer_name, latest); } else { - const Layer *newest = this->FindLastModified(layer_name, layer_version); + const Layer* newest = this->FindLastModified(layer_name, layer_version); if (newest != nullptr) { return newest; @@ -374,8 +375,8 @@ const Layer *LayerManager::Find(const std::string &layer_name, const Version &la return nullptr; } -const Layer *LayerManager::FindLastModified(const std::string &layer_name, const Version &version) const { - const Layer *result = nullptr; +const Layer* LayerManager::FindLastModified(const std::string& layer_name, const Version& version) const { + const Layer* result = nullptr; for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { if (!this->available_layers[i].descriptor.enabled) { @@ -400,7 +401,7 @@ const Layer *LayerManager::FindLastModified(const std::string &layer_name, const return result; } -const Layer *LayerManager::FindFromManifest(const Path &manifest_path, bool find_disabled_layers) const { +const Layer* LayerManager::FindFromManifest(const Path& manifest_path, bool find_disabled_layers) const { for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { if (!find_disabled_layers) { if (!this->available_layers[i].descriptor.enabled) { @@ -415,7 +416,7 @@ const Layer *LayerManager::FindFromManifest(const Path &manifest_path, bool find return nullptr; } -Layer *LayerManager::FindFromManifest(const Path &manifest_path, bool find_disabled_layers) { +Layer* LayerManager::FindFromManifest(const Path& manifest_path, bool find_disabled_layers) { for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { if (!find_disabled_layers) { if (!this->available_layers[i].descriptor.enabled) { @@ -432,7 +433,7 @@ Layer *LayerManager::FindFromManifest(const Path &manifest_path, bool find_disab void LayerManager::ApplyLayerDescriptor() { for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { - Layer &layer = this->available_layers[i]; + Layer& layer = this->available_layers[i]; auto it = this->layer_init.find(layer.manifest_path); if (it == this->layer_init.end()) { @@ -440,7 +441,7 @@ void LayerManager::ApplyLayerDescriptor() { } for (std::size_t j = 0, o = it->second.size(); j < o; ++j) { - const LayerDisplay &init = it->second[j]; + const LayerDisplay& init = it->second[j]; if (!init.id.key.empty()) { if (init.id.key != layer.key) { @@ -453,8 +454,8 @@ void LayerManager::ApplyLayerDescriptor() { } } -// Find all installed layers on the system. -void LayerManager::LoadAllInstalledLayers(ConfiguratorMode configurator_mode) { +// Locations searched for layer manifests, in search order. +std::array, LAYERS_PATHS_COUNT> LayerManager::BuildLayersSearchPaths() const { std::array, LAYERS_PATHS_COUNT> paths; // Search new layers @@ -476,18 +477,28 @@ void LayerManager::LoadAllInstalledLayers(ConfiguratorMode configurator_mode) { paths[LAYERS_PATHS_EXPLICIT_ENV_ADD] = GetEnvVariablePaths("VK_ADD_LAYER_PATH", LAYER_TYPE_EXPLICIT); // LAYERS_PATHS_SDK - paths[LAYERS_PATHS_SDK].push_back(Path(Path::SDK_EXPLICIT_LAYERS)); + const Path sdk_explicit_layers_path(Path::SDK_EXPLICIT_LAYERS); + if (!sdk_explicit_layers_path.Empty()) { + paths[LAYERS_PATHS_SDK].push_back(sdk_explicit_layers_path); + } // LAYERS_PATHS_GUI std::vector added_paths = this->BuildLayerPaths(); paths[LAYERS_PATHS_GUI].insert(paths[LAYERS_PATHS_GUI].begin(), added_paths.begin(), added_paths.end()); + return paths; +} + +// Find all installed layers on the system. +void LayerManager::LoadAllInstalledLayers(ConfiguratorMode configurator_mode) { + const std::array, LAYERS_PATHS_COUNT>& paths = this->BuildLayersSearchPaths(); + for (std::size_t group_index = 0, group_count = paths.size(); group_index < group_count; ++group_index) { const LayersPaths layers_path = static_cast(group_index); - const std::vector &paths_group = paths[group_index]; + const std::vector& paths_group = paths[group_index]; for (std::size_t i = 0, n = paths_group.size(); i < n; ++i) { - const std::vector &layers_paths = ::CollectLayersPaths(paths_group[i]); + const std::vector& layers_paths = ::CollectLayersPaths(paths_group[i]); for (std::size_t p = 0, o = layers_paths.size(); p < o; ++p) { this->LoadLayers(layers_paths[p], ::GetLayerType(layers_path), configurator_mode); @@ -498,7 +509,7 @@ void LayerManager::LoadAllInstalledLayers(ConfiguratorMode configurator_mode) { // this->ApplyLayerDescriptor(); } -LayerValidated LayerManager::Validate(const Path &layer_path, QString json_text, ConfiguratorMode configurator_mode) const { +LayerValidated LayerManager::Validate(const Path& layer_path, QString json_text, ConfiguratorMode configurator_mode) { JsonValidator validator; bool result = validator.Check(json_text); @@ -507,6 +518,10 @@ LayerValidated LayerManager::Validate(const Path &layer_path, QString json_text, default: { } break; case CONFIGURATOR_MODE_GUI: { + if (this->hide_validation_message_paths.find(layer_path) != this->hide_validation_message_paths.end()) { + break; + } + QMessageBox alert; alert.setWindowTitle("Failed to load a layer manifest..."); alert.setText(format("%s is not a valid layer file", layer_path.AbsolutePath().c_str()).c_str()); @@ -514,9 +529,13 @@ LayerValidated LayerManager::Validate(const Path &layer_path, QString json_text, alert.setIcon(QMessageBox::Critical); alert.setStandardButtons(QMessageBox::Yes | QMessageBox::No); alert.setDefaultButton(QMessageBox::Yes); + alert.setCheckBox(new QCheckBox("Do not show again for this layer manifest.")); int result = alert.exec(); + if (alert.checkBox()->isChecked()) { + this->hide_validation_message_paths.insert(layer_path); + } if (result == QMessageBox::Yes) { - const QString &selected_path = QFileDialog::getSaveFileName( + const QString& selected_path = QFileDialog::getSaveFileName( nullptr, format("Export %s validation log", layer_path.AbsolutePath().c_str()).c_str(), (AbsolutePath(Path::HOME) + "/" + layer_path.Basename() + "_log.txt").c_str(), "Log(*.txt)"); QFile log_file(selected_path); @@ -544,12 +563,12 @@ LayerValidated LayerManager::Validate(const Path &layer_path, QString json_text, return result ? LAYER_VALIDATE_PASS : LAYER_VALIDATE_FAIL; } -LayerDescriptor LayerManager::GetDescriptor(const Path &layer_path, const std::string &layer_key) const { +LayerDescriptor LayerManager::GetDescriptor(const Path& layer_path, const std::string& layer_key) const { auto it = layer_init.find(layer_path); if (it != layer_init.end()) { - const std::vector &data = it->second; + const std::vector& data = it->second; for (std::size_t i = 0, n = data.size(); i < n; ++i) { - const LayerDisplay &display = data[i]; + const LayerDisplay& display = data[i]; if (display.id.key == layer_key) { return display.descriptor; } @@ -559,7 +578,12 @@ LayerDescriptor LayerManager::GetDescriptor(const Path &layer_path, const std::s return LayerDescriptor(); } -LayerLoadStatus LayerManager::LoadLayers(const Path &layer_path, LayerType type, ConfiguratorMode configurator_mode) { +LayerLoadStatus LayerManager::LoadLayers(const Path& layer_path, LayerType type, ConfiguratorMode configurator_mode, + LayerValidated* validated) { + if (validated != nullptr) { + *validated = LAYER_VALIDATE_NONE; + } + QFile file(layer_path.AbsolutePath().c_str()); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { assert(0); @@ -572,7 +596,7 @@ LayerLoadStatus LayerManager::LoadLayers(const Path &layer_path, LayerType type, // Convert the text to a JSON document & validate it. // It does need to be a valid json formatted file. QJsonParseError json_parse_error; - const QJsonDocument &json_document = QJsonDocument::fromJson(json_text.toUtf8(), &json_parse_error); + const QJsonDocument& json_document = QJsonDocument::fromJson(json_text.toUtf8(), &json_parse_error); if (json_parse_error.error != QJsonParseError::NoError) { return LAYER_LOAD_INVALID; } @@ -583,19 +607,19 @@ LayerLoadStatus LayerManager::LoadLayers(const Path &layer_path, LayerType type, } Version file_format_version; - const QJsonObject &json_root_object = json_document.object(); + const QJsonObject& json_root_object = json_document.object(); if (json_root_object.value("file_format_version") != QJsonValue::Undefined) { file_format_version = Version(json_root_object.value("file_format_version").toString().toStdString().c_str()); } LayerLoadStatus status = LAYER_LOAD_ADDED; - const std::string &last_modified = layer_path.LastModified(); + const std::string& last_modified = layer_path.LastModified(); if (json_root_object.value("layers") != QJsonValue::Undefined) { - const QJsonArray &json_layers_array = json_root_object.value("layers").toArray(); + const QJsonArray& json_layers_array = json_root_object.value("layers").toArray(); for (int i = 0, n = json_layers_array.size(); i < n; ++i) { - const QJsonObject &json_layer_object = json_layers_array[i].toObject(); + const QJsonObject& json_layer_object = json_layers_array[i].toObject(); std::string key = ReadStringValue(json_layer_object, "name"); @@ -606,15 +630,20 @@ LayerLoadStatus LayerManager::LoadLayers(const Path &layer_path, LayerType type, LayerDescriptor descriptor = this->GetDescriptor(layer_path, key); - if (this->validate_manifests && (descriptor.last_modified != last_modified) || !descriptor.validated) { + if (this->validate_manifests && + (descriptor.last_modified != last_modified || descriptor.validated != LAYER_VALIDATE_PASS)) { descriptor.validated = this->Validate(layer_path, json_text, configurator_mode); descriptor.last_modified = last_modified; } + if (validated != nullptr && *validated != LAYER_VALIDATE_FAIL) { + *validated = descriptor.validated; + } + status = this->LoadLayer(json_layer_object, layer_path, type, file_format_version, descriptor); } } else if (json_root_object.value("layer") != QJsonValue::Undefined) { - const QJsonObject &json_layer_object = json_root_object.value("layer").toObject(); + const QJsonObject& json_layer_object = json_root_object.value("layer").toObject(); std::string layer_key = ReadStringValue(json_layer_object, "name"); @@ -625,11 +654,15 @@ LayerLoadStatus LayerManager::LoadLayers(const Path &layer_path, LayerType type, LayerDescriptor descriptor = this->GetDescriptor(layer_path, layer_key); if (this->validate_manifests && - (descriptor.last_modified != last_modified || descriptor.validated == LAYER_VALIDATE_NONE)) { + (descriptor.last_modified != last_modified || descriptor.validated != LAYER_VALIDATE_PASS)) { descriptor.validated = this->Validate(layer_path, json_text, configurator_mode); descriptor.last_modified = last_modified; } + if (validated != nullptr) { + *validated = descriptor.validated; + } + status = this->LoadLayer(json_layer_object, layer_path, type, file_format_version, descriptor); } else { assert(0); @@ -638,7 +671,7 @@ LayerLoadStatus LayerManager::LoadLayers(const Path &layer_path, LayerType type, return status; } -LayerLoadStatus LayerManager::LoadLayer(const QJsonObject &json_layer_object, const Path &layer_path, LayerType type, +LayerLoadStatus LayerManager::LoadLayer(const QJsonObject& json_layer_object, const Path& layer_path, LayerType type, Version file_format_version, LayerDescriptor descriptor) { Layer layer; layer.type = type; @@ -651,7 +684,7 @@ LayerLoadStatus LayerManager::LoadLayer(const QJsonObject &json_layer_object, co return status; } - Layer *duplicated_layer = this->Find(layer.GetId(), false); + Layer* duplicated_layer = this->Find(layer.GetId(), false); if (duplicated_layer != nullptr) { if (duplicated_layer->descriptor.removed) { duplicated_layer->descriptor.removed = false; @@ -671,7 +704,7 @@ LayerLoadStatus LayerManager::LoadLayer(const QJsonObject &json_layer_object, co } void LayerManager::RemoveLayer(LayerId id) { - Layer *layer = this->Find(id, false); + Layer* layer = this->Find(id, false); assert(layer); layer->descriptor.enabled = false; @@ -679,7 +712,7 @@ void LayerManager::RemoveLayer(LayerId id) { } void LayerManager::EnableLayer(LayerId id, bool enable) { - Layer *layer = this->Find(id, false); + Layer* layer = this->Find(id, false); assert(layer); layer->descriptor.enabled = enable; @@ -703,11 +736,14 @@ std::vector LayerManager::GatherLayerNames() const { return result; } -bool operator<(const LayerDisplay &a, const LayerDisplay &b) { - if (a.id.key == b.id.key) { +bool operator<(const LayerDisplay& a, const LayerDisplay& b) { + if (a.id.key != b.id.key) { + return a.id.key < b.id.key; + } else if (a.id.api_version != b.id.api_version) { return a.id.api_version < b.id.api_version; } else { - return a.id.key < b.id.key; + // Layers with the same key and API version but located in different paths are different layers + return a.id.manifest_path < b.id.manifest_path; } } @@ -715,7 +751,7 @@ std::map> LayerManager::BuildLayerStor std::map> result; for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { - const Layer *layer = &this->available_layers[i]; + const Layer* layer = &this->available_layers[i]; if (layer == nullptr) { continue; } @@ -748,7 +784,7 @@ std::map> LayerManager::BuildLayerStor for (auto it = this->layer_init.begin(), end = this->layer_init.end(); it != end; ++it) { auto jt = result.find(it->first); if (jt == result.end()) { - const std::vector &display = it->second; + const std::vector& display = it->second; std::map entry; for (std::size_t i = 0, n = display.size(); i < n; ++i) { @@ -766,7 +802,7 @@ std::set LayerManager::BuildLayerDisplayList() const { std::set result; for (std::size_t i = 0, n = this->available_layers.size(); i < n; ++i) { - const Layer *layer = &this->available_layers[i]; + const Layer* layer = &this->available_layers[i]; if (layer == nullptr) { continue; } diff --git a/vkconfig_core/layer_manager.h b/vkconfig_core/layer_manager.h index 22bf976237..d0eaf8f54d 100644 --- a/vkconfig_core/layer_manager.h +++ b/vkconfig_core/layer_manager.h @@ -25,6 +25,7 @@ #include "serialization.h" #include "type_layers_paths.h" +#include #include #include #include @@ -60,8 +61,10 @@ class LayerManager : public Serialize { const Layer* FindFromManifest(const Path& manifest_path, bool find_disabled_layers = false) const; Layer* FindFromManifest(const Path& manifest_path, bool find_disabled_layers = false); + std::array, LAYERS_PATHS_COUNT> BuildLayersSearchPaths() const; void LoadAllInstalledLayers(ConfiguratorMode configurator_mode); - LayerLoadStatus LoadLayers(const Path& layer_path, LayerType type, ConfiguratorMode configurator_mode); + LayerLoadStatus LoadLayers(const Path& layer_path, LayerType type, ConfiguratorMode configurator_mode, + LayerValidated* validated = nullptr); void RemoveLayer(LayerId id); void EnableLayer(LayerId id, bool enable); @@ -74,6 +77,7 @@ class LayerManager : public Serialize { std::vector GatherLayerNames() const; std::set gui_added_layers_paths; + std::set hide_validation_message_paths; std::vector available_layers; Path last_layers_dir = Path(Path::HOME); @@ -84,7 +88,7 @@ class LayerManager : public Serialize { } private: - LayerValidated Validate(const Path& layer_path, QString json_text, ConfiguratorMode configurator_mode) const; + LayerValidated Validate(const Path& layer_path, QString json_text, ConfiguratorMode configurator_mode); LayerLoadStatus LoadLayer(const QJsonObject& json_layer_object, const Path& layer_path, LayerType type, Version file_format_version, LayerDescriptor descriptor); diff --git a/vkconfig_core/parameter.cpp b/vkconfig_core/parameter.cpp index c4c04746d8..c108d4c7f3 100644 --- a/vkconfig_core/parameter.cpp +++ b/vkconfig_core/parameter.cpp @@ -101,6 +101,17 @@ void Parameter::SetExpanded(const std::string& setting_key, const std::string& f } } +void Parameter::ResetExpanded(const Layer& layer) { + for (std::size_t i = 0, n = this->settings.size(); i < n; ++i) { + const SettingMeta* setting_meta = ::FindSetting(layer.settings, this->settings[i]->key.c_str()); + if (setting_meta == nullptr) { + continue; + } + + this->settings[i]->ResetExpanded(*setting_meta); + } +} + ParameterRank GetParameterOrdering(const LayerManager& layers, const Parameter& parameter) { assert(!parameter.key.empty()); diff --git a/vkconfig_core/parameter.h b/vkconfig_core/parameter.h index c4ad0850cc..864cbe33bf 100644 --- a/vkconfig_core/parameter.h +++ b/vkconfig_core/parameter.h @@ -50,6 +50,7 @@ struct Parameter { bool IsAutoImplicitLayer() const; bool ApplyPresetSettings(const LayerPreset& preset); + void ResetExpanded(const Layer& layer); bool GetExpanded(const std::string& setting_key, const std::string& flag = "") const; void SetExpanded(const std::string& setting_key, const std::string& flag, bool expanded); diff --git a/vkconfig_core/path.cpp b/vkconfig_core/path.cpp index dc1e0f75de..2fa780ef23 100644 --- a/vkconfig_core/path.cpp +++ b/vkconfig_core/path.cpp @@ -439,7 +439,12 @@ static const std::string GetExplicitLayersDir() { }; static_assert(std::size(TABLE) == ENVIRONMENT_COUNT); - return GetSDKDir() + TABLE[VKC_ENV]; + const std::string sdk_dir = GetSDKDir(); + if (sdk_dir.empty()) { + return ""; + } + + return sdk_dir + TABLE[VKC_ENV]; } static const std::string GetVulkanDir() { diff --git a/vkconfig_core/setting.cpp b/vkconfig_core/setting.cpp index 485525a7e1..97bb5c9e2c 100644 --- a/vkconfig_core/setting.cpp +++ b/vkconfig_core/setting.cpp @@ -153,6 +153,8 @@ bool IsArray(SettingType type) { return type == SETTING_FLAGS || type == SETTING SettingData::SettingData(const std::string& key, const SettingType& type) : key(key), type(type) { assert(!this->key.empty()); } +void SettingData::ResetExpanded(const SettingMeta& meta) { this->expanded = meta.expanded; } + bool SettingData::Equal(const SettingData& other) const { if (this->key != other.key) return false; diff --git a/vkconfig_core/setting.h b/vkconfig_core/setting.h index f8e577da0e..f8f0de616c 100644 --- a/vkconfig_core/setting.h +++ b/vkconfig_core/setting.h @@ -158,6 +158,7 @@ struct SettingData { bool operator!=(const SettingData& other) const { return !this->Equal(other); } virtual void Reset() = 0; + virtual void ResetExpanded(const SettingMeta& meta); virtual void Copy(const SettingData* data) = 0; virtual bool Load(const QJsonObject& json_setting) = 0; virtual bool Save(QJsonObject& json_setting) const = 0; diff --git a/vkconfig_core/setting_flags.cpp b/vkconfig_core/setting_flags.cpp index 1c762e56ae..603d56d0df 100644 --- a/vkconfig_core/setting_flags.cpp +++ b/vkconfig_core/setting_flags.cpp @@ -212,7 +212,7 @@ SettingDataFlags::SettingDataFlags(const SettingMetaFlags* meta) : SettingData(m assert(meta != nullptr); for (std::size_t i = 0, n = meta->enum_values.size(); i < n; ++i) { - this->expanded_flags.insert(std::make_pair(meta->enum_values[i].key, true)); + this->expanded_flags.insert(std::make_pair(meta->enum_values[i].key, meta->enum_values[i].expanded)); } } @@ -221,6 +221,15 @@ void SettingDataFlags::Reset() { this->value = this->meta->default_value; } +void SettingDataFlags::ResetExpanded(const SettingMeta& meta) { + SettingData::ResetExpanded(meta); + + assert(this->meta != nullptr); + for (std::size_t i = 0, n = this->meta->enum_values.size(); i < n; ++i) { + this->expanded_flags[this->meta->enum_values[i].key] = this->meta->enum_values[i].expanded; + } +} + void SettingDataFlags::Copy(const SettingData* data) { if (data->type != this->type) return; diff --git a/vkconfig_core/setting_flags.h b/vkconfig_core/setting_flags.h index 365715fb60..dce2c156fb 100644 --- a/vkconfig_core/setting_flags.h +++ b/vkconfig_core/setting_flags.h @@ -99,6 +99,7 @@ struct SettingDataFlags : public SettingData { bool Save(QJsonObject& json_setting) const override; std::string Export(ExportMode export_mode) const override; void Reset() override; + void ResetExpanded(const SettingMeta& meta) override; void Append(const SettingDataFlags* data); void Remove(const SettingDataFlags* data); diff --git a/vkconfig_core/test/CMakeLists.txt b/vkconfig_core/test/CMakeLists.txt index c614d49fc4..ad93104c63 100644 --- a/vkconfig_core/test/CMakeLists.txt +++ b/vkconfig_core/test/CMakeLists.txt @@ -32,7 +32,7 @@ function(vkConfigTest NAME) add_executable(${TEST_NAME} ${TEST_FILE} ${FILES_JSON} ${FILES_TEXT} resources.qrc) set_target_properties(${TEST_NAME} PROPERTIES FOLDER "vkconfig/tests") if(Qt6_FOUND) - target_link_libraries(${TEST_NAME} vkconfig-core Vulkan::LayerSettings GTest::gtest GTest::gtest_main Qt6::Core Qt6::Gui Qt6::Widgets Qt6::Network) + target_link_libraries(${TEST_NAME} vkconfig-core Vulkan::LayerSettings GTest::gtest_main Qt6::Core Qt6::Gui Qt6::Widgets Qt6::Network) endif() target_compile_definitions(${TEST_NAME} PRIVATE CMAKE_CURRENT_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}") diff --git a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.bat b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.bat index 982803ea7a..dab74a2539 100644 --- a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.bat +++ b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.bat @@ -13,7 +13,7 @@ :: See the License for the specific language governing permissions and :: limitations under the License. :: -:: This code was generated by Vulkan Configurator 3.5.2 +:: This code was generated by Vulkan Configurator 3.5.3 :: Loader Settings: :: Vulkan Layers enabled and ordered: diff --git a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.sh b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.sh index 1eada28665..a7c8480846 100644 --- a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.sh +++ b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.sh @@ -13,7 +13,7 @@ #! See the License for the specific language governing permissions and #! limitations under the License. #! -#! This code was generated by Vulkan Configurator 3.5.2 +#! This code was generated by Vulkan Configurator 3.5.3 #! Loader Settings: #! Vulkan Layers enabled and ordered: diff --git a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.txt b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.txt index aa72adc4a3..a4510f15e2 100644 --- a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.txt +++ b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.txt @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -# This code was generated by Vulkan Configurator 3.5.2 +# This code was generated by Vulkan Configurator 3.5.3 # reference layer # ========================================== diff --git a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.vulkan_h_code b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.vulkan_h_code index 1b80dab7e9..55b364fe7b 100644 --- a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.vulkan_h_code +++ b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.vulkan_h_code @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This code was generated by Vulkan Configurator 3.5.2 + * This code was generated by Vulkan Configurator 3.5.3 */ #pragma once diff --git a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.vulkan_hpp_code b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.vulkan_hpp_code index 3a5ec63915..c96662f379 100644 --- a/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.vulkan_hpp_code +++ b/vkconfig_core/test/generated/VK_LAYER_LUNARG_reference_1_2_1.vulkan_hpp_code @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This code was generated by Vulkan Configurator 3.5.2 + * This code was generated by Vulkan Configurator 3.5.3 */ #pragma once diff --git a/vkconfig_core/test/generated/vk_layer_settings.bat b/vkconfig_core/test/generated/vk_layer_settings.bat index 982803ea7a..dab74a2539 100644 --- a/vkconfig_core/test/generated/vk_layer_settings.bat +++ b/vkconfig_core/test/generated/vk_layer_settings.bat @@ -13,7 +13,7 @@ :: See the License for the specific language governing permissions and :: limitations under the License. :: -:: This code was generated by Vulkan Configurator 3.5.2 +:: This code was generated by Vulkan Configurator 3.5.3 :: Loader Settings: :: Vulkan Layers enabled and ordered: diff --git a/vkconfig_core/test/generated/vk_layer_settings.sh b/vkconfig_core/test/generated/vk_layer_settings.sh index 1eada28665..a7c8480846 100644 --- a/vkconfig_core/test/generated/vk_layer_settings.sh +++ b/vkconfig_core/test/generated/vk_layer_settings.sh @@ -13,7 +13,7 @@ #! See the License for the specific language governing permissions and #! limitations under the License. #! -#! This code was generated by Vulkan Configurator 3.5.2 +#! This code was generated by Vulkan Configurator 3.5.3 #! Loader Settings: #! Vulkan Layers enabled and ordered: diff --git a/vkconfig_core/test/generated/vk_layer_settings.txt b/vkconfig_core/test/generated/vk_layer_settings.txt index aa72adc4a3..a4510f15e2 100644 --- a/vkconfig_core/test/generated/vk_layer_settings.txt +++ b/vkconfig_core/test/generated/vk_layer_settings.txt @@ -13,7 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -# This code was generated by Vulkan Configurator 3.5.2 +# This code was generated by Vulkan Configurator 3.5.3 # reference layer # ========================================== diff --git a/vkconfig_core/test/generated/vulkan_hpp_layer_settings.code b/vkconfig_core/test/generated/vulkan_hpp_layer_settings.code index 3a5ec63915..c96662f379 100644 --- a/vkconfig_core/test/generated/vulkan_hpp_layer_settings.code +++ b/vkconfig_core/test/generated/vulkan_hpp_layer_settings.code @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This code was generated by Vulkan Configurator 3.5.2 + * This code was generated by Vulkan Configurator 3.5.3 */ #pragma once diff --git a/vkconfig_core/test/generated/vulkan_layer_settings.code b/vkconfig_core/test/generated/vulkan_layer_settings.code index 1b80dab7e9..55b364fe7b 100644 --- a/vkconfig_core/test/generated/vulkan_layer_settings.code +++ b/vkconfig_core/test/generated/vulkan_layer_settings.code @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * This code was generated by Vulkan Configurator 3.5.2 + * This code was generated by Vulkan Configurator 3.5.3 */ #pragma once diff --git a/vkconfig_core/test/test_command_line.cpp b/vkconfig_core/test/test_command_line.cpp index 10511b5544..627bfcb4d8 100644 --- a/vkconfig_core/test/test_command_line.cpp +++ b/vkconfig_core/test/test_command_line.cpp @@ -276,6 +276,50 @@ TEST(test_command_line, usage_mode_layers_list) { EXPECT_EQ(HELP_DEFAULT, command_line.help); } +TEST(test_command_line, usage_mode_layers_list_verbose) { + static char* argv[] = {(char*)"vkconfig", (char*)"layers", (char*)"--list-verbose"}; + int argc = static_cast(std::size(argv)); + + CommandLine command_line(argc, argv); + + EXPECT_EQ(COMMAND_LAYERS, command_line.command); + EXPECT_EQ(COMMAND_RESET_SOFT, command_line.command_reset_arg); + EXPECT_EQ(COMMAND_LAYERS_VERBOSE, command_line.command_layers_arg); + EXPECT_EQ(COMMAND_LOADER_NONE, command_line.command_loader_arg); + EXPECT_EQ(COMMAND_DOC_NONE, command_line.command_doc_arg); + EXPECT_EQ(GENERATE_SETTINGS_TXT, command_line.generate_settings_mode); + EXPECT_TRUE(command_line.selected_layers_name.empty()); + EXPECT_STREQ("default", command_line.selected_configuration_name.c_str()); + EXPECT_TRUE(command_line.GetInputPath().Empty()); + EXPECT_STREQ("vk_layer_settings.txt", ::ConvertStandardSeparators(command_line.GetOutputPath().RelativePath()).c_str()); + EXPECT_FALSE(command_line.dry_run); + EXPECT_EQ(ERROR_NONE, command_line.error); + EXPECT_TRUE(command_line.error_args.empty()); + EXPECT_EQ(HELP_DEFAULT, command_line.help); +} + +TEST(test_command_line, usage_mode_layers_path) { + static char* argv[] = {(char*)"vkconfig", (char*)"layers", (char*)"--path"}; + int argc = static_cast(std::size(argv)); + + CommandLine command_line(argc, argv); + + EXPECT_EQ(COMMAND_LAYERS, command_line.command); + EXPECT_EQ(COMMAND_RESET_SOFT, command_line.command_reset_arg); + EXPECT_EQ(COMMAND_LAYERS_PATH, command_line.command_layers_arg); + EXPECT_EQ(COMMAND_LOADER_NONE, command_line.command_loader_arg); + EXPECT_EQ(COMMAND_DOC_NONE, command_line.command_doc_arg); + EXPECT_EQ(GENERATE_SETTINGS_TXT, command_line.generate_settings_mode); + EXPECT_TRUE(command_line.selected_layers_name.empty()); + EXPECT_STREQ("default", command_line.selected_configuration_name.c_str()); + EXPECT_TRUE(command_line.GetInputPath().Empty()); + EXPECT_STREQ("vk_layer_settings.txt", ::ConvertStandardSeparators(command_line.GetOutputPath().RelativePath()).c_str()); + EXPECT_FALSE(command_line.dry_run); + EXPECT_EQ(ERROR_NONE, command_line.error); + EXPECT_TRUE(command_line.error_args.empty()); + EXPECT_EQ(HELP_DEFAULT, command_line.help); +} + TEST(test_command_line, usage_mode_layers_surrender) { static char* argv[] = {(char*)"vkconfig", (char*)"layers", (char*)"--surrender"}; int argc = static_cast(std::size(argv)); diff --git a/vkconfig_core/test/test_layer_manager.cpp b/vkconfig_core/test/test_layer_manager.cpp index c24e2d92c8..c8c0a63f10 100644 --- a/vkconfig_core/test/test_layer_manager.cpp +++ b/vkconfig_core/test/test_layer_manager.cpp @@ -330,3 +330,20 @@ TEST(test_layer_manager, avoid_duplicate) { EXPECT_EQ(first_load_count, second_load_count); } + +TEST(test_layer_manager, LayerDisplay_same_version_different_paths) { + LayerDisplay layer_a; + layer_a.id.key = "VK_LAYER_LUNARG_test"; + layer_a.id.api_version = Version(1, 4, 363); + layer_a.id.manifest_path = Path("/path_a/VkLayer_test.json"); + + LayerDisplay layer_b = layer_a; + layer_b.id.manifest_path = Path("/path_b/VkLayer_test.json"); + + std::set layers; + layers.insert(layer_a); + layers.insert(layer_b); + layers.insert(layer_a); + + EXPECT_TRUE(layers.size() == 2); +} diff --git a/vkconfig_core/test/test_layer_preset.cpp b/vkconfig_core/test/test_layer_preset.cpp index 5ece200a04..8f4943962f 100644 --- a/vkconfig_core/test/test_layer_preset.cpp +++ b/vkconfig_core/test/test_layer_preset.cpp @@ -136,5 +136,5 @@ TEST(test_layer_preset, find_preset_index_missing_value) { ::CollectDefaultSettingData(layer.settings, layer_settings); int index = layer.FindPresetIndex(layer_settings); // missing preset values are ignored - EXPECT_EQ(index, 0); + EXPECT_EQ(index, 1); } diff --git a/vkconfig_core/test/test_path.cpp b/vkconfig_core/test/test_path.cpp index 8b73849220..a22d998ee6 100644 --- a/vkconfig_core/test/test_path.cpp +++ b/vkconfig_core/test/test_path.cpp @@ -26,6 +26,7 @@ #include #include +#include #include @@ -344,6 +345,28 @@ TEST(test_path, get_path_home_sdk) { EXPECT_STREQ(Path("~/VulkanSDK").AbsolutePath().c_str(), value.c_str()); } +TEST(test_path, get_path_sdk_explicit_layers_unset) { + const QByteArray vulkan_sdk = qgetenv("VULKAN_SDK"); + qunsetenv("VULKAN_SDK"); + + EXPECT_TRUE(Path(Path::SDK_EXPLICIT_LAYERS).Empty()); + + qputenv("VULKAN_SDK", vulkan_sdk); +} + +TEST(test_path, get_path_sdk_explicit_layers_set) { + const QByteArray vulkan_sdk = qgetenv("VULKAN_SDK"); + QTemporaryDir sdk_dir; + ASSERT_TRUE(sdk_dir.isValid()); + qputenv("VULKAN_SDK", sdk_dir.path().toUtf8()); + + const QString value(AbsolutePath(Path::SDK_EXPLICIT_LAYERS, false).c_str()); + EXPECT_TRUE(value.startsWith(AbsolutePath(Path::SDK, false).c_str())); + EXPECT_TRUE(value.endsWith(VKC_ENV == VKC_ENV_WIN32 ? "/Bin" : "/share/vulkan/explicit_layer.d")); + + qputenv("VULKAN_SDK", vulkan_sdk); +} + TEST(test_path, get_path_url_sdk) { const std::string value = AbsolutePath(Path::URL_SDK, false); const std::string expected = format("https://vulkan.lunarg.com/doc/sdk/%s.0/", Version::VKHEADER.str().c_str()); diff --git a/vkconfig_core/version.cpp b/vkconfig_core/version.cpp index 10bd33d0be..039f20b7ab 100644 --- a/vkconfig_core/version.cpp +++ b/vkconfig_core/version.cpp @@ -28,7 +28,7 @@ #include #include -const Version Version::VKCONFIG(3, 5, 2); +const Version Version::VKCONFIG(3, 5, 3); const Version Version::VKHEADER(VK_HEADER_VERSION_COMPLETE); const Version Version::NONE(0, 0, 0); const Version Version::LATEST(~0, ~0, ~0); diff --git a/vkconfig_core/vulkan_util.cpp b/vkconfig_core/vulkan_util.cpp index 3215294118..05f1329625 100644 --- a/vkconfig_core/vulkan_util.cpp +++ b/vkconfig_core/vulkan_util.cpp @@ -24,6 +24,7 @@ #include "../vkconfig_core/type_platform.h" #include "../vkconfig_core/util.h" +#include #include #include @@ -80,9 +81,22 @@ static const char *GetVulkanLibrary() { return TABLE[VKC_PLATFORM]; } +static bool LoadVulkanLibrary(QLibrary &library) { + if (VKC_PLATFORM == PLATFORM_MACOS && QCoreApplication::instance() != nullptr) { + // Use the Vulkan Loader bundled in vkconfig-gui.app first + library.setFileName(QCoreApplication::applicationDirPath() + "/../Frameworks/libvulkan.1.dylib"); + if (library.load()) { + return true; + } + } + + library.setFileName(GetVulkanLibrary()); + return library.load(); +} + VulkanFunctions::VulkanFunctions() { - QLibrary library(GetVulkanLibrary()); - if (!library.load()) { + QLibrary library; + if (!LoadVulkanLibrary(library)) { return; } diff --git a/vkconfig_gui/CHANGELOG.md b/vkconfig_gui/CHANGELOG.md index 289e98626e..0e24744ae4 100644 --- a/vkconfig_gui/CHANGELOG.md +++ b/vkconfig_gui/CHANGELOG.md @@ -1,3 +1,27 @@ +## Vulkan Configurator 3.5.3 - November 2026 +[Vulkan SDK 1.4.xxx.0](https://github.com/LunarG/VulkanTools/tree/vulkan-sdk-1.4.xxx) + +### Improvements: +- Bundle the Vulkan Loader in the macOS application bundle so Vulkan Configurator no longer requires a system wide Vulkan Loader installation +- Replace the use and disable external `vk_layer_settings.txt` file actions by a single toggle action +- Speed up layer manifest validation (validation layer manifest tested 18x faster) +- Change `vkconfig layers --path` to list the locations Vulkan Configurator searches for Vulkan layers and the layers found in each +- Update the *Portability* built-in configuration to use the `VP_LUNARG_desktop_baseline_2026` profile +- Enable layer manifest validation by default and report invalid layer manifests on each launch until "Do not show again" is checked for that manifest +- Report the number of layer manifests failing the schema validation when reloading layers +- Display the layer manifest last modified date in the *Vulkan Layers located on the system* list to identify layers with the same API version + +### Fixes: +- Fix macOS Dock icon remaining visible when Vulkan Configurator keeps running in the system tray +- Fix layer manifests being validated on load when manifest validation is disabled +- Fix layer settings tree ignoring the manifest `expanded` state by default and on settings reset +- Fix layer preset displayed as "User-Defined Settings" after settings reset when the default values match a layer preset +- Fix `vkconfig layers --list-verbose` command line argument showing the help +- Fix searching and trying to create an invalid `${VULKAN_SDK}` layers directory when `VULKAN_SDK` is not set +- Fix layer name, layer settings checkbox and layer versions not displayed when the selected layer has no settings +- Fix layer settings not displayed after selecting another layer version that has settings +- Fix only one layer displayed in the *Vulkan Layers located on the system* list when layers with the same API version are located in different paths + ## Vulkan Configurator 3.5.2 - September 2026 [Vulkan SDK 1.4.363.0](https://github.com/LunarG/VulkanTools/tree/vulkan-sdk-1.4.363) diff --git a/vkconfig_gui/dock.h b/vkconfig_gui/dock.h new file mode 100644 index 0000000000..6450bba789 --- /dev/null +++ b/vkconfig_gui/dock.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026 Valve Corporation + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Authors: + * - Christophe Riccio + */ + +#pragma once + +// Show or hide the application icon in the macOS Dock, the system tray icon is not affected +#if defined(__APPLE__) +void SetDockIconVisible(bool visible); +#else +inline void SetDockIconVisible(bool visible) { (void)visible; } +#endif diff --git a/vkconfig_gui/macOS/Resources/VulkanIcon.icns b/vkconfig_gui/macOS/Resources/VulkanIcon.icns index fb82fb7de2..9f17efc5f2 100644 Binary files a/vkconfig_gui/macOS/Resources/VulkanIcon.icns and b/vkconfig_gui/macOS/Resources/VulkanIcon.icns differ diff --git a/vkconfig_gui/macOS/dock.mm b/vkconfig_gui/macOS/dock.mm new file mode 100644 index 0000000000..97de8a90ec --- /dev/null +++ b/vkconfig_gui/macOS/dock.mm @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026 Valve Corporation + * Copyright (c) 2026 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Authors: + * - Christophe Riccio + */ + +#include "../dock.h" + +#import + +void SetDockIconVisible(bool visible) { + // An "accessory" application has no Dock icon and no menu bar but keeps its status bar items + [NSApp setActivationPolicy:visible ? NSApplicationActivationPolicyRegular : NSApplicationActivationPolicyAccessory]; +} diff --git a/vkconfig_gui/macOS/vkconfig.cmake b/vkconfig_gui/macOS/vkconfig.cmake index 40cd46128c..fd1b17f54c 100644 --- a/vkconfig_gui/macOS/vkconfig.cmake +++ b/vkconfig_gui/macOS/vkconfig.cmake @@ -17,9 +17,12 @@ +enable_language(OBJCXX) + add_executable(vkconfig-gui MACOSX_BUNDLE ${FILES_ALL} + ${CMAKE_CURRENT_SOURCE_DIR}/macOS/dock.mm ${CMAKE_CURRENT_SOURCE_DIR}/macOS/Resources/VulkanIcon.icns ) #set_target_properties(vkconfig PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/macOS/Info.plist) @@ -48,6 +51,20 @@ add_custom_command(TARGET vkconfig-gui POST_BUILD COMMENT "Running macdeployqt..." ) +# Bundle the Vulkan Loader so vkconfig doesn't rely on a system wide installation +if(TARGET Vulkan::Loader) + add_custom_command(TARGET vkconfig-gui POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory + "${CMAKE_CURRENT_BINARY_DIR}/vkconfig-gui.app/Contents/Frameworks" + COMMAND ${CMAKE_COMMAND} -E copy + "$" + "${CMAKE_CURRENT_BINARY_DIR}/vkconfig-gui.app/Contents/Frameworks/libvulkan.1.dylib" + COMMENT "Copying the Vulkan Loader to vkconfig-gui.app..." + ) +else() + message(WARNING "Vulkan::Loader not found, vkconfig-gui.app will rely on the system Vulkan Loader") +endif() + add_custom_command(TARGET vkconfig-gui POST_BUILD COMMAND cp "${CMAKE_CURRENT_SOURCE_DIR}/macOS/Info.plist" @@ -55,6 +72,13 @@ add_custom_command(TARGET vkconfig-gui POST_BUILD COMMENT "Copying Info.plist to vkconfig-gui.app..." ) +# The bundle was modified after linking so it must be signed again or macOS will kill it at launch +add_custom_command(TARGET vkconfig-gui POST_BUILD + COMMAND codesign --force --deep --sign - + "${CMAKE_CURRENT_BINARY_DIR}/vkconfig-gui.app" + COMMENT "Ad-hoc signing vkconfig-gui.app..." +) + set_target_properties(vkconfig-gui PROPERTIES SKIP_BUILD_RPATH FALSE) set_target_properties(vkconfig-gui PROPERTIES BUILD_WITH_INSTALL_RPATH TRUE) set_target_properties(vkconfig-gui PROPERTIES INSTALL_RPATH "") diff --git a/vkconfig_gui/mainwindow.cpp b/vkconfig_gui/mainwindow.cpp index 3c19918e3c..13839317ea 100644 --- a/vkconfig_gui/mainwindow.cpp +++ b/vkconfig_gui/mainwindow.cpp @@ -21,6 +21,7 @@ #include "mainwindow.h" #include "style.h" +#include "dock.h" #include "../vkconfig_core/configurator.h" #include "../vkconfig_core/util.h" @@ -232,20 +233,25 @@ void MainWindow::OnIconActivated(QSystemTrayIcon::ActivationReason reason) { break; case QSystemTrayIcon::DoubleClick: if (this->isMinimized() || this->isHidden()) { - this->hide(); - this->showNormal(); - this->setWindowState(Qt::WindowState::WindowActive); - this->UpdateUI(UPDATE_REBUILD_UI); + this->ShowFromTray(); } else { this->hide(); + SetDockIconVisible(false); } break; } } -void MainWindow::OnTrayActionShow() { +void MainWindow::OnTrayActionShow() { this->ShowFromTray(); } + +void MainWindow::ShowFromTray() { + SetDockIconVisible(true); + this->hide(); this->showNormal(); + this->setWindowState(Qt::WindowState::WindowActive); + this->raise(); + this->activateWindow(); this->UpdateUI(UPDATE_REBUILD_UI); } @@ -344,6 +350,11 @@ void MainWindow::closeEvent(QCloseEvent* event) { configurator.window_geometry = this->saveGeometry(); configurator.window_state = this->saveState(); + // Only the system tray icon remains when Vulkan Configurator keeps running + if (configurator.GetUseSystemTray()) { + SetDockIconVisible(false); + } + QMainWindow::closeEvent(event); } /* diff --git a/vkconfig_gui/mainwindow.h b/vkconfig_gui/mainwindow.h index d26410b173..9d1edbbc39 100644 --- a/vkconfig_gui/mainwindow.h +++ b/vkconfig_gui/mainwindow.h @@ -55,6 +55,7 @@ class MainWindow : public QMainWindow { // void showEvent(QShowEvent *event) override; bool eventFilter(QObject* target, QEvent* event) override; void changeEvent(QEvent* event) override; + void ShowFromTray(); QSystemTrayIcon* _tray_icon = nullptr; diff --git a/vkconfig_gui/resourcefiles/vulkan.ico b/vkconfig_gui/resourcefiles/vulkan.ico index 4574bd0873..6d7e75b753 100644 Binary files a/vkconfig_gui/resourcefiles/vulkan.ico and b/vkconfig_gui/resourcefiles/vulkan.ico differ diff --git a/vkconfig_gui/settings_tree.cpp b/vkconfig_gui/settings_tree.cpp index c494f4b282..e192921d24 100644 --- a/vkconfig_gui/settings_tree.cpp +++ b/vkconfig_gui/settings_tree.cpp @@ -60,33 +60,42 @@ void SettingsTreeManager::CreateGUI() { this->CleanupGUI(); Configurator& configurator = Configurator::Get(); - if (!configurator.HasActiveParameter() || !configurator.HasActiveSettings()) { + if (!configurator.HasActiveParameter() || !configurator.HasEnabledUI(ENABLE_UI_LAYERS)) { return; } Parameter* parameter = configurator.GetActiveParameter(); - if (parameter->builtin == LAYER_BUILTIN_NONE) { - if (configurator.layers.FindFromManifest(parameter->manifest) == nullptr) { - Configuration* configuration = configurator.GetActiveConfiguration(); - configuration->SwitchLayerLatest(configurator.layers, parameter->key); - } + if (parameter->builtin != LAYER_BUILTIN_NONE) { + return; } - // this->RefreshVersion(); + if (configurator.layers.FindFromManifest(parameter->manifest) == nullptr) { + if (configurator.layers.Find(parameter->key, Version::LATEST) == nullptr) { + return; + } + + Configuration* configuration = configurator.GetActiveConfiguration(); + configuration->SwitchLayerLatest(configurator.layers, parameter->key); + } + // The layer is displayed even when it doesn't have any setting so that the user can still select the layer version const Layer* layer = configurator.layers.FindFromManifest(parameter->manifest); + if (layer == nullptr) { + return; + } + + // Make sure the parameter has the setting data of the selected layer version + ::CollectDefaultSettingData(layer->settings, parameter->settings); std::string title = parameter->key; - if (layer != nullptr) { - if (layer->status != STATUS_STABLE) { - title += format(" (%s)", GetToken(layer->status)); - } + if (layer->status != STATUS_STABLE) { + title += format(" (%s)", GetToken(layer->status)); } // title.erase(0, strlen("VK_LAYER_")); this->ui->configurations_group_box_settings->blockSignals(true); this->ui->configurations_group_box_settings->setTitle(format("%s:", title.c_str()).c_str()); - this->ui->configurations_group_box_settings->setEnabled(configurator.HasEnabledUI(ENABLE_UI_SETTINGS)); + this->ui->configurations_group_box_settings->setEnabled(true); this->ui->configurations_group_box_settings->setCheckable(!configurator.GetActiveConfiguration()->override_settings); this->ui->configurations_group_box_settings->setChecked(parameter->override_settings); this->ui->configurations_group_box_settings->blockSignals(false); @@ -97,53 +106,7 @@ void SettingsTreeManager::CreateGUI() { parameter->override_settings); this->ui->configurations_settings_reset->setVisible(!layer->presets.empty()); - const std::vector& layer_versions = configurator.layers.GatherManifests(parameter->key); - this->ui->configurations_versions->setEnabled(true); - this->ui->configurations_versions->setVisible(!layer_versions.empty()); - if (!layer_versions.empty()) { - const Layer* layer_select = configurator.layers.FindFromManifest(parameter->manifest); - const Layer* layer_latest = configurator.layers.Find(parameter->key, Version::LATEST); - - this->ui->configurations_versions->blockSignals(true); - this->ui->configurations_versions->clear(); - - this->layer_version_path.clear(); - - const std::string& latest_label = "Latest - " + layer_latest->manifest_path.AbsolutePath(); - this->ui->configurations_versions->addItem(latest_label.c_str()); - this->ui->configurations_versions->setItemData(0, layer_latest->manifest_path.AbsolutePath().c_str(), Qt::ToolTipRole); - - this->layer_version_path.push_back(layer_latest->manifest_path); - - int version_index = 0; - for (std::size_t i = 0, n = layer_versions.size(); i < n; ++i) { - if (layer_versions[i] == parameter->manifest) { - version_index = this->ui->configurations_versions->count(); - } - - const Layer* layer_version = configurator.layers.FindFromManifest(layer_versions[i]); - - const int current_index = this->ui->configurations_versions->count(); - - const std::string& label = layer_version->api_version.str() + " - " + layer_version->manifest_path.AbsolutePath(); - - this->ui->configurations_versions->addItem(label.c_str()); - this->ui->configurations_versions->setItemData(current_index, layer_version->manifest_path.AbsolutePath().c_str(), - Qt::ToolTipRole); - - this->layer_version_path.push_back(layer_version->manifest_path); - } - - if (parameter->api_version != Version::LATEST) { - this->ui->configurations_versions->setCurrentIndex(version_index); - } - - this->ui->configurations_versions->blockSignals(false); - - if (layer_select != nullptr) { - this->ui->configurations_versions->setToolTip(layer_select->manifest_path.AbsolutePath().c_str()); - } - } + this->BuildVersions(*parameter); // preset combobox { @@ -453,6 +416,60 @@ void SettingsTreeManager::BuildTreeItem(QTreeWidgetItem* parent, const SettingMe } } +void SettingsTreeManager::BuildVersions(const Parameter& parameter) { + Configurator& configurator = Configurator::Get(); + + const std::vector& layer_versions = configurator.layers.GatherManifests(parameter.key); + this->ui->configurations_versions->setEnabled(true); + this->ui->configurations_versions->setVisible(!layer_versions.empty()); + if (layer_versions.empty()) { + return; + } + + const Layer* layer_select = configurator.layers.FindFromManifest(parameter.manifest); + const Layer* layer_latest = configurator.layers.Find(parameter.key, Version::LATEST); + + this->ui->configurations_versions->blockSignals(true); + this->ui->configurations_versions->clear(); + + this->layer_version_path.clear(); + + const std::string& latest_label = "Latest - " + layer_latest->manifest_path.AbsolutePath(); + this->ui->configurations_versions->addItem(latest_label.c_str()); + this->ui->configurations_versions->setItemData(0, layer_latest->manifest_path.AbsolutePath().c_str(), Qt::ToolTipRole); + + this->layer_version_path.push_back(layer_latest->manifest_path); + + int version_index = 0; + for (std::size_t i = 0, n = layer_versions.size(); i < n; ++i) { + if (layer_versions[i] == parameter.manifest) { + version_index = this->ui->configurations_versions->count(); + } + + const Layer* layer_version = configurator.layers.FindFromManifest(layer_versions[i]); + + const int current_index = this->ui->configurations_versions->count(); + + const std::string& label = layer_version->api_version.str() + " - " + layer_version->manifest_path.AbsolutePath(); + + this->ui->configurations_versions->addItem(label.c_str()); + this->ui->configurations_versions->setItemData(current_index, layer_version->manifest_path.AbsolutePath().c_str(), + Qt::ToolTipRole); + + this->layer_version_path.push_back(layer_version->manifest_path); + } + + if (parameter.api_version != Version::LATEST) { + this->ui->configurations_versions->setCurrentIndex(version_index); + } + + this->ui->configurations_versions->blockSignals(false); + + if (layer_select != nullptr) { + this->ui->configurations_versions->setToolTip(layer_select->manifest_path.AbsolutePath().c_str()); + } +} + void SettingsTreeManager::BuildTree() { Configurator& configurator = Configurator::Get(); Parameter* parameter = configurator.GetActiveParameter(); @@ -497,13 +514,14 @@ void SettingsTreeManager::OnSettingsResetted() { Parameter* parameter = configurator.GetActiveParameter(); assert(parameter != nullptr); - const Layer* layer = configurator.layers.Find(parameter->key.c_str(), parameter->api_version); + const Layer* layer = configurator.layers.FindFromManifest(parameter->manifest); if (layer == nullptr) { return; } const LayerPreset& preset = layer->presets[Layer::DEFAULT_PRESET]; parameter->ApplyPresetSettings(preset); + parameter->ResetExpanded(*layer); this->RefreshPresetLabel(); configurator.Override(OVERRIDE_AREA_LAYERS_SETTINGS_BIT); @@ -522,7 +540,7 @@ void SettingsTreeManager::OnPresetChanged(int combox_preset_index) { return; } - const Layer* layer = configurator.layers.Find(parameter->key.c_str(), parameter->api_version); + const Layer* layer = configurator.layers.FindFromManifest(parameter->manifest); if (layer == nullptr) { return; } @@ -594,6 +612,18 @@ void SettingsTreeManager::RefreshItem(RefreshAreas refresh_areas, QTreeWidgetIte } } + TreeItem* tree_item = dynamic_cast(parent); + if (tree_item != nullptr) { + Configurator& configurator = Configurator::Get(); + Parameter* parameter = configurator.GetActiveParameter(); + if (parameter != nullptr) { + bool is_expanded = tree_item->flag.empty() ? parameter->GetExpanded(tree_item->key) + : parameter->GetExpanded(tree_item->key, tree_item->flag); + + parent->setExpanded(is_expanded); + } + } + for (int i = 0, n = parent->childCount(); i < n; ++i) { QTreeWidgetItem* child = parent->child(i); if (child == nullptr) { diff --git a/vkconfig_gui/settings_tree.h b/vkconfig_gui/settings_tree.h index 52692056bb..1debc5c572 100644 --- a/vkconfig_gui/settings_tree.h +++ b/vkconfig_gui/settings_tree.h @@ -54,22 +54,23 @@ class SettingsTreeManager : public QObject { void OnPresetChanged(int combox_preset_index); void OnSettingsResetted(); - void on_item_collapsed(QTreeWidgetItem *item); - void on_item_expanded(QTreeWidgetItem *item); + void on_item_collapsed(QTreeWidgetItem* item); + void on_item_expanded(QTreeWidgetItem* item); Q_SIGNALS: void signalLayerVersionChanged(); private: - SettingsTreeManager(const SettingsTreeManager &) = delete; - SettingsTreeManager &operator=(const SettingsTreeManager &) = delete; + SettingsTreeManager(const SettingsTreeManager&) = delete; + SettingsTreeManager& operator=(const SettingsTreeManager&) = delete; - void SetSettingExpanded(const std::string &key, const std::string &flag, bool expanded); + void SetSettingExpanded(const std::string& key, const std::string& flag, bool expanded); + void BuildVersions(const Parameter& parameter); void BuildTree(); - void BuildTreeItem(QTreeWidgetItem *parent, const SettingMeta &meta); + void BuildTreeItem(QTreeWidgetItem* parent, const SettingMeta& meta); - void RefreshItem(RefreshAreas refresh_areas, QTreeWidgetItem *parent); + void RefreshItem(RefreshAreas refresh_areas, QTreeWidgetItem* parent); std::shared_ptr ui; // LayerVersionComboBox *layer_version = nullptr; diff --git a/vkconfig_gui/source/vulkan.png b/vkconfig_gui/source/vulkan.png new file mode 100644 index 0000000000..4871db9f83 Binary files /dev/null and b/vkconfig_gui/source/vulkan.png differ diff --git a/vkconfig_gui/tab_configurations.cpp b/vkconfig_gui/tab_configurations.cpp index 1fc94bcc52..e4e08b9b8f 100644 --- a/vkconfig_gui/tab_configurations.cpp +++ b/vkconfig_gui/tab_configurations.cpp @@ -514,32 +514,20 @@ bool TabConfigurations::EventFilter(QObject* target, QEvent* event) { menu.addSeparator(); - QAction* action_use_external_settings = new QAction("Use External vk_layer_settings.txt file...", nullptr); - action_use_external_settings->setCheckable(true); - Configuration* configuration = configurator.GetActiveConfiguration(); - if (configuration != nullptr) { - action_use_external_settings->setChecked(configuration->override_settings); - if (configuration->override_settings) { - action_use_external_settings->setToolTip( - "Select another external layer settings file to control layer settings instead of Vulkan Configurator UI."); - } else { - action_use_external_settings->setToolTip( - "Disable the layer settings control from Vulkan Configurator UI to use an external file."); - } - } - action_use_external_settings->setEnabled(item != nullptr); - menu.addAction(action_use_external_settings); - - QAction* action_disable_external_settings = new QAction("Disable External vk_layer_settings.txt file", nullptr); - if (configuration != nullptr) { - action_disable_external_settings->setEnabled(configuration->override_settings); - if (configuration->override_settings) { - action_disable_external_settings->setToolTip("Restore the layer settings control from Vulkan Configurator UI."); - } + const Configuration* configuration = configurator.GetActiveConfiguration(); + const bool use_external_settings = configuration != nullptr && configuration->override_settings; + + QAction* action_toggle_external_settings = new QAction("Use External vk_layer_settings.txt file...", nullptr); + action_toggle_external_settings->setCheckable(true); + action_toggle_external_settings->setChecked(use_external_settings); + if (use_external_settings) { + action_toggle_external_settings->setToolTip("Restore the layer settings control from Vulkan Configurator UI."); } else { - action_disable_external_settings->setEnabled(false); + action_toggle_external_settings->setToolTip( + "Disable the layer settings control from Vulkan Configurator UI to use an external file."); } - menu.addAction(action_disable_external_settings); + action_toggle_external_settings->setEnabled(item != nullptr && configuration != nullptr); + menu.addAction(action_toggle_external_settings); menu.addSeparator(); @@ -640,10 +628,12 @@ bool TabConfigurations::EventFilter(QObject* target, QEvent* event) { this->GenerateClicked(GENERATE_SETTINGS_MARKDOWN); } else if (action == action_export_html) { this->GenerateClicked(GENERATE_SETTINGS_HTML); - } else if (action == action_use_external_settings) { - this->on_configuration_settings_file_search_pressed(); - } else if (action == action_disable_external_settings) { - this->on_configuration_settings_file_disable_pressed(); + } else if (action == action_toggle_external_settings) { + if (use_external_settings) { + this->on_configuration_settings_file_disable_pressed(); + } else { + this->on_configuration_settings_file_search_pressed(); + } } } } else if (target == this->ui->configurations_layers_list) { diff --git a/vkconfig_gui/tab_layers.cpp b/vkconfig_gui/tab_layers.cpp index 31d672ea8e..3ec64a2258 100644 --- a/vkconfig_gui/tab_layers.cpp +++ b/vkconfig_gui/tab_layers.cpp @@ -195,6 +195,7 @@ void TabLayers::on_layers_reload_pressed() { Configurator &configurator = Configurator::Get(); std::vector layers_count(LAYER_LOAD_COUNT, 0); + int layers_validation_failed_count = 0; const std::vector &layers_paths = ::CollectLayersPaths(new_path); @@ -209,8 +210,13 @@ void TabLayers::on_layers_reload_pressed() { this->ui->layers_progress->setValue(static_cast(i + 1)); this->ui->layers_progress->update(); - LayerLoadStatus status = configurator.layers.LoadLayers(layers_paths[i], LAYER_TYPE_EXPLICIT, configurator.mode); + LayerValidated validated = LAYER_VALIDATE_NONE; + LayerLoadStatus status = + configurator.layers.LoadLayers(layers_paths[i], LAYER_TYPE_EXPLICIT, configurator.mode, &validated); ++layers_count[status]; + if (validated == LAYER_VALIDATE_FAIL) { + ++layers_validation_failed_count; + } std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::milliseconds(10)); } @@ -234,6 +240,9 @@ void TabLayers::on_layers_reload_pressed() { text += format(" - %d layer manifests added.\n", layers_count[LAYER_LOAD_ADDED]); text += format(" - %d layer manifests reloaded.\n", layers_count[LAYER_LOAD_RELOADED]); text += format(" - %d layer manifests unmodified.", layers_count[LAYER_LOAD_UNMODIFIED]); + if (configurator.layers.validate_manifests) { + text += format("\n - %d layer manifests failed the schema validation.", layers_validation_failed_count); + } QMessageBox message; message.setIcon(QMessageBox::Information); diff --git a/vkconfig_gui/vkconfig.pro b/vkconfig_gui/vkconfig.pro index 8dfc52ded6..ad2d1f1a82 100644 --- a/vkconfig_gui/vkconfig.pro +++ b/vkconfig_gui/vkconfig.pro @@ -6,9 +6,8 @@ CONFIG += sdk_no_version_check INCLUDEPATH += ../external/Debug/64/Vulkan-Headers/include INCLUDEPATH += ../external/Vulkan-Headers/include INCLUDEPATH += ../Vulkan-Headers/include - -# Ignore JSON validation -DEFINES += JSON_VALIDATION_OFF +INCLUDEPATH += ../external/Debug/64/valijson/build/install/include +INCLUDEPATH += ../external/valijson/build/install/include # The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings @@ -129,6 +128,7 @@ SOURCES += \ style.cpp HEADERS += \ + dock.h \ ../vkconfig_core/is_dll_32.h \ ../vkconfig_core/application_singleton.h \ ../vkconfig_core/bitfield.h \ @@ -252,6 +252,9 @@ macx: { QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.15 +OBJECTIVE_SOURCES += macOS/dock.mm +LIBS += -framework AppKit + QMAKE_INFO_PLIST = macOS/Info.plist RC_FILE = macOS/Resources/VulkanIcon.icns } diff --git a/vkconfig_gui/widget_tab_layers_path.cpp b/vkconfig_gui/widget_tab_layers_path.cpp index 4da507750b..23e8786d71 100644 --- a/vkconfig_gui/widget_tab_layers_path.cpp +++ b/vkconfig_gui/widget_tab_layers_path.cpp @@ -26,12 +26,20 @@ #include #include +#include + LayerWidget::LayerWidget(const Layer& layer) : layer_id(layer.GetId()) { const Configurator& configurator = Configurator::Get(); const std::string status = layer.status == STATUS_STABLE ? "" : format(" (%s)", ::GetToken(layer.status)); - const std::string text = format("%s - %s%s - %s layer", layer.key.c_str(), layer.api_version.str().c_str(), status.c_str(), - ::ToLowerCase(::GetToken(layer.type)).c_str()); + + // Identify layers with the same key and API version located in different paths + std::string last_modified = layer.manifest_path.LastModified(); + std::replace(last_modified.begin(), last_modified.end(), 'T', ' '); + const std::string modified = last_modified.empty() ? "" : format(" (%s)", last_modified.c_str()); + + const std::string text = format("%s - %s%s - %s layer%s", layer.key.c_str(), layer.api_version.str().c_str(), status.c_str(), + ::ToLowerCase(::GetToken(layer.type)).c_str(), modified.c_str()); this->setText(text.c_str()); this->setToolTip(format("%s", layer.manifest_path.AbsolutePath().c_str()).c_str());