TExcelTAD
Home › Shaders & Graphics Programming › Vulkan 1: Instance, Devices, Swapchain

Vulkan 1: Instance, Devices, Swapchain

Vulkan is famous for needing about a thousand lines to draw a triangle. Most of those lines are not hard; they just make explicit every decision OpenGL made silently. This lesson walks through the objects you create once at startup, in order. The next lesson covers what happens every frame.

None of this code runs in the browser, so the Vulkan snippets are plain C++ fences, shortened to the essential fields. Where a decision is pure logic (choosing a GPU, a queue family, a present mode), there is a runnable C++ model of it.

Learn it properly: follow vulkan-tutorial.com from start to finish once. It is the standard path, available in several languages. Then, in your own projects, use vk-bootstrap for this startup code and VMA (Vulkan Memory Allocator) for memory, as most real codebases do. Keep the official Vulkan documentation and the validation layers on at all times.

The startup chain

text
VkInstance ── VkDebugUtilsMessengerEXT (validation messages)
   │
   ├── VkSurfaceKHR (from the window: GLFW, SDL3, Win32…)
   │
   └── VkPhysicalDevice  (a GPU you can query, not use)
          │
          └── VkDevice  (the logical device: your connection to that GPU)
                 ├── VkQueue  (graphics, present, compute, transfer)
                 └── VkSwapchainKHR ── VkImage[] ── VkImageView[]

Every object you create, you destroy, in reverse order. The validation layers report anything you forget.

1. Instance and validation layers

The instance connects your app to the Vulkan loader. You declare the API version you target and the instance extensions you need: the window system's surface extensions (GLFW lists them with glfwGetRequiredInstanceExtensions) and VK_EXT_debug_utils for debug messages.

cpp
VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO};
app.pApplicationName = "Course";
app.apiVersion = VK_API_VERSION_1_3;

const char* layers[] = {"VK_LAYER_KHRONOS_validation"};   // development builds only

uint32_t glfwCount = 0;
const char** glfwExts = glfwGetRequiredInstanceExtensions(&glfwCount);
std::vector<const char*> exts(glfwExts, glfwExts + glfwCount);
exts.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);

VkInstanceCreateInfo ci{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};
ci.pApplicationInfo = &app;
ci.enabledLayerCount = 1;
ci.ppEnabledLayerNames = layers;
ci.enabledExtensionCount = uint32_t(exts.size());
ci.ppEnabledExtensionNames = exts.data();

VkInstance instance;
if (vkCreateInstance(&ci, nullptr, &instance) != VK_SUCCESS) { /* no driver, or a missing layer/extension */ }

Two patterns you will see in every Vulkan call: each struct starts with an sType (so the driver knows what it is) and a pNext pointer (to chain extension structs), and functions return a VkResult you must check.

The validation layers (VK_LAYER_KHRONOS_validation, part of the Vulkan SDK) check every call against the specification and print errors such as "image is in layout UNDEFINED but expected COLOR_ATTACHMENT_OPTIMAL". Vulkan drivers themselves do almost no checking, so without the layers a mistake is a crash, a black screen, or "works on my GPU". Turn them on in development; ship without them.

2. Surface

A VkSurfaceKHR is the window as Vulkan sees it. The windowing library creates it:

cpp
VkSurfaceKHR surface;
glfwCreateWindowSurface(instance, window, nullptr, &surface);     // GLFW
// SDL3: SDL_Vulkan_CreateSurface(window, instance, nullptr, &surface);

3. Picking a physical device and queue families

vkEnumeratePhysicalDevices lists the GPUs. For each, you query its properties (name, type, limits), features (what it can do) and queue families: groups of queues with the same capabilities. You need a family that supports graphics and one that can present to your surface (usually the same one).

cpp
uint32_t count = 0;
vkEnumeratePhysicalDevices(instance, &count, nullptr);           // the "call twice" pattern:
std::vector<VkPhysicalDevice> gpus(count);                      // first the count, then the data
vkEnumeratePhysicalDevices(instance, &count, gpus.data());

