Program Listing for File AdapterChoices.hpp

Program Listing for File AdapterChoices.hpp#

↰ Return to documentation for file (Src/GraphicsEngineVulkan/vulkan_base/AdapterChoices.hpp)

#pragma once

#include <algorithm>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
#include <vulkan/vulkan.hpp>

#include "vulkan_base/PhysicalDeviceChoices.hpp"

// OxidANT's adapter.rs in Vulkan terms, pure for tests without a GPU; BuildIntegrity.AdapterChoicesFollowRustsAdapterRs.
namespace Kataglyphis {

// The CLI flag and variable that name an adapter by a case-insensitive part of its entry label.
inline constexpr std::string_view kAdapterFlag = "--adapter";
inline constexpr std::string_view kAdapterEnv = "KATAGLYPHIS_ADAPTER";

enum class AdapterClass : std::uint8_t { Discrete, Integrated, Virtual, Cpu, Unknown };

constexpr auto adapterClassOf(vk::PhysicalDeviceType type) -> AdapterClass
{
    switch (type) {
    case vk::PhysicalDeviceType::eDiscreteGpu:
        return AdapterClass::Discrete;
    case vk::PhysicalDeviceType::eIntegratedGpu:
        return AdapterClass::Integrated;
    case vk::PhysicalDeviceType::eVirtualGpu:
        return AdapterClass::Virtual;
    case vk::PhysicalDeviceType::eCpu:
        return AdapterClass::Cpu;
    case vk::PhysicalDeviceType::eOther:
    default:
        return AdapterClass::Unknown;
    }
}

constexpr auto adapterClassName(AdapterClass type) -> const char *
{
    switch (type) {
    case AdapterClass::Discrete:
        return "Discrete GPU";
    case AdapterClass::Integrated:
        return "Integrated GPU";
    case AdapterClass::Virtual:
        return "Virtual GPU";
    case AdapterClass::Cpu:
        return "CPU";
    case AdapterClass::Unknown:
    default:
        return "Other";
    }
}

// The PCI vendor ids a renderer meets; nullptr for another.
constexpr auto adapterVendorName(std::uint32_t id) -> const char *
{
    switch (id) {
    case 0x8086:
        return "Intel";
    case 0x10de:
        return "NVIDIA";
    case 0x1002:
    case 0x1022:
        return "AMD";
    case 0x13b5:
        return "Arm";
    case 0x5143:
        return "Qualcomm";
    case 0x106b:
        return "Apple";
    case 0x1414:
        return "Microsoft";
    case 0x1010:
        return "Imagination";
    case 0x144d:
        return "Samsung";
    default:
        return nullptr;
    }
}

namespace adapter_detail {
    inline auto trimmed(std::string_view text) -> std::string_view
    {
        const auto blank = [](char character) { return std::isspace(static_cast<unsigned char>(character)) != 0; };
        while (!text.empty() && blank(text.front())) { text.remove_prefix(1); }
        while (!text.empty() && blank(text.back())) { text.remove_suffix(1); }
        return text;
    }

    inline auto lowered(std::string_view text) -> std::string
    {
        std::string out(text);
        std::ranges::transform(
          out, out.begin(), [](unsigned char character) { return static_cast<char>(std::tolower(character)); });
        return out;
    }

