From 6ac2bb682a1428df11647a2096e3fe8a3a834a72 Mon Sep 17 00:00:00 2001 From: BZLZHH Date: Sun, 29 Nov 2026 09:34:44 +0800 Subject: [PATCH] [Feat] (Backend selection, configuration, tests): prefer usable hardware Vulkan by default --- MobileGL/Config.h | 1 + MobileGL/ConfigLoader.cpp | 11 +- MobileGL/Init.cpp | 9 ++ .../DirectVulkan/Renderer/SwapchainObject.cpp | 30 ++-- .../DirectVulkan/Renderer/SwapchainObject.h | 3 + .../DirectVulkan/Renderer/VulkanRenderer.cpp | 18 ++- .../DirectVulkan/Renderer/VulkanRenderer.h | 9 +- .../Renderer/VulkanRendererDevice.cpp | 147 ++++++++++++------ .../MG_IntegrationTest/Harness/HeadlessGL.cpp | 21 +-- MobileGL/MG_Remote/Server/ServerMain.cpp | 1 + MobileGL/MG_Test/Util/ConfigFileTest.cpp | 3 + README.md | 2 +- userguide/configuration.md | 6 +- 13 files changed, 183 insertions(+), 78 deletions(-) diff --git a/MobileGL/Config.h b/MobileGL/Config.h index dede64b0..35a89d39 100644 --- a/MobileGL/Config.h +++ b/MobileGL/Config.h @@ -19,6 +19,7 @@ namespace MobileGL::MG_Config { inline const Uint64 CacheVersion = 0; extern BackendType ActiveBackendType; + extern Bool AutoSelectBackend; // Tri-state override for device-specific quirks: Auto lets the detected device decide, // ForceOn/ForceOff bypass the detection in either direction. ForceOn only bypasses the diff --git a/MobileGL/ConfigLoader.cpp b/MobileGL/ConfigLoader.cpp index 7c17cd96..592e7dd5 100644 --- a/MobileGL/ConfigLoader.cpp +++ b/MobileGL/ConfigLoader.cpp @@ -29,6 +29,7 @@ namespace MobileGL::MG_Config { // Zero/default-initialized at static-init time (all fields have constexpr-friendly // defaults), so it is safe to read even if MG_ConfigLoader::Init has not run yet. FeaturesTable Features; + Bool AutoSelectBackend = false; #if MOBILEGL_BUILD_DISAGGREGATED // Same contract, and for the same reason: MG_Backend::Init() reads Transport, and a // build order that put it before MG_ConfigLoader::Init() must see Monolith rather than @@ -461,7 +462,10 @@ namespace MobileGL::MG_ConfigLoader { inline void InitBackendType() { String backendTypeStr; - QueryEnvVariable("MOBILEGL_BACKEND_TYPE", backendTypeStr, "DirectGLES"); + constexpr const char* key = "MOBILEGL_BACKEND_TYPE"; + const auto configured = acceptedEnvVariablesMap->find(key); + MG_Config::AutoSelectBackend = configured == acceptedEnvVariablesMap->end(); + if (!MG_Config::AutoSelectBackend) backendTypeStr = configured->second; #if defined(__ANDROID__) // An Android app that hosts the library sets the environment itself, before the library // loads; the debug property is how a developer picks the backend for such a process @@ -471,6 +475,7 @@ namespace MobileGL::MG_ConfigLoader { MGLOG_I("Config: debug.mobilegl.backend=%s overrides MOBILEGL_BACKEND_TYPE=%s", property, backendTypeStr.c_str()); backendTypeStr = property; + MG_Config::AutoSelectBackend = false; } #endif #define ENTRY(backendType) \ @@ -479,6 +484,10 @@ namespace MobileGL::MG_ConfigLoader { MGLOG_I("Config: Active backend type set to " #backendType); \ return; \ } + if (MG_Config::AutoSelectBackend) { + MG_Config::ActiveBackendType = BackendType::DirectGLES; + return; + } ENTRY(DirectGLES) ENTRY(DirectVulkan) ENTRY(Unknown) diff --git a/MobileGL/Init.cpp b/MobileGL/Init.cpp index bb9f5798..adfd2767 100644 --- a/MobileGL/Init.cpp +++ b/MobileGL/Init.cpp @@ -10,6 +10,7 @@ #include "Config.h" #include #include +#include #include #include #include @@ -135,6 +136,14 @@ namespace MobileGL { MG_Util::Debug::InitFile(); MGLOG_I("Initializing MobileGL..."); MG_ConfigLoader::Init(); + if (MG_Config::AutoSelectBackend) { + if (MG_Backend::DirectVulkan::VulkanRenderer::ProbeDefaultBackend()) { + MG_Config::ActiveBackendType = BackendType::DirectVulkan; + MGLOG_I("Config: automatically selected DirectVulkan"); + } else { + MGLOG_I("Config: automatically selected DirectGLES"); + } + } MGLOG_I("Config loaded"); // Immediately after the config load and before anything can count: the MGPipe // boundary counters latch their enable flag here, so every counting site in the diff --git a/MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.cpp b/MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.cpp index 73c8da16..418f5ef7 100644 --- a/MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.cpp +++ b/MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.cpp @@ -95,23 +95,31 @@ namespace MobileGL::MG_Backend::DirectVulkan { VkSurfaceKHR surface) { SwapchainCapabilities swapchainCapabilities{}; - VK_VERIFY( - vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &swapchainCapabilities.capabilities)); + if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &swapchainCapabilities.capabilities) != + VK_SUCCESS) + return {}; Uint32 formatCount = 0; - VK_VERIFY(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, nullptr)); + if (vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, nullptr) != VK_SUCCESS) + return {}; if (formatCount != 0) { swapchainCapabilities.surfaceFormats.resize(formatCount); - VK_VERIFY(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, - swapchainCapabilities.surfaceFormats.data())); + if (vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, + swapchainCapabilities.surfaceFormats.data()) != VK_SUCCESS) + return {}; + swapchainCapabilities.surfaceFormats.resize(formatCount); } Uint32 presentModeCount = 0; - VK_VERIFY(vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, nullptr)); + if (vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, nullptr) != + VK_SUCCESS) + return {}; if (presentModeCount != 0) { swapchainCapabilities.presentModes.resize(presentModeCount); - VK_VERIFY(vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, - swapchainCapabilities.presentModes.data())); + if (vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, + swapchainCapabilities.presentModes.data()) != VK_SUCCESS) + return {}; + swapchainCapabilities.presentModes.resize(presentModeCount); } return swapchainCapabilities; @@ -174,8 +182,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { Uint32 graphicsQueueFamily, Uint32 presentQueueFamily, Uint32 minImageCountHint, Uint32 extraImageCount, VkExtent2D desiredExtent, Optional swapInterval) { const auto swapchainCapabilities = GetSwapchainCapabilities(physicalDevice, surface); - MOBILEGL_ASSERT(swapchainCapabilities.IsComplete(), - "SwapchainObject::Create failed: incomplete swapchain capabilities"); + if (!swapchainCapabilities.IsComplete()) throw RuntimeError("Incomplete Vulkan swapchain capabilities"); MGLOG_I("Got %d surface formats:", swapchainCapabilities.surfaceFormats.size()); for (const auto& sf : swapchainCapabilities.surfaceFormats) { @@ -227,8 +234,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { } createInfo.imageArrayLayers = 1; - const VkImageUsageFlags requiredImageUsage = - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + const VkImageUsageFlags requiredImageUsage = RequiredImageUsage; MOBILEGL_ASSERT((swapchainCaps.supportedUsageFlags & requiredImageUsage) == requiredImageUsage, "Swapchain does not support required usage flags (COLOR_ATTACHMENT | TRANSFER_DST). " "supportedUsageFlags=0x%x", diff --git a/MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.h b/MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.h index a5d8804c..8b92e918 100644 --- a/MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.h +++ b/MobileGL/MG_Backend/DirectVulkan/Renderer/SwapchainObject.h @@ -15,6 +15,9 @@ namespace MobileGL::MG_Backend::DirectVulkan { class SwapchainObject { public: + static constexpr VkImageUsageFlags RequiredImageUsage = + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + struct SwapchainCapabilities { VkSurfaceCapabilitiesKHR capabilities; Vector surfaceFormats; diff --git a/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.cpp b/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.cpp index e7f1b1af..769b4182 100644 --- a/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.cpp +++ b/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.cpp @@ -231,7 +231,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { // only once this backend is the one being brought up, so an Espryt-side bitmask cannot // kill a Magma run and vice versa. MagmaPipeValidateSubsystemConfiguration(); - CreateInstance(); + CreateInstance(m_window != NativeWindowType{}); if (!CreateSurface()) throw RuntimeError("DirectVulkan: the initial surface could not be created"); PickPhysicalDevice(); CreateLogicalDeviceAndQueues(); @@ -445,6 +445,22 @@ namespace MobileGL::MG_Backend::DirectVulkan { } void VulkanRenderer::Shutdown() { + if (m_deviceProbe) { + if (m_commandPool) vkDestroyCommandPool(m_device, m_commandPool, nullptr); + DestroyAllocator(); + if (m_device) vkDestroyDevice(m_device, nullptr); + if (m_surface) vkDestroySurfaceKHR(m_instance, m_surface, nullptr); +#if defined(VK_USE_PLATFORM_ANDROID_KHR) + if (m_fallbackImageReader) { + const auto deleteReader = + reinterpret_cast(dlsym(m_platformLibrary, "AImageReader_delete")); + deleteReader(m_fallbackImageReader); + dlclose(m_platformLibrary); + } +#endif + if (m_instance) vkDestroyInstance(m_instance, nullptr); + return; + } if (m_instance == VK_NULL_HANDLE && m_device == VK_NULL_HANDLE && m_surface == VK_NULL_HANDLE) { return; } diff --git a/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.h b/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.h index d09a6e9a..f183b430 100644 --- a/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.h +++ b/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRenderer.h @@ -160,6 +160,8 @@ namespace MobileGL::MG_Backend::DirectVulkan { VulkanRenderer(NativeWindowType window, const VulkanRendererConfig& cfg = {}); ~VulkanRenderer(); + static Bool ProbeDefaultBackend(); + void Initialize(); void Shutdown(); @@ -1693,7 +1695,8 @@ namespace MobileGL::MG_Backend::DirectVulkan { // must not allocate. Vector m_patchedAttributesScratch; - void CreateInstance(); + Bool m_deviceProbe = false; + void CreateInstance(Bool windowSurface); VkResult SetupDebugMessenger(); VkResult DestroyDebugMessenger(); VkResult SetupDebugReportCallback(); @@ -1756,7 +1759,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { const Vector& queueFamilies, Int preferredFamilyIndex = -1); static Vector GetQueueFamilyFromPhysicalDevice(VkPhysicalDevice device); - static Int GetQueueFamilyIndex(const Vector& queueFamilies, VkQueueFlagBits flag); + static Int GetQueueFamilyIndex(const Vector& queueFamilies, VkQueueFlags flags); static Vector EnumerateInstanceExtensions(); static Vector EnumerateDeviceExtensions(VkPhysicalDevice device); static Bool IsExtensionSupported(const Vector& availableExtensions, @@ -1773,7 +1776,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { static Bool IsNecessaryDeviceExtensionSupported(VkPhysicalDevice device); static Bool GetMoreCapablePhysicalDevice(VkPhysicalDevice newVkDevice, VkSurfaceKHR surface, const PhysicalDevice& compareWithDevice, - PhysicalDevice& outBetterDevice); + PhysicalDevice& outBetterDevice, Bool requireHardware); static constexpr const char* s_validationLayerNames[] = {"VK_LAYER_KHRONOS_validation"}; // VK_KHR_image_format_list: lets MUTABLE_FORMAT images declare their exact view-format // set so the driver can keep bandwidth compression (see CreateLogicalDeviceAndQueues). diff --git a/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRendererDevice.cpp b/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRendererDevice.cpp index a1a98d72..06c72c06 100644 --- a/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRendererDevice.cpp +++ b/MobileGL/MG_Backend/DirectVulkan/Renderer/VulkanRendererDevice.cpp @@ -70,7 +70,47 @@ namespace MobileGL::MG_Backend::DirectVulkan { } // namespace #endif - void VulkanRenderer::CreateInstance() { + namespace { + Bool IsHardwareDevice(VkPhysicalDevice device, const VkPhysicalDeviceProperties& properties) { + if (properties.apiVersion < VK_API_VERSION_1_1 || properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) { + return false; + } + if (properties.apiVersion >= VK_API_VERSION_1_2) { + VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; + VkPhysicalDeviceProperties2 extended{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; + vkGetPhysicalDeviceProperties2(device, &extended); + if (driver.driverID == VK_DRIVER_ID_GOOGLE_SWIFTSHADER || driver.driverID == VK_DRIVER_ID_MESA_LLVMPIPE) + return false; + } + return true; + } + } // namespace + + Bool VulkanRenderer::ProbeDefaultBackend() { + VulkanRenderer probe(NativeWindowType{}); + probe.m_deviceProbe = true; + probe.m_config.EnableValidationLayers = false; + try { + // The application has not chosen a surface yet. Verify the pbuffer route so + // the process-wide choice also works for applications that never open a window. + probe.CreateInstance(false); +#if !defined(VK_USE_PLATFORM_METAL_EXT) + if (!probe.CreateSurface()) return false; +#endif + probe.PickPhysicalDevice(); + probe.CreateLogicalDeviceAndQueues(); + probe.CreateAllocator(); + probe.CreateCommandPool(); + MGLOG_I("DirectVulkan: startup probe passed on %s", probe.m_physicalDevice.properties.deviceName); + return true; + } + catch (const RuntimeError& error) { + MGLOG_I("DirectVulkan: startup probe declined: %s", error.what()); + return false; + } + } + + void VulkanRenderer::CreateInstance(Bool windowSurface) { #if defined(VK_USE_PLATFORM_METAL_EXT) // MoltenVK snapshots its configuration when the loader first discovers the ICD. Set // this before instance-extension enumeration, while preserving an explicit user value. @@ -88,7 +128,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { MGLOG_I(" %s (r.%u)", extension.extensionName, extension.specVersion); } - Bool validationLayerAvailable = CheckValidationLayerSupport(); + Bool validationLayerAvailable = !m_deviceProbe && CheckValidationLayerSupport(); MGLOG_I("Validation layers %s.", validationLayerAvailable ? "available" : "not available"); MGLOG_I("Validation layers %s.", m_config.EnableValidationLayers ? "requested" : "not requested"); @@ -136,7 +176,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { // Extensions Vector exts = {VK_KHR_SURFACE_EXTENSION_NAME}; - if (!m_window) { + if (!windowSurface) { #ifdef VK_USE_PLATFORM_METAL_EXT exts.push_back(VK_EXT_METAL_SURFACE_EXTENSION_NAME); #elif defined VK_USE_PLATFORM_ANDROID_KHR @@ -166,6 +206,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { // reported as one below - never papered over with a window. m_headlessSurfaceSupported = IsExtensionSupported(m_extensions, VK_EXT_HEADLESS_SURFACE_EXTENSION_NAME); if (!m_headlessSurfaceSupported) { + if (m_deviceProbe) throw RuntimeError("VK_EXT_headless_surface is unavailable"); MGLOG_F("%s is not available from this Vulkan loader, so an offscreen (pbuffer) DirectVulkan " "surface cannot be created. Refusing to substitute a window: offscreen surfaces must not " "depend on a window system. Install an ICD that implements it (lavapipe does).", @@ -214,10 +255,8 @@ namespace MobileGL::MG_Backend::DirectVulkan { for (const char* ext : exts) { if (!IsExtensionSupported(m_extensions, ext)) { - MGLOG_E("Required Vulkan instance extension not found: %s", ext); + throw RuntimeError(format("Required Vulkan instance extension not found: {}", ext)); } - MOBILEGL_ASSERT(IsExtensionSupported(m_extensions, ext), "Required Vulkan instance extension not found: %s", - ext); } instanceInfo.enabledExtensionCount = exts.size(); @@ -238,7 +277,8 @@ namespace MobileGL::MG_Backend::DirectVulkan { instanceInfo.pNext = instanceCreatePNext; - VK_VERIFY(vkCreateInstance(&instanceInfo, nullptr, &m_instance), "vkCreateInstance failed"); + const VkResult result = vkCreateInstance(&instanceInfo, nullptr, &m_instance); + if (result != VK_SUCCESS) throw RuntimeError(format("vkCreateInstance failed ({})", static_cast(result))); if (debugUtilsAvailable) { VK_VERIFY(SetupDebugMessenger()); @@ -319,8 +359,11 @@ namespace MobileGL::MG_Backend::DirectVulkan { void VulkanRenderer::PickPhysicalDevice() { Uint32 deviceCount = 0; - VK_VERIFY(vkEnumeratePhysicalDevices(m_instance, &deviceCount, nullptr)); + if (vkEnumeratePhysicalDevices(m_instance, &deviceCount, nullptr) != VK_SUCCESS) { + throw RuntimeError("vkEnumeratePhysicalDevices failed"); + } if (deviceCount == 0) { + if (m_deviceProbe) throw RuntimeError("No Vulkan physical devices available"); // A real, reachable configuration, not a broken invariant: an instance can be // created from ICDs that load perfectly and then expose no device at all - a // GPU-less machine with the vendor ICDs installed (RADV/ANV/NVK on a CI runner) @@ -346,29 +389,26 @@ namespace MobileGL::MG_Backend::DirectVulkan { // actually written. const VkResult enumerateResult = vkEnumeratePhysicalDevices(m_instance, &deviceCount, devices.data()); if (enumerateResult != VK_SUCCESS && enumerateResult != VK_INCOMPLETE) { - VK_VERIFY(enumerateResult, "vkEnumeratePhysicalDevices failed"); + throw RuntimeError(format("vkEnumeratePhysicalDevices failed ({})", static_cast(enumerateResult))); } devices.resize(deviceCount); if (devices.empty()) { MGLOG_F("vkEnumeratePhysicalDevices reported devices and then wrote none"); throw RuntimeError("No Vulkan physical devices available for DirectVulkan"); } - for (Int i = 0; i < deviceCount; i++) { - if (GetMoreCapablePhysicalDevice(devices[i], m_surface, m_physicalDevice, m_physicalDevice)) + const Bool requireHardware = m_deviceProbe || MG_Config::AutoSelectBackend; + for (Uint32 i = 0; i < deviceCount; ++i) { + if (GetMoreCapablePhysicalDevice(devices[i], m_surface, m_physicalDevice, m_physicalDevice, + requireHardware)) MGLOG_I("Picked physical device %d.", i); } - if (m_physicalDevice.handle == VK_NULL_HANDLE) { - m_physicalDevice.handle = devices[0]; - vkGetPhysicalDeviceProperties(devices[0], &m_physicalDevice.properties); - MGLOG_I("No suitable physical device picked yet, defaulting to device 0."); - MGLOG_W("No graphics queue found on physical device. Picking a device that doesn't do graphics?"); - } + if (!m_physicalDevice.IsComplete()) throw RuntimeError("No suitable DirectVulkan physical device"); } Bool VulkanRenderer::GetMoreCapablePhysicalDevice(VkPhysicalDevice newVkDevice, VkSurfaceKHR surface, const PhysicalDevice& otherDevice, - PhysicalDevice& outBetterDevice) { + PhysicalDevice& outBetterDevice, Bool requireHardware) { const auto deviceTypeToStr = [](VkPhysicalDeviceType type) { switch (type) { case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: @@ -396,6 +436,8 @@ namespace MobileGL::MG_Backend::DirectVulkan { VK_VERSION_MINOR(apiVersion), VK_VERSION_PATCH(apiVersion), deviceTypeToStr(deviceProperties.deviceType)); + if (requireHardware && !IsHardwareDevice(newVkDevice, deviceProperties)) return false; + // Check device extensions (including swapchain extension) Bool deviceExtSupported = IsNecessaryDeviceExtensionSupported(newVkDevice); if (!deviceExtSupported) { @@ -406,16 +448,21 @@ namespace MobileGL::MG_Backend::DirectVulkan { } // Check swapchain capabilities - auto swapchainCapabilities = SwapchainObject::GetSwapchainCapabilities(newVkDevice, surface); - if (!swapchainCapabilities.IsComplete()) { - outBetterDevice = otherDevice; - MGLOG_I(" Ignored physical device. (Reason: Swapchain capabilities not met)"); - return false; + if (surface) { + const auto caps = SwapchainObject::GetSwapchainCapabilities(newVkDevice, surface); + constexpr auto requiredUsage = SwapchainObject::RequiredImageUsage; + if (!caps.IsComplete() || + (requireHardware && (caps.capabilities.supportedUsageFlags & requiredUsage) != requiredUsage)) { + MGLOG_I(" Ignored physical device. (Reason: Swapchain capabilities not met)"); + return false; + } } // Check queue families Vector queueFamilies = GetQueueFamilyFromPhysicalDevice(newVkDevice); - newDevice.queueFamilies.graphicsFamily = GetQueueFamilyIndex(queueFamilies, VK_QUEUE_GRAPHICS_BIT); + VkQueueFlags queueFlags = VK_QUEUE_GRAPHICS_BIT; + if (requireHardware) queueFlags |= VK_QUEUE_COMPUTE_BIT; + newDevice.queueFamilies.graphicsFamily = GetQueueFamilyIndex(queueFamilies, queueFlags); if (newDevice.queueFamilies.graphicsFamily == -1) { outBetterDevice = otherDevice; MGLOG_I(" Ignored physical device. (Reason: No graphics queue family)"); @@ -423,7 +470,9 @@ namespace MobileGL::MG_Backend::DirectVulkan { } newDevice.queueFamilies.presentFamily = - GetPresentQueueFamilyIndex(newDevice, surface, queueFamilies, newDevice.queueFamilies.graphicsFamily); + surface + ? GetPresentQueueFamilyIndex(newDevice, surface, queueFamilies, newDevice.queueFamilies.graphicsFamily) + : newDevice.queueFamilies.graphicsFamily; if (newDevice.queueFamilies.presentFamily == -1) { outBetterDevice = otherDevice; MGLOG_I(" Ignored physical device. (Reason: No present queue family)"); @@ -866,12 +915,10 @@ namespace MobileGL::MG_Backend::DirectVulkan { VkPhysicalDeviceIndexTypeUint8Features indexTypeUint8Features{}; indexTypeUint8Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES; - if (indexTypeUint8ExtensionName != nullptr) { + if (indexTypeUint8ExtensionName != nullptr && getPhysicalDeviceFeatures2 != nullptr) { VkPhysicalDeviceFeatures2 featureQuery{}; featureQuery.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; featureQuery.pNext = &indexTypeUint8Features; - MOBILEGL_ASSERT(getPhysicalDeviceFeatures2 != nullptr, - "CreateLogicalDeviceAndQueues: vkGetPhysicalDeviceFeatures2 is unavailable"); getPhysicalDeviceFeatures2(m_physicalDevice.handle, &featureQuery); if (indexTypeUint8Features.indexTypeUint8 == VK_TRUE) { if (!IsExtensionAlreadyEnabled(enabledDeviceExtensions, indexTypeUint8ExtensionName)) { @@ -1445,7 +1492,9 @@ namespace MobileGL::MG_Backend::DirectVulkan { deviceFeatures.drawIndirectFirstInstance ? "true" : "false", deviceFeatures.multiDrawIndirect ? "true" : "false", m_shaderDrawParametersFeatureEnabled ? "true" : "false"); - VK_VERIFY(vkCreateDevice(m_physicalDevice.handle, &deviceCreateInfo, nullptr, &m_device), "vkCreateDevice"); + const VkResult result = vkCreateDevice(m_physicalDevice.handle, &deviceCreateInfo, nullptr, &m_device); + if (result != VK_SUCCESS) throw RuntimeError(format("vkCreateDevice failed ({})", static_cast(result))); + if (m_deviceProbe) return; if (wireDepthResolveEnabled) { m_wireCreateRenderPass2 = reinterpret_cast( @@ -1978,7 +2027,9 @@ namespace MobileGL::MG_Backend::DirectVulkan { allocatorInfo.pVulkanFunctions = &vulkanFunctions; allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_0; - VK_VERIFY(vmaCreateAllocator(&allocatorInfo, &m_allocator), "vmaCreateAllocator"); + const VkResult result = vmaCreateAllocator(&allocatorInfo, &m_allocator); + if (result != VK_SUCCESS) + throw RuntimeError(format("vmaCreateAllocator failed ({})", static_cast(result))); } void VulkanRenderer::DestroyAllocator() { @@ -2015,7 +2066,9 @@ namespace MobileGL::MG_Backend::DirectVulkan { VkCommandPoolCreateInfo createInfo{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; createInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; createInfo.queueFamilyIndex = m_physicalDevice.queueFamilies.graphicsFamily; - VK_VERIFY(vkCreateCommandPool(m_device, &createInfo, nullptr, &m_commandPool)); + const VkResult result = vkCreateCommandPool(m_device, &createInfo, nullptr, &m_commandPool); + if (result != VK_SUCCESS) + throw RuntimeError(format("vkCreateCommandPool failed ({})", static_cast(result))); MGLOG_I("Command pool created"); } @@ -2109,6 +2162,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { auto* createHeadlessSurface = reinterpret_cast( vkGetInstanceProcAddr(m_instance, "vkCreateHeadlessSurfaceEXT")); if (!m_headlessSurfaceSupported || createHeadlessSurface == nullptr) { + if (m_deviceProbe) return false; MGLOG_F("vkCreateHeadlessSurfaceEXT is unavailable (%s reported as %s) while creating an " "offscreen DirectVulkan surface", VK_EXT_HEADLESS_SURFACE_EXTENSION_NAME, @@ -2116,9 +2170,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { throw RuntimeError("vkCreateHeadlessSurfaceEXT is unavailable for an offscreen DirectVulkan surface"); } VkHeadlessSurfaceCreateInfoEXT sci{VK_STRUCTURE_TYPE_HEADLESS_SURFACE_CREATE_INFO_EXT}; - VK_VERIFY(createHeadlessSurface(m_instance, &sci, nullptr, &m_surface), - "vkCreateHeadlessSurfaceEXT failed"); - return true; + return createHeadlessSurface(m_instance, &sci, nullptr, &m_surface) == VK_SUCCESS; #else auto* createHeadlessSurface = reinterpret_cast( vkGetInstanceProcAddr(m_instance, "vkCreateHeadlessSurfaceEXT")); @@ -2131,9 +2183,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { throw RuntimeError("vkCreateHeadlessSurfaceEXT is unavailable for an offscreen DirectVulkan surface"); } VkHeadlessSurfaceCreateInfoEXT sci{VK_STRUCTURE_TYPE_HEADLESS_SURFACE_CREATE_INFO_EXT}; - VK_VERIFY(createHeadlessSurface(m_instance, &sci, nullptr, &m_surface), - "vkCreateHeadlessSurfaceEXT failed"); - return true; + return createHeadlessSurface(m_instance, &sci, nullptr, &m_surface) == VK_SUCCESS; #endif } #if defined VK_USE_PLATFORM_ANDROID_KHR @@ -2232,10 +2282,9 @@ namespace MobileGL::MG_Backend::DirectVulkan { return queueFamilies; } - Int VulkanRenderer::GetQueueFamilyIndex(const Vector& queueFamilies, - VkQueueFlagBits flag) { + Int VulkanRenderer::GetQueueFamilyIndex(const Vector& queueFamilies, VkQueueFlags flags) { for (Uint32 i = 0; i < queueFamilies.size(); i++) { - if (queueFamilies[i].queueFlags & flag) { + if (queueFamilies[i].queueCount != 0 && (queueFamilies[i].queueFlags & flags) == flags) { return i; } } @@ -2275,7 +2324,9 @@ namespace MobileGL::MG_Backend::DirectVulkan { Vector extensions; for (Uint32 attempt = 0; attempt < 8; ++attempt) { Uint32 extensionCount = 0; - VK_VERIFY(vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr)); + if (vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr) != VK_SUCCESS) { + throw RuntimeError("vkEnumerateInstanceExtensionProperties failed"); + } extensions.resize(extensionCount); if (extensionCount == 0) { return extensions; @@ -2286,8 +2337,8 @@ namespace MobileGL::MG_Backend::DirectVulkan { return extensions; } if (result != VK_INCOMPLETE) { - VK_VERIFY(result, "vkEnumerateInstanceExtensionProperties failed"); - return extensions; + throw RuntimeError( + format("vkEnumerateInstanceExtensionProperties failed ({})", static_cast(result))); } MGLOG_I("vkEnumerateInstanceExtensionProperties returned VK_INCOMPLETE (the loader's list grew " "mid-enumeration); re-enumerating"); @@ -2299,9 +2350,15 @@ namespace MobileGL::MG_Backend::DirectVulkan { Vector VulkanRenderer::EnumerateDeviceExtensions(VkPhysicalDevice device) { Uint32 extensionCount = 0; - VK_VERIFY(vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr)); + if (vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr) != VK_SUCCESS) { + throw RuntimeError("vkEnumerateDeviceExtensionProperties failed"); + } Vector extensions(extensionCount); - VK_VERIFY(vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, extensions.data())); + if (extensionCount != 0 && + vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, extensions.data()) != VK_SUCCESS) { + throw RuntimeError("vkEnumerateDeviceExtensionProperties failed"); + } + extensions.resize(extensionCount); return extensions; } diff --git a/MobileGL/MG_IntegrationTest/Harness/HeadlessGL.cpp b/MobileGL/MG_IntegrationTest/Harness/HeadlessGL.cpp index ecc57eab..c22b3c90 100644 --- a/MobileGL/MG_IntegrationTest/Harness/HeadlessGL.cpp +++ b/MobileGL/MG_IntegrationTest/Harness/HeadlessGL.cpp @@ -8,6 +8,8 @@ #include "HeadlessGL.h" +#include + #include #include #include @@ -140,11 +142,6 @@ namespace MGITest { #endif } - std::string EnvOr(const char* name, const char* fallback) { - const char* value = std::getenv(name); - return (value != nullptr && value[0] != '\0') ? std::string(value) : std::string(fallback); - } - // A skip reason is only useful if it says which call failed AND why, so // every bring-up step reports the EGL error it left behind. std::string WithEglError(const char* what) { @@ -564,16 +561,12 @@ namespace MGITest { // before the pre-flight forks - the child must measure the same platform // the parent will use. EnsureHeadlessPlatform(); - // The backend that is actually about to come up, which is what every - // `BackendName() == "DirectGLES"` gate in the scenarios means by the question. - // MG_ConfigLoader::InitBackendType defaults an unset MOBILEGL_BACKEND_TYPE to - // DirectGLES, so the same default belongs here; this used to report the literal - // "" instead. Under ctest the variable is always set by the ENVIRONMENT - // property, which is why that never showed - but run straight from a device - // shell, where nothing sets it, DirectGLES came up and every case gated on the - // NAME DirectGLES skipped as though it had not. - m_backendName = EnvOr("MOBILEGL_BACKEND_TYPE", "DirectGLES"); m_usable = BringUp(); + if (m_usable) { + m_backendName = MobileGL::MG_Config::ActiveBackendType == MobileGL::BackendType::DirectVulkan + ? "DirectVulkan" + : "DirectGLES"; + } } bool HeadlessGL::BringUp() { diff --git a/MobileGL/MG_Remote/Server/ServerMain.cpp b/MobileGL/MG_Remote/Server/ServerMain.cpp index fb652030..1e5498f0 100644 --- a/MobileGL/MG_Remote/Server/ServerMain.cpp +++ b/MobileGL/MG_Remote/Server/ServerMain.cpp @@ -478,6 +478,7 @@ namespace { static std::once_flag s_serverConfigured; std::call_once(s_serverConfigured, [] { MobileGL::MG_ConfigLoader::Init(); + MobileGL::MG_Config::AutoSelectBackend = false; // The wire handshake supplies the backend. MobileGL::MG_Config::Transport = MobileGL::MG_Config::TransportMode::Spawn; MobileGL::MG_Pipe::MGPipeSetServerProcessRole(true); }); diff --git a/MobileGL/MG_Test/Util/ConfigFileTest.cpp b/MobileGL/MG_Test/Util/ConfigFileTest.cpp index 2cc286fb..c6c7605e 100644 --- a/MobileGL/MG_Test/Util/ConfigFileTest.cpp +++ b/MobileGL/MG_Test/Util/ConfigFileTest.cpp @@ -88,6 +88,7 @@ namespace { TEST_F(ConfigFileTest, WithoutFilesOrEnvironmentTheBuiltInDefaultsHold) { Loader::Init(); + EXPECT_TRUE(Config::AutoSelectBackend); EXPECT_EQ(Config::ActiveBackendType, BackendType::DirectGLES); EXPECT_EQ(Config::Features.FramesInFlight, 3u); EXPECT_EQ(Lookup("MOBILEGL_TRANSPORT"), ""); @@ -166,10 +167,12 @@ namespace { Loader::Init(); EXPECT_EQ(Config::ActiveBackendType, BackendType::DirectVulkan); EXPECT_EQ(Lookup("MOBILEGL_BACKEND_TYPE"), "DirectVulkan"); + EXPECT_FALSE(Config::AutoSelectBackend); ::setenv("MOBILEGL_BACKEND_TYPE", "DirectGLES", 1); Loader::Init(); EXPECT_EQ(Config::ActiveBackendType, BackendType::DirectGLES); + EXPECT_FALSE(Config::AutoSelectBackend); ::unsetenv("MOBILEGL_BACKEND_TYPE"); // Without the backend file, client.conf's line is the answer. diff --git a/README.md b/README.md index a37bb9bf..153905e9 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,7 @@ MobileGL supports runtime configuration via environment variables. | Variable | Description | Allowed Values | Default | |-------------------------|--------------------------------------------------|--------------------------------------|----------------| -| `MOBILEGL_BACKEND_TYPE` | Select active backend implementation at startup. | `DirectGLES`, `DirectVulkan` | `DirectGLES` | +| `MOBILEGL_BACKEND_TYPE` | Select the active backend at startup. | `DirectGLES`, `DirectVulkan` | Automatic | | `MOBILEGL_DISABLE_TIMERQUERY` | Disable GPU timer-query exposure and use. | `0`, `1` | `0` | | `MOBILEGL_ESPRYT_USE_ANGLE` | Load ANGLE EGL/GLES libraries. | `0`, `1` | `0` | | `MOBILEGL_SUBGROUP_EMULATION` | `GL_KHR_shader_subgroup` emulation (32-lane, compute stage). `Auto` emulates only where the driver has no subgroup operations; `ForceOn` emulates even over native support; `ForceOff` never emulates (native support is still used). | `Auto`, `ForceOn`, `ForceOff` | `Auto` | diff --git a/userguide/configuration.md b/userguide/configuration.md index 13afe87e..15f3cfd5 100644 --- a/userguide/configuration.md +++ b/userguide/configuration.md @@ -45,9 +45,13 @@ environment too. The backend itself is the exception: the client asks for it (se ## Backend and general +The automatic probe checks the local Vulkan driver and verifies the pbuffer route where available +before the application supplies a window. On Linux, this requires `VK_EXT_headless_surface`. If the +renderer runs on another device, set `MOBILEGL_BACKEND_TYPE` for that server’s hardware. + | Variable | Values | Default | Meaning | |---|---|---|---| -| `MOBILEGL_BACKEND_TYPE` | `DirectGLES`, `DirectVulkan` | `DirectGLES` | Espryt (GLES) or Magma (Vulkan). Case-sensitive. Any other value leaves MobileGL without a backend. In a split session the client's value is sent to the server, which uses it unless the server pinned a different one. | +| `MOBILEGL_BACKEND_TYPE` | `DirectGLES`, `DirectVulkan` | Automatic | Prefer DirectVulkan when a hardware device passes the Vulkan startup probe. Otherwise use DirectGLES. Explicit values are case-sensitive. Any other value leaves MobileGL without a backend. In a split session the client sends the selected backend to the server, which uses it unless the server pinned a different one. | | `MOBILEGL_FRAMES_IN_FLIGHT` | 1-64 | 3 | How many frames may be queued ahead of the GPU. Magma: its frame contexts. Espryt: after presenting frame N it waits for frame N+1-value to finish (1 = full CPU/GPU sync). Split topologies: the client may run `max(1, value - 2)` presents ahead of the server, so 4 gives one more frame of overlap (and of latency). The old name `MOBILEGL_MAGMA_FRAMESINFLIGHT` still works but is deprecated. | | `MOBILEGL_RELAXED_SEMANTICS` | flag | off | Apply legacy leniencies (for example drawing with vertex array object 0, reusing texture names after delete) even to contexts that explicitly requested a core profile. Contexts that did not request core get them anyway. | | `MOBILEGL_ADVERTISE_FP64` | flag | off | Advertise `GL_ARB_gpu_shader_fp64`. `double` types compile either way but run at 32-bit precision. |