for (VkPhysicalDevice gpu : gpus) {
    VkPhysicalDeviceProperties props;
    vkGetPhysicalDeviceProperties(gpu, &props);                 // props.deviceType, props.apiVersion, limits

    uint32_t qCount = 0;
    vkGetPhysicalDeviceQueueFamilyProperties(gpu, &qCount, nullptr);
    std::vector<VkQueueFamilyProperties> families(qCount);
    vkGetPhysicalDeviceQueueFamilyProperties(gpu, &qCount, families.data());
    for (uint32_t i = 0; i < qCount; i++) {
        VkBool32 canPresent = VK_FALSE;
        vkGetPhysicalDeviceSurfaceSupportKHR(gpu, i, surface, &canPresent);
        bool graphics = families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT;
        // remember a family with graphics && canPresent
    }
}

The choice itself is plain logic: reject GPUs that lack what you need, then prefer a discrete GPU. Here it is as a runnable model, with three made-up machines' worth of GPUs:

cpp · try it yourself
#include <cstdio>
#include <string>
#include <vector>

enum Type { Integrated, Discrete, Cpu };
struct Family { bool graphics, compute, transfer, present; int queues; };
struct Gpu { std::string name; Type type; int apiMinor; bool dynamicRendering; std::vector<Family> families; };

int findGraphicsPresent(const Gpu& g) {
    for (int i = 0; i < (int)g.families.size(); i++)
        if (g.families[i].graphics && g.families[i].present) return i;
    return -1;
}

int score(const Gpu& g, std::string& why) {
    if (g.apiMinor < 3) { why = "needs Vulkan 1.3"; return -1; }
    if (!g.dynamicRendering) { why = "no dynamicRendering"; return -1; }
    if (findGraphicsPresent(g) < 0) { why = "no graphics+present queue"; return -1; }
    int s = g.type == Discrete ? 1000 : g.type == Integrated ? 100 : 1;
    why = "ok";
    return s;
}

int main() {
    std::vector<Gpu> gpus = {
        {"llvmpipe (software)", Cpu, 3, true, {{true, true, true, true, 1}}},
        {"Laptop iGPU", Integrated, 3, true, {{true, true, true, true, 1}}},
        {"Old dGPU", Discrete, 2, false, {{true, true, true, true, 16}}},
        {"Desktop dGPU", Discrete, 3, true, {{true, true, true, false, 16}, {true, true, true, true, 2}, {false, false, true, false, 2}}},
    };
    int best = -1, bestScore = -1;
    for (int i = 0; i < (int)gpus.size(); i++) {
        std::string why;
        int s = score(gpus[i], why);
        std::printf("%-20s score %5d  (%s)\n", gpus[i].name.c_str(), s, why.c_str());
        if (s > bestScore) { bestScore = s; best = i; }
    }
    std::printf("picked: %s, graphics+present family %d\n", gpus[best].name.c_str(), findGraphicsPresent(gpus[best]));
}
llvmpipe (software)  score     1  (ok)
Laptop iGPU          score   100  (ok)
Old dGPU             score    -1  (needs Vulkan 1.3)
Desktop dGPU         score  1000  (ok)
picked: Desktop dGPU, graphics+present family 1

Note the desktop GPU: its family 0 can do graphics but cannot present to this surface, so the search must check both flags. On real hardware a single family usually does both, but code that assumes "family 0" eventually breaks.

4. Logical device and queues

The logical device is created from the physical device with the queues, device extensions (VK_KHR_swapchain at minimum) and features you will use. Features you do not enable are not available, even if the GPU supports them. Vulkan 1.3 core features such as dynamic rendering and synchronization2 are enabled through the VkPhysicalDeviceVulkan13Features struct, chained with pNext:

cpp
float priority = 1.0f;
VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
qci.queueFamilyIndex = graphicsFamily;
qci.queueCount = 1;
qci.pQueuePriorities = &priority;

VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
f13.dynamicRendering = VK_TRUE;
f13.synchronization2 = VK_TRUE;

const char* devExts[] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
dci.pNext = &f13;
dci.queueCreateInfoCount = 1;
dci.pQueueCreateInfos = &qci;
dci.enabledExtensionCount = 1;
dci.ppEnabledExtensionNames = devExts;

VkDevice device;
vkCreateDevice(gpu, &dci, nullptr, &device);
VkQueue graphicsQueue;
vkGetDeviceQueue(device, graphicsFamily, 0, &graphicsQueue);

Queues are where you submit work. Big GPUs expose separate families for async compute and DMA transfers, which engines use to overlap work; a beginner renderer needs just one graphics queue.