    // Rust's `{:#06x}`: 0x and at least four digits.
    inline auto pciHex(std::uint32_t value) -> std::string
    {
        constexpr std::string_view kDigits = "0123456789abcdef";
        std::string digits;
        for (std::uint32_t rest = value; rest != 0U || digits.size() < 4U; rest >>= 4U) {
            digits.insert(digits.begin(), kDigits[rest & 0xFU]);
        }
        return "0x" + digits;
    }
}// namespace adapter_detail

// The device's name; without one its PCI vendor and device id, then the driver, as Rust's label() writes them.
inline auto adapterLabel(std::string_view name, std::uint32_t vendor, std::uint32_t device, std::string_view driver)
  -> std::string
{
    if (const std::string_view given = adapter_detail::trimmed(name); !given.empty()) { return std::string(given); }
    std::vector<std::string> parts;
    if (const char *known = adapterVendorName(vendor); known != nullptr) {
        parts.emplace_back(known);
    } else if (vendor != 0U) {
        parts.push_back("vendor " + adapter_detail::pciHex(vendor));
    }
    if (device != 0U) { parts.push_back(adapter_detail::pciHex(device)); }
    if (const std::string_view named = adapter_detail::trimmed(driver); !named.empty()) {
        parts.push_back("(" + std::string(named) + ")");
    }
    std::string label;
    for (const std::string &part : parts) { label += (label.empty() ? "" : " ") + part; }
    return label.empty() ? std::string("unknown adapter") : label;
}

// One row of the adapter list, and what --adapter matches: `NVIDIA RTX 2000 Ada (Vulkan)`.
inline auto adapterEntryLabel(std::string_view label) -> std::string { return std::string(label) + " (Vulkan)"; }

// The command line's --adapter over KATAGLYPHIS_ADAPTER; a blank one names nothing.
inline auto adapterRequestName(std::optional<std::string> commandLine, std::optional<std::string> environment)
  -> std::optional<std::string>
{
    if (commandLine.has_value() && !adapter_detail::trimmed(*commandLine).empty()) { return commandLine; }
    if (environment.has_value() && !adapter_detail::trimmed(*environment).empty()) { return environment; }
    return std::nullopt;
}

// A case-insensitive part of the entry label.
inline auto adapterNameMatches(std::string_view entryLabel, std::string_view name) -> bool
{
    return adapter_detail::lowered(entryLabel).find(adapter_detail::lowered(adapter_detail::trimmed(name)))
           != std::string::npos;
}

// What the renderer requires of a device, as VulkanDevice::unusable_reason reads it.
struct AdapterFacts
{
    std::uint32_t apiVersion = 0;
    vk::Bool32 dynamicRendering = VK_FALSE;
    vk::Bool32 synchronization2 = VK_FALSE;
    vk::Bool32 imageCubeArray = VK_FALSE;
    bool swapchainExtension = false;
    bool graphicsQueue = false;
    bool computeQueue = false;
    bool presentQueue = false;
    bool surfaceFormatsAndModes = false;
};

// Empty for a device the renderer can use, else everything it lacks: "no dynamicRendering, no synchronization2".
inline auto adapterUnusableReason(const AdapterFacts &facts) -> std::string
{
    std::vector<const char *> missing;
    if (VK_API_VERSION_MAJOR(facts.apiVersion) < 1
        || (VK_API_VERSION_MAJOR(facts.apiVersion) == 1 && VK_API_VERSION_MINOR(facts.apiVersion) < 3)) {
        missing.push_back("Vulkan 1.3");
    }
    if (facts.dynamicRendering != VK_TRUE) { missing.push_back("dynamicRendering"); }
    if (facts.synchronization2 != VK_TRUE) { missing.push_back("synchronization2"); }
    if (facts.imageCubeArray != VK_TRUE) { missing.push_back("imageCubeArray"); }
    if (!facts.swapchainExtension) { missing.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); }
    if (!facts.graphicsQueue) { missing.push_back("graphics queue"); }
    if (!facts.computeQueue) { missing.push_back("compute queue"); }
    if (!facts.presentQueue) { missing.push_back("presentation to the window"); }
    // Without the swapchain extension the surface was not queried, so its formats say nothing more.
    if (facts.swapchainExtension && !facts.surfaceFormatsAndModes) {
        missing.push_back("surface format or present mode");
    }
    std::string reason;
    for (const char *what : missing) { reason += std::string(reason.empty() ? "no " : ", no ") + what; }
    return reason;
}

// One physical device as the list shows it and the choice reads it.
struct AdapterEntry
{
    std::string label;
    std::string entryLabel;
    AdapterClass type = AdapterClass::Unknown;
    PhysicalDeviceScore score{};
    // Empty when the renderer can use the device.
    std::string unusableReason;

    [[nodiscard]] bool usable() const { return unusableReason.empty(); }
};

struct AdapterChoice
{
    std::size_t index = 0;
    // A name was asked for and no usable adapter matched it.
    bool unmatchedRequest = false;
    // --gpu asked for a type and no usable adapter is one.
    bool unmatchedMode = false;
    friend bool operator==(const AdapterChoice &, const AdapterChoice &) = default;
};

constexpr auto adapterMatchesMode(AdapterClass type, GpuSelectionMode mode) -> bool
{
    switch (mode) {
    case GpuSelectionMode::Dedicated:
        return type == AdapterClass::Discrete;
    case GpuSelectionMode::Integrated:
        return type == AdapterClass::Integrated;
    case GpuSelectionMode::Auto:
    default:
        return true;
    }
}