5. Swapchain

The swapchain is a ring of images owned by the presentation engine. You render into one while another is on screen. Creating it means choosing:

  • Surface format: usually VK_FORMAT_B8G8R8A8_SRGB with VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, so writes from linear shader colors are gamma-encoded by the hardware (see Field Notes).
  • Present mode: VK_PRESENT_MODE_FIFO_KHR (vsync, the only mode guaranteed to exist), MAILBOX_KHR (low latency, no tearing, replaces queued frames), IMMEDIATE_KHR (may tear).
  • Extent (the window size in pixels, which can differ from the size in screen coordinates on high-DPI displays) and image count (usually minImageCount + 1, clamped to maxImageCount, where 0 means "no maximum").
cpp
VkSwapchainCreateInfoKHR sci{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR};
sci.surface = surface;
sci.minImageCount = imageCount;
sci.imageFormat = VK_FORMAT_B8G8R8A8_SRGB;
sci.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
sci.imageExtent = extent;
sci.imageArrayLayers = 1;
sci.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
sci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;          // graphics and present on the same family
sci.preTransform = caps.currentTransform;
sci.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
sci.presentMode = VK_PRESENT_MODE_FIFO_KHR;
sci.clipped = VK_TRUE;
vkCreateSwapchainKHR(device, &sci, nullptr, &swapchain);
// then vkGetSwapchainImagesKHR + one VkImageView per image

When the window is resized, presentation returns VK_ERROR_OUT_OF_DATE_KHR (or VK_SUBOPTIMAL_KHR); you wait for the device to go idle and recreate the swapchain and its views.

The same startup with vk-bootstrap

vk-bootstrap replaces steps 1–5 with builders that do the checks and the "call twice" queries for you. Each build()/select() returns a result you must check:

cpp
#include "VkBootstrap.h"

auto instRet = vkb::InstanceBuilder{}
    .set_app_name("Course")
    .request_validation_layers()
    .use_default_debug_messenger()
    .require_api_version(1, 3, 0)
    .build();
if (!instRet) { std::printf("%s\n", instRet.error().message().c_str()); return; }
vkb::Instance vkbInstance = instRet.value();

glfwCreateWindowSurface(vkbInstance.instance, window, nullptr, &surface);

VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES};
f13.dynamicRendering = VK_TRUE;
f13.synchronization2 = VK_TRUE;

vkb::PhysicalDevice gpu = vkb::PhysicalDeviceSelector{vkbInstance}
    .set_minimum_version(1, 3)
    .set_required_features_13(f13)
    .set_surface(surface)
    .select().value();

vkb::Device vkbDevice = vkb::DeviceBuilder{gpu}.build().value();
VkQueue graphicsQueue = vkbDevice.get_queue(vkb::QueueType::graphics).value();
uint32_t graphicsFamily = vkbDevice.get_queue_index(vkb::QueueType::graphics).value();

vkb::Swapchain vkbSwapchain = vkb::SwapchainBuilder{vkbDevice}
    .set_desired_format({VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR})
    .set_desired_present_mode(VK_PRESENT_MODE_FIFO_KHR)
    .set_desired_extent(width, height)
    .build().value();
std::vector<VkImage> images = vkbSwapchain.get_images().value();
std::vector<VkImageView> views = vkbSwapchain.get_image_views().value();

Writing the raw version once (with the tutorial) teaches you what these builders decide; using the library afterwards saves hundreds of lines you would otherwise maintain.

Test yourself

What is the difference between a VkPhysicalDevice and a VkDevice?

  1. None, they are aliases
  2. The physical device describes a GPU you can query; the logical device is the connection you create to use it, with chosen queues, extensions and features
  3. The VkDevice is the CPU
  4. The physical device is only for compute

Which present mode is guaranteed to be supported?

  1. VK_PRESENT_MODE_MAILBOX_KHR
  2. VK_PRESENT_MODE_IMMEDIATE_KHR
  3. VK_PRESENT_MODE_FIFO_KHR
  4. VK_PRESENT_MODE_FIFO_RELAXED_KHR

Why keep the validation layers enabled during development?

  1. They make rendering faster
  2. Vulkan drivers do almost no error checking, so the layers are what report misuse
  3. They are required to create a swapchain
  4. They enable dynamic rendering