// Name first, then --gpu's type, then any usable device; a tie goes to the first listed (scorePhysicalDevice ranks).
inline auto chooseAdapter(std::span<const AdapterEntry> adapters,
  const std::optional<std::string> &name,
  GpuSelectionMode mode) -> std::optional<AdapterChoice>
{
    const auto best = [&](const auto &matches) -> std::optional<std::size_t> {
        std::optional<std::size_t> found;
        for (std::size_t index = 0; index < adapters.size(); ++index) {
            const AdapterEntry &entry = adapters[index];
            if (!entry.usable() || !matches(entry)) { continue; }
            if (!found.has_value() || entry.score > adapters[*found].score) { found = index; }
        }
        return found;
    };
    if (name.has_value()) {
        if (const auto named =
              best([&](const AdapterEntry &entry) { return adapterNameMatches(entry.entryLabel, *name); });
          named.has_value()) {
            return AdapterChoice{ .index = *named };
        }
    }
    if (const auto typed = best([&](const AdapterEntry &entry) { return adapterMatchesMode(entry.type, mode); });
      typed.has_value()) {
        return AdapterChoice{ .index = *typed, .unmatchedRequest = name.has_value() };
    }
    const auto any = best([](const AdapterEntry &) { return true; });
    if (!any.has_value()) { return std::nullopt; }
    return AdapterChoice{ .index = *any, .unmatchedRequest = name.has_value(), .unmatchedMode = true };
}

// The status bar's word beside the adapter and the tooltip that explains it.
struct AdapterHint
{
    const char *text;
    const char *tooltip;
};

// Rust's NATIVE_INTEGRATED; a function, since Sphinx's C++ parser rejects this initializer in the API docs.
constexpr auto nativeIntegratedHint() -> AdapterHint
{
    return { .text = "Integrated GPU",
        .tooltip =
          "A discrete GPU is available: Renderer > Adapter > Use restarts the viewer on it, as does --adapter "
          "<name> or KATAGLYPHIS_ADAPTER=<name>." };
}

// Rust's native hint: on an integrated adapter while a usable discrete one is listed.
inline auto adapterHint(std::span<const AdapterEntry> adapters, std::size_t inUse) -> std::optional<AdapterHint>
{
    if (inUse >= adapters.size() || adapters[inUse].type != AdapterClass::Integrated) { return std::nullopt; }
    const bool discrete = std::ranges::any_of(
      adapters, [](const AdapterEntry &entry) { return entry.usable() && entry.type == AdapterClass::Discrete; });
    return discrete ? std::optional<AdapterHint>(nativeIntegratedHint()) : std::nullopt;
}

struct SplitAdapterArgument
{
    std::optional<std::string> adapter;
    std::vector<std::string> rest;
    // Where absl's `--` sits in `rest`, if anywhere: what follows it is positional, an `--adapter` too.
    std::optional<std::size_t> terminator;
};

// The command line without its --adapter (spaced or with `=`), and that adapter; the last one wins.
inline auto splitAdapterArgument(std::span<const std::string> args) -> SplitAdapterArgument
{
    constexpr std::string_view kWithValue = "--adapter=";
    SplitAdapterArgument split;
    for (std::size_t index = 0; index < args.size(); ++index) {
        const std::string &arg = args[index];
        if (arg == "--") {
            split.terminator = split.rest.size();
            split.rest.insert(split.rest.end(), args.begin() + static_cast<std::ptrdiff_t>(index), args.end());
            break;
        }
        if (arg == kAdapterFlag) {
            split.adapter = index + 1 < args.size() ? std::optional<std::string>(args[++index]) : std::nullopt;
        } else if (arg.starts_with(kWithValue)) {
            split.adapter = arg.substr(kWithValue.size());
        } else {
            split.rest.push_back(arg);
        }
    }
    if (split.adapter.has_value() && adapter_detail::trimmed(*split.adapter).empty()) { split.adapter.reset(); }
    return split;
}

// A restart's arguments with --adapter replaced, put before a `--` (unlike Rust) lest it read as two positionals.
inline auto relaunchArguments(std::span<const std::string> args, std::string_view entry) -> std::vector<std::string>
{
    SplitAdapterArgument split = splitAdapterArgument(args);
    const auto at = split.rest.begin() + static_cast<std::ptrdiff_t>(split.terminator.value_or(split.rest.size()));
    split.rest.insert(at, { std::string(kAdapterFlag), std::string(entry) });
    return split.rest;
}

// CreateProcessW's command line, which CommandLineToArgvW and the CRT split back into exactly `args`.
inline auto windowsCommandLine(std::span<const std::string> args) -> std::string
{
    std::string line;
    for (const std::string &arg : args) {
        if (!line.empty()) { line += ' '; }
        if (!arg.empty() && arg.find_first_of(" \t\n\v\"") == std::string::npos) {
            line += arg;
            continue;
        }
        line += '"';
        std::size_t backslashes = 0;
        for (const char character : arg) {
            if (character == '\\') {
                ++backslashes;
                continue;
            }
            // Backslashes double only before a quote, which then gets one of its own.
            line.append(character == '"' ? backslashes * 2 + 1 : backslashes, '\\');
            line += character;
            backslashes = 0;
        }
        line.append(backslashes * 2, '\\');
        line += '"';
    }
    return line;
}

}// namespace Kataglyphis