Skip to content
ImagineWorld

Establishing a Build Environment

node_idnode-book_vulkan-3d-graphics-rendering-cookbook_chapter-01-establishing-a-build-environment
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num1
chapter_titleEstablishing a Build Environment
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 1 — Establishing a Build Environment

Section titled “Chapter 1 — Establishing a Build Environment”

In this chapter, you will learn how to set up a 3D graphics development environment on your computer for Windows and Linux operating systems. You will learn which software tools are needed to run the demos from this book’s source code bundle: https://github.com/PacktPublishing/3D-Graphics-Rendering-Cookbook-Second-Edition.

We will cover the following topics:

  • Setting up our development environment on Microsoft Windows
  • Setting up our development environment on Linux
  • Installing the Vulkan SDK for Microsoft Windows and Linux
  • Managing dependencies
  • Getting the demo data
  • Creating utilities for CMake projects
  • Using the GLFW library
  • Multithreading with Taskflow
  • Compiling Vulkan shaders at runtime
  • Compressing textures into the BC7 format

Setting up our development environment on Microsoft Windows

Section titled “Setting up our development environment on Microsoft Windows”

In this recipe, we will get started by setting up our development environment on Windows. We will go through the installation of each of the required tools individually and in detail.

In order to start working with the examples from this book in a Microsoft Windows environment, you will need some essential tools to be installed in your system.

The most important one is Microsoft Visual Studio 2022. Additional tools include the Git version control system, the CMake build tool, and the Python programming language. Throughout this book, we use these tools on the command line only, so no GUI add-ons will be required.

Let’s install each of the required tools individually.

Follow the given steps to install Microsoft Visual Studio 2022:

  1. Open https://visualstudio.microsoft.com and download the Visual Studio 2022 Community Edition installer.
  2. Start the installer and follow the on-screen instructions. For the purposes of this book, you need to have a native C++ compiler for the 64-bit Intel platform. Other components of the Visual Studio development environment are not required to run this book’s bundled sample code.

Follow the given steps to install Git:

  1. Download the latest Git installer from https://git-scm.com/downloads, run it, and follow the on-screen instructions. We assume that Git is added to the system PATH variable. Enable the option shown in the following image during installation:

Figure 1.4: Git from the command line and also from third-party software

  1. Select Use Windows’ default console window, as shown in the next screenshot. This option will allow you to build the scripts in this book from any directory on your computer:

A screenshot of a computer Description automatically generated

Figure 1.5: Use Windows’ default console window

Read more

Git is complex software and a huge topic in itself. We recommend the book Mastering Git, 2nd edition written by Jakub Narębski and published by Packt Publishing, along with Git Essentials: Developer’s Guide to Git by François Dupire and the downloadable ebook ProGit, Second Edition, by Scott Chacon and Ben Straub, https://git-scm.com/book/en/v2.

To install CMake, please follow the given steps:

  1. Download the latest 64-bit CMake installer from https://cmake.org/download/.
  2. Run it and follow the on-screen instructions. If you already have an earlier version of CMake installed, it is recommended to uninstall it first.
  3. Select the Add CMake to the system PATH for all users option, as shown here:

A screenshot of a computer program Description automatically generated

Figure 1.6: Add CMake to the system PATH for all users

To install Python, please follow the given steps:

  1. Download the latest Python 3 installer for 64-bit systems from https://www.python.org/downloads/.
  2. Run it and follow the on-screen instructions.
  3. During the installation, you also need to install the pip feature. Choose Custom Installation and make sure that the pip checkbox is checked, as shown:

A screenshot of a computer Description automatically generated

Figure 1.7: Custom installation

  1. Once the installation has completed, make sure to add the folder containing python.exe to the PATH environment variable.

Besides Git, there are other popular version control systems, like SVN and Mercurial. While developing large software systems, you will inevitably face the need to download some libraries from a non-Git repository. We recommend getting familiar with Mercurial.

While working in the command-line environment, it is useful to have some tools from the Unix environment, like wget, grep, find, etc. The GnuWin32 project provides precompiled binaries of these tools, which can be downloaded from http://gnuwin32.sourceforge.net.

Furthermore, in the Windows environment, orthodox file managers make file manipulation a lot easier. We definitely recommend giving the open-source Far Manager a try. You can download it from https://farmanager.com. It looks like this:

Figure 1.8: The look and feel of Far Manager

Setting up our development environment on Linux

Section titled “Setting up our development environment on Linux”

Linux is becoming more and more attractive for 3D graphics development, including gaming technology. Let’s go through a list of tools necessary to start working with this book on Linux.

We assume you have a desktop computer with a Debian-based GNU/Linux operating system installed. We also assume you are familiar with the apt package manager.

To start developing modern graphics programs on Linux, you need to have up-to-date video card drivers installed that support Vulkan 1.3. To build examples from this book, a C++ compiler with C++20 support is required. We tested our code with Clang and the GNU Compiler Collection.

On a Debian-based system, the installation process is straightforward; however, before installing any of the required packages, we recommend running the following command to ensure your system is up to date:

sudo apt-get update

Let us go through the list of essential software and install whatever is missing.

  1. GCC Compiler: Assuming you have a properly configured apt package manager, run the following command to install the GCC compiler and related tools. We tested GCC 12:

    sudo apt-get install build-essential
  2. CMake: The CMake build tool is also available in the standard repositories. To install CMake, type the following command:

    sudo apt-get install cmake

Note

CMake 3.19 or above is sufficient for the code samples in this book.

  1. Git: To install the Git version control system, run the following command:
    sudo apt-get install git
  2. Python 3: To install the Python 3 package, run the following command:
    sudo apt-get install python3.7

The exact version of Python may vary between Linux distributions. Any version of Python 3 will suffice for the scripts in this book.

Now we are done with the basic packages and can install graphics-related software. Let us move on to the next recipe to learn how to set up the Vulkan SDK.

Installing the Vulkan SDK for Windows and Linux

Section titled “Installing the Vulkan SDK for Windows and Linux”

In this recipe, you will learn how to get started with the Vulkan SDK. We will describe the requirements and procedure for installing the LunarG Vulkan SDK for Windows and Linux.

In principle, it is possible to write Vulkan applications without the Vulkan SDK, using only C/C++ header files provided by Khronos. You can get these header files by cloning the Git repository: https://github.com/KhronosGroup/Vulkan-Headers. However, it is advised to install the complete Vulkan SDK to be able to use Vulkan validation layers and a standalone GLSL compiler.

Make sure you have the latest up-to-date video card drivers for your operating system. On Windows, you can download video drivers from your GPU vendor’s website. For Ubuntu, refer to the documentation: https://ubuntu.com/server/docs/nvidia-drivers-installation.

To install Vulkan 1.3 on Linux, follow these steps:

  1. Open the https://www.lunarg.com/vulkan-sdk/ page in a browser and download the latest Vulkan SDK for Windows or Linux.
  2. After the download has finished, run the Windows installer file and follow the on-screen instructions. If you have Ubuntu 22.04 installed, use the following commands provided on LunarG’s website:
    wget -qO- https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc
    sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-1.3.296-jammy.list https://packages.lunarg.com/vulkan/1.3.296/lunarg-vulkan-1.3.296-jammy.list
    sudo apt update
    sudo apt install vulkan-sdk
  3. For other Linux distributions, you may need to download the .tar.gz SDK archive from https://vulkan.lunarg.com/sdk/home#linux and unpack it manually. You need to set environment variables to locate the Vulkan SDK components. Use the source command to run a config script that will do it for you:
    source ~/vulkan/1.3.296.1/setup-env.sh

When developing cross-platform applications, it is good to use similar tools for each platform. Since Linux supports GCC and Clang compilers, using GCC or Clang on Windows ensures that you avoid the most common portability issues. A complete package of C and C++ compilers can be downloaded from http://www.equation.com/servlet/equation.cmd?fa=fortran.

An alternative way to use GCC on Windows is to install the MSYS2 environment from https://www.msys2.org. It features the package management system used in Arch Linux, Pacman.

This book’s examples use multiple open-source libraries. To manage these dependencies, we use a free and open-source tool called Bootstrap. The tool is similar to Google’s repo tool and works on both Windows and Linux, as well as on macOS for that matter.

In this recipe, we will learn how to use Bootstrap to download libraries using the Vulkan Headers repository as an example.

Make sure you have Git and Python installed as described in the previous recipes. After that, clone the Bootstrap repository from GitHub:

git clone https://github.com/corporateshark/bootstrapping

Let’s look into the source code bundle and run the bootstrap.py script:

bootstrap.py

The script will start downloading all the third-party libraries required to compile and run the source code bundle for this book. On Windows, the tail of the output should look as follows.

Cloning into 'M:\Projects.CPP\Book_Rendering2\Sources\deps\src\assimp'...
remote: Enumerating objects: 25, done.
remote: Counting objects: 100% (25/25), done.
remote: Compressing objects: 100% (24/24), done.
remote: Total 51414 (delta 2), reused 10 (delta 1), pack-reused 51389
Receiving objects: 100% (51414/51414), 148.46 MiB | 3.95 MiB/s, done.
Resolving deltas: 100% (36665/36665), done.
Checking out files: 100% (2163/2163), done.

Once the download process is complete, we are ready to build the project.

Bootstrap takes a JSON file as input, opening bootstrap.json from the current directory by default. It contains metadata of libraries we want to download; for example, their names, where to retrieve them from, a specific version to download, and so on. Besides that, each used library can have some additional instructions on how to build it. Those can be patches applied to the original library, unpacking instructions, SHA hashes to check archive integrity, and many others.

The source code for each library can be represented by either a URL of a version control system repository or by an archive file with the library source files.

A typical JSON file entry corresponding to one library looks like this snippet:

[{
"name": "vulkan",
"source": {
"type": "git",
"url" : "https://github.com/KhronosGroup/Vulkan-Headers.git",
"revision": "v1.3.296"
}
}]

The field type can have one of these values: archive, git, hg, or svn. The first value corresponds to an archive file, such as .zip, .tar.gz, or .tar.bz2, while the last three types describe different version control system repositories. The url field contains a URL of the archive file to be downloaded or a URL of the repository. The revision field can specify a particular revision, tag, or branch to check out.

The complete JSON file is a comma-separated list of such entries. For this recipe, we have only one library to download. We will add more libraries in the next chapters. The accompanying source code bundle contains a JSON file with all the libraries used in this book.

There is comprehensive documentation for this tool that describes other command-line options and JSON fields in great detail. It can be downloaded from https://github.com/corporateshark/bootstrapping.

The Bootstrap tool does not differentiate between source code and binary assets. All the textures, 3D models, and other resources for your application can also be downloaded and kept up to date and organized in an automated way.

This book makes use of free 3D graphics datasets as much as possible. The comprehensive list of large 3D datasets is maintained by Morgan McGuire – Computer Graphics Archive, July 2017 (https://casual-effects.com/data). We will use some large 3D models from his archive for demonstration purposes in this book. Let us download one of them.

The bundled source code contains a Python script, deploy_deps.py, which will download all the required 3D models automatically. To download the entire Bistro dataset manually, which is not recommended, follow these simple steps:

  1. Open the https://casual-effects.com/data/ page in a browser and find the Amazon Lumberyard Bistro dataset.
  2. Click on the Download link and allow the browser to download all the data files. Below is a screenshot of Morgan McGuire’s site with the download link.

Figure 1.9: Amazon Lumberyard Bistro as pictured on casualeffects.com as a 2.4 GB download

In this recipe, we will see how CMake is used to configure all the code examples in this book and learn some small tricks along the way.

Read more

For those who are just starting with CMake, we recommend reading the books CMake Cookbook (Radovan Bast and Roberto Di Remigio) by Packt Publishing and Mastering CMake (Ken Martin and Bill Hoffman) by Kitware.

For a start, let’s create a minimalistic C++ application with a trivial main() function and build it using CMake:

int main() {
printf("Hello World!\n");
return 0;
}

Let’s introduce two helper macros for CMake. You can find them in the CMake/CommonMacros.txt file of our source code bundle at https://github.com/PacktPublishing/3D-Graphics-Rendering-Cookbook-Second-Edition.

  1. The SETUP_GROUPS macro iterates over a space-delimited list of C and C++ files, whether it is a header or a source file, and assigns each of them to a separate group. The group name is constructed based on the path of each individual file. This way, we end up with a nice structure similar to a filesystem within a directory in the Visual Studio Solution Explorer window, as we can see on the right in the following figure:

Figure 1.10: Without groups (left) and with groups (right)

  1. The macro starts by iterating over a list of files passed in the src_files parameter:
    macro(SETUP_GROUPS src_files)
    foreach(FILE ${src_files})
    get_filename_component(PARENT_DIR "${FILE}" PATH)
  2. We store the parent directory name as a default group name. Regardless of the operating system, replace all forward slashes with backslashes:
    set(GROUP "${PARENT_DIR}")
    string(REPLACE "/" "\\" GROUP "${GROUP}")
  3. Then, we can tell CMake to assign the current file to a source group with this name.
    source_group("${GROUP}" FILES "${FILE}")
    endforeach()
    endmacro()
  4. The second macro, SETUP_APP, is used as a shortcut to create a new CMake project with all the standard properties we want it to have. It is very convenient when having to deal with a number of very similar subprojects, for example, like in this book.
    macro(SETUP_APP projname chapter)
    set(FOLDER_NAME ${chapter})
    set(PROJECT_NAME ${projname})
    project(${PROJECT_NAME} CXX)
  5. After setting the project name, this macro uses the GLOB_RECURSE function to collect all source and header files into the SRC_FILES and HEADER_FILES variables.
    file(GLOB_RECURSE SRC_FILES LIST_DIRECTORIES false
    RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} src/*.c??)
    file(GLOB_RECURSE HEADER_FILES LIST_DIRECTORIES false
    RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} src/*.h)
  6. In all our code samples, we use the directory src containing the source files as an include directory, too.
    include_directories(src)
  7. All enumerated source and header files are added to an executable inside the current project.
    add_executable(${PROJ_NAME} ${SRC_FILES} ${HEADER_FILES})
  8. We use the SETUP_GROUP macro from Step 1 to place each source and header file into an appropriate group inside the project.
    SETUP_GROUPS("${SRC_FILES}")
    SETUP_GROUPS("${HEADER_FILES}")
  9. The next three properties set different executable file names for each supported build configuration. These lines are optional, yet they are really useful when using CMake with the Visual Studio IDE. The reason is that Visual Studio can change build configurations (or “build types”, as they are called in CMake) dynamically directly from the IDE, and each build configuration can have its own output file name. We add suffixes to these file names so that they can co-exist in a single output folder.
    set_target_properties(${PROJ_NAME}
    PROPERTIES OUTPUT_NAME_DEBUG ${PROJ_NAME}_Debug)
    set_target_properties(${PROJ_NAME}
    PROPERTIES OUTPUT_NAME_RELEASE ${PROJ_NAME}_Release)
    set_target_properties(${PROJ_NAME}
    PROPERTIES OUTPUT_NAME_RELWITHDEBINFO ${PROJ_NAME}_ReleaseDebInfo)
  10. Since we use C++20 throughout this book, we require CMake to enable it.
    set_property(
    TARGET ${PROJ_NAME} PROPERTY CXX_STANDARD 20)
    set_property(
    TARGET ${PROJ_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
  11. To ease the debugging with Visual Studio, we enable console output by changing the application type to Console. We also set the local debugger working directory to CMAKE_SOURCE_DIR, which will make finding assets a lot more straightforward and consistent. There are some Apple-specific properties to allow building the source code on Mac machines.
    if(MSVC)
    add_definitions(-D_CONSOLE)
    set_property(TARGET ${PROJ_NAME} PROPERTY
    VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
    endif()
    if(APPLE)
    set_target_properties(${PROJECT_NAME} PROPERTIES
    XCODE_GENERATE_SCHEME TRUE
    XCODE_SCHEME_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
    endif()
    endmacro()
  12. Finally, the top-level CMakeLists.txt file of our first project will look like this:
    cmake_minimum_required(VERSION 3.19)
    project(Chapter01)
    include(../../CMake/CommonMacros.txt)
    SETUP_APP(Ch01_Sample01_CMake "Chapter 01")

Note

You may notice that the line project(Chapter01) above is overridden by a call to project() inside the SETUP_APP macro. This is due to the following CMake warning, which will be emitted if we do not declare a new project right from the get-go.

CMake Warning (dev) in CMakeLists.txt:
No project() command is present. The top-level CMakeLists.txt file must contain a literal, direct call to the project() command. Add a line of project(ProjectName) near the top of the file, but after cmake_minimum_required().
  1. To build and test the executable, create the build subfolder, change the working directory to build, and run CMake as follows:
    • For Windows and Visual Studio 2022, run the following command to configure our project for the 64-bit target platform architecture.
      cmake .. -G "Visual Studio 17 2022" -A x64
      • For Linux, we can use the Unix Makefiles CMake generator as follows:
      cmake .. -G "Unix Makefiles"
  2. To build an executable for the release build type, you can use the following command on any platform. To build a debug version, use --config Debug or skip that parameter entirely.
    cmake --build . --config Release

All the demo applications from the source code bundle should be run from the folder where the data/ subfolder is located.

Alternatively, you can use the cross-platform build system Ninja along with CMake. It is possible to do so simply by changing the CMake project generator name.

cmake .. -G "Ninja"

Invoke Ninja from the command line to compile the project.

ninja
[2/2] Linking CXX executable Ch01_Sample01_CMake.exe

Notice how fast everything gets built now, compared to the classic cmake --build command. See https://ninja-build.org for more details.

Now let’s take a look at how to work with some basic open source libraries.

The GLFW library hides all the complexity of creating windows, graphics contexts, and surfaces and getting input events from the operating system. In this recipe, we build a minimalistic application with GLFW to get an empty window onto the screen.

We build our examples with GLFW 3.4. Here is a JSON snippet for the Bootstrap script so that you can download the proper library version:

{
"name": "glfw",
"source": {
"type": "git",
"url": "https://github.com/glfw/glfw.git",
"revision": "3.4"
}
}

The complete source code for this recipe can be found in the source code bundle under the name of Chapter01/02_GLFW.

Let’s write a minimalistic application that creates a window and waits for an exit command from the user – pressing the Esc key. This functionality will be used in all of our subsequent demos, so we have wrapped it into a helper function initWindow() declared in shared/HelpersGLFW.h. Let’s take a look at how to use it to create an empty GLFW window:

  1. Include all necessary headers and decide on the initial window dimensions:
    #include <shared/HelpersGLFW.h>
    int main() {
    uint32_t width = 1280;
    uint32_t height = 800;
  2. Invoke the initWindow() function to create a window. The width and height parameters are passed by reference and, after the call, will contain the actual working area of the created window. If we pass the initial values of 0, the window will be created to span the entire desktop working area without overlapping the system taskbar.
    GLFWwindow* window =
    initWindow("GLFW example", width, height);
  3. For this application, the main loop and cleanup are trivial:
    while (!glfwWindowShouldClose(window)) {
    glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
    }

Now we will take a look at the internals of initWindow() for some interesting details.

Let’s use this library to create an application that opens an empty window:

  1. First, we set the GLFW error callback via a lambda to catch potential errors and then initialize GLFW:
    GLFWwindow* initWindow(const char* windowTitle,
    uint32_t& outWidth, uint32_t& outHeight) {
    glfwSetErrorCallback( {
    printf("GLFW Error (%i): %s\n", error, description);
    });
    if (!glfwInit()) return nullptr;
  2. Let’s decide if we want to make a desktop full-screen window. Set the resizable flag for windows that aren’t full-screen and retrieve the desired window dimensions. We are going to initialize Vulkan manually, so no graphics API initialization is required to be done by GLFW. The flag wantsWholeArea determines if we want a true full-screen window or a window that does not overlap the system taskbar.
    const bool wantsWholeArea = !outWidth || !outHeight;
    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
    glfwWindowHint(GLFW_RESIZABLE,
    wantsWholeArea ? GLFW_FALSE : GLFW_TRUE);
    GLFWmonitor* monitor = glfwGetPrimaryMonitor();
    const GLFWvidmode* mode = glfwGetVideoMode(monitor);
    int x = 0;
    int y = 0;
    int w = mode->width;
    int h = mode->height;
    if (wantsWholeArea) {
    glfwGetMonitorWorkarea(monitor, &x, &y, &w, &h);
    } else {
    w = outWidth;
    h = outHeight;
    }
  3. Create a window and retrieve the actual window dimensions:
    GLFWwindow* window = glfwCreateWindow(
    w, h, windowTitle, nullptr, nullptr);
    if (!window) {
    glfwTerminate();
    return nullptr;
    }
    if (wantsWholeArea) glfwSetWindowPos(window, x, y);
    glfwGetWindowSize(window, &w, &h);
    outWidth = (uint32_t)w;
    outHeight = (uint32_t)h;
  4. Set a default keyboard callback to handle the Esc key. A simple lambda will do this job for us.
    glfwSetKeyCallback(window, {
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
    glfwSetWindowShouldClose(window, GLFW_TRUE);
    }
    });
    return window;
    }

If you run this tiny application, it will create an empty window, as in the following screenshot:

Figure 1.11: Our first application

Further details about how to use GLFW can be found at https://www.glfw.org/documentation.html.

Modern graphical applications require us to harness the power of multiple CPUs to be performant. Taskflow is a fast C++ header-only library that can help you write parallel programs with complex task dependencies quickly. This library is extremely useful as it allows you to jump into the development of multithreaded graphical applications that make use of advanced rendering concepts, such as frame graphs and multithreaded command buffer generation.

Here, we use Taskflow version 3.8.0. You can download it using the following Bootstrap snippet:

{
"name": "taskflow",
"source": {
"type": "git",
"url" : "https://github.com/taskflow/taskflow.git",
"revision": "v3.8.0"
}
}

To debug dependency graphs produced by Taskflow, it is recommended that you install the GraphViz tool from https://www.graphviz.org.

The complete source code for this recipe can be found in Chapter01/03_Taskflow.

Let’s create and run a set of concurrent dependent tasks via the for_each_index() algorithm. Each task will print a single value from an array in a concurrent fashion. The processing order can vary between different runs of the program:

  1. Include the taskflow.hpp header file. The tf::Taskflow class is the main place to create a task dependency graph. Declare an instance and a data vector to process.
    #include <taskflow/taskflow.hpp>
    int main() {
    tf::Taskflow taskflow;
    std::vector<int> items{ 1, 2, 3, 4, 5, 6, 7, 8 };
  2. The for_each_index() member function returns a task that implements a parallel for loop algorithm. We specify the range 0..items.size() and the step 1. The returned task can be used for synchronization purposes:
    auto task = taskflow.for_each_index(
    0u, uint32_t(items.size()), 1u, [&](int i) {
    printf("%i", items[i]);
    }).name("for_each_index");
  3. Let’s attach some work before and after the parallel for task so that we can view Start and End messages in the output. Let’s call the new S and T tasks accordingly:
    taskflow.emplace([]() {
    printf("\nS - Start\n"); }).name("S").precede(task);
    taskflow.emplace([]() {
    printf("\nT - End\n"); }).name("T").succeed(task);
  4. Save the generated tasks dependency graph in .dot format so that we can process it later with the GraphViz dot tool:
    std::ofstream os(".cache/taskflow.dot");
    taskflow.dump(os);
  5. Now we can create a tf::executor object and run the constructed Taskflow graph:
    tf::Executor executor;
    executor.run(taskflow).wait();
    return 0;
    }

An important point to note is that the Taskflow dependency graph is built only once. After that, it can be reused in every frame to efficiently execute concurrent tasks.

The output from the preceding program should look similar to the following listing:

S – Start
18345672
T - End

Here, we can see our S and T tasks. Between them, there are multiple threads with different IDs processing different elements of the items[] vector in parallel. Your output may vary due to concurrency.

The application saved the dependency graph inside the .cache/taskflow.dot file. It can be converted into a visual representation by GraphViz, https://graphviz.org, using the following command:

dot -Tpng taskflow.dot > output.png

The resulting .png image should look similar to the following screenshot:

Figure 1.12: The Taskflow dependency graph for for_each_index()

This functionality is extremely useful when you are debugging complex dependency graphs (and producing complex-looking images for your books and papers).

The Taskflow library functionality is vast and provides implementations for numerous parallel algorithms and profiling capabilities. Please refer to the official documentation for in-depth coverage at https://taskflow.github.io/taskflow/index.html.

Before we can start working with Vulkan, it’s important to speed up the iterative process of writing shaders. Vulkan uses shaders in the binary form called Standard Portable Intermediate Representation, known as SPIR-V, and typically relies on a standalone shader compiler to precompile shaders offline. While this is ideal for a released product, it can slow down early stages of development and rapid prototyping, where shaders are frequently changed and need to be recompiled with every run. In this recipe, we’ll show you how to compile Vulkan shaders at runtime using Khronos’ reference shader compiler glslang.

Our application is using LightweightVK which is statically linked to the glslang shader compiler. The compiler version used in this recipe was downloaded using the following Bootstrap snippet.

{
"name": "glslang",
"source": {
"type": "git",
"url" : "https://github.com/KhronosGroup/glslang.git",
"revision": "15.1.0"
}
}

The complete source code for this recipe can be found in the source code bundle under the name Chapter01/04_GLSLang. The implementation of shader compilation in LightweightVK is located in deps/src/lightweightvk/lvk/vulkan/VulkanUtils.cpp in the function lvk::compileShader().

Let us go through the steps necessary to compile GLSL shaders to SPIR-V using glslang. In this book text, we’ve omitted most error checking for clarity, though it is included in the actual source code.

  1. We should use this helper function to compile a GLSL shader from its source code for a specific Vulkan pipeline stage and return the resulting SPIR-V binary as a vector bytes. Initializing the compiler input structure can be a bit verbose. We specify the shader’s source language as GLSLANG_SOURCE_GLSL and set the correct targets to generate SPIR-V 1.6 for Vulkan 1.3. With C++20’s designated initializers, this task becomes much simpler. This feature is also helpful in general Vulkan development, where a common task for developers is to populate structure members with specific values.
    lvk::Result compileShader(
    glslang_stage_t stage,
    const char* code,
    std::vector<uint8_t>* outSPIRV,
    const glslang_resource_t* glslLangResource)
    {
    const glslang_input_t input = {
    .language = GLSLANG_SOURCE_GLSL,
    .stage = stage,
    .client = GLSLANG_CLIENT_VULKAN,
    .client_version = GLSLANG_TARGET_VULKAN_1_3,
    .target_language = GLSLANG_TARGET_SPV,
    .target_language_version = GLSLANG_TARGET_SPV_1_6,
    .code = code,
    .default_version = 100,
    .default_profile = GLSLANG_NO_PROFILE,
    .force_default_version_and_profile = false,
    .forward_compatible = false,
    .messages = GLSLANG_MSG_DEFAULT_BIT,
    .resource = glslLangResource,
    };
  2. Let`s create a glslang shader object using the abovementioned input. The SCOPE_EXIT macro ensures the shader object is properly deallocated whenever we exit the current scope. Its implementation is beyond the scope of this book. However, we recommend watching the CppCon 2015 presentation Declarative Control Flow by Andrei Alexandrescu which dives deep into the implementation details. The implementation we use is located in deps/src/lightweightvk/third-party/deps/src/ldrutils/lutils/ScopeExit.h.
    glslang_shader_t* shader = glslang_shader_create(&input);
    SCOPE_EXIT {
    glslang_shader_delete(shader);
    };
  3. The shader needs to be preprocessed by the compiler. The following function returns true if all extensions, pragmas and version strings mentioned in the shader source code are valid. The logShaderSource() function prints to the console the source code of the shader together with line numbers and is very handy for debugging.
    if (!glslang_shader_preprocess(shader, &input)) {
    LLOGW("Shader preprocessing failed:\n");
    LLOGW(" %s\n", glslang_shader_get_info_log(shader));
    LLOGW(" %s\n",
    glslang_shader_get_info_debug_log(shader));
    lvk::logShaderSource(code);
    return Result(Result::Code::RuntimeError);
    }
  4. Then the shader gets parsed into an internal representation inside the compiler.
    if (!glslang_shader_parse(shader, &input)) {
    LLOGW("Shader parsing failed:\n");
    LLOGW(" %s\n", glslang_shader_get_info_log(shader));
    LLOGW(" %s\n",
    glslang_shader_get_info_debug_log(shader));
    lvk::logShaderSource(
    glslang_shader_get_preprocessed_code(shader));
    return Result(Result::Code::RuntimeError);
    }
  5. If everything went fine during the previous stages, now we can link the shader into a program and proceed with the binary code generation stage. The same SCOPE_EXIT is applied to program to prevent memory leaks.
    glslang_program_t* program = glslang_program_create();
    glslang_program_add_shader(program, shader);
    SCOPE_EXIT {
    glslang_program_delete(program);
    };
    if (!glslang_program_link(program,
    GLSLANG_MSG_SPV_RULES_BIT |
    GLSLANG_MSG_VULKAN_RULES_BIT)) {
    LLOGW("Shader linking failed:\n");
    LLOGW(" %s\n", glslang_program_get_info_log(program));
    LLOGW(" %s\n",
    glslang_program_get_info_debug_log(program));
    return Result(Result::Code::RuntimeError);
    }
  6. Now we are ready to generate some binary SPIR-V code. The glslang compiler supports multiple code generation flags to control debug info generation. This is useful if you want to inspect your shaders at run-time with a tool such as RenderDoc.
    glslang_spv_options_t options = {
    .generate_debug_info = true,
    .strip_debug_info = false,
    .disable_optimizer = false,
    .optimize_size = true,
    .disassemble = false,
    .validate = true,
    .emit_nonsemantic_shader_debug_info = false,
    .emit_nonsemantic_shader_debug_source = false,
    };
    glslang_program_SPIRV_generate_with_options(
    program, input.stage, &options);
  7. There might be some messages produced by the code generator. Check and print them if there are any. The resulting SPIR-V code can be retrieved in the following way. We return it as a binary blob of uint8_t values.
    if (glslang_program_SPIRV_get_messages(program)) {
    LLOGW("%s\n",
    glslang_program_SPIRV_get_messages(program));
    }
    const uint8_t* spirv = reinterpret_cast<const uint8_t*>(
    glslang_program_SPIRV_get_ptr(program));
    const size_t numBytes =
    glslang_program_SPIRV_get_size(program) *
    sizeof(uint32_t);
    *outSPIRV = std::vector(spirv, spirv + numBytes);
    return Result();
    }

Let’s inspect the demo application which loads GLSL shader code from files, compiles it using the abovementioned function, and then saves SPIR-V binaries into files.

The application is straightforward. It loads the shader source code from a text file and uses the compileShader() function we have just written to compile it into SPIR-V.

void testShaderCompilation(
const char* sourceFilename, const char* destFilename)
{
std::string shaderSource = readShaderFile(sourceFilename);
std::vector<uint8_t> spirv;
lvk::Result res = lvk::compileShader(
vkShaderStageFromFileName(sourceFilename),
shaderSource.c_str(),
&spirv,
glslang_default_resource());
saveSPIRVBinaryFile(destFilename, spirv.data(), spirv.size());
}

Each generated SPIR-V binary blob is saved to a file for further inspection.

void saveSPIRVBinaryFile(
const char* filename, const uint8_t* code, size_t size)
{
FILE* f = fopen(filename, "wb");
fwrite(code, sizeof(uint8_t), size, f);
fclose(f);
}

The main() function, which drives the demo application, initializes the glslang compiler and runs the tests.

int main()
{
glslang_initialize_process();
testShaderCompilation("Chapter01/04_GLSLang/src/main.vert",
".cache/04_GLSLang.vert.bin");
testShaderCompilation("Chapter01/04_GLSLang/src/main.frag",
".cache/04_GLSLang.frag.bin");
glslang_finalize_process();
return 0;
}

The abovementioned program produces the same SPIR-V output as the following console commands:

glslangValidator
-g -Os --target-env vulkan1.3 main.vert -o main.vert.bin
glslangValidator
-g -Os --target-env vulkan1.3 main.frag -o main.frag.bin

Binary SPIR-V modules can be used to create Vulkan shader modules as follows. One key detail to note in this example is how to determine the size of the push constants used by the shader. This information will be important in later chapters when we build Vulkan pipelines:

ShaderModuleState VulkanContext::createShaderModuleFromSPIRV(
const void* spirv,
size_t numBytes,
const char* debugName,
Result* outResult) const
{
VkShaderModule vkShaderModule = VK_NULL_HANDLE;
const VkShaderModuleCreateInfo ci = {
.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
.codeSize = numBytes,
.pCode = (const uint32_t*)spirv,
};
const VkResult result =
vkCreateShaderModule(vkDevice_, &ci, nullptr, &vkShaderModule);
lvk::setResultFrom(outResult, result);
if (result != VK_SUCCESS) return {.sm = VK_NULL_HANDLE};
VK_ASSERT(lvk::setDebugObjectName(
vkDevice_,
VK_OBJECT_TYPE_SHADER_MODULE,
(uint64_t)vkShaderModule,
debugName));

After creating the Vulkan shader module, we can determine the size of the push constants used by the shader. To do this, we use the SPIRV-Reflect library, which makes it easy to extract this information:

SpvReflectShaderModule mdl;
SpvReflectResult result = spvReflectCreateShaderModule(
numBytes, spirv, &mdl);
SCOPE_EXIT {
spvReflectDestroyShaderModule(&mdl);
};
uint32_t pushConstantsSize = 0;
for (uint32_t i = 0; i < mdl.push_constant_block_count; ++i) {
const SpvReflectBlockVariable& block =
mdl.push_constant_blocks[i];
pushConstantsSize =
std::max(pushConstantsSize, block.offset + block.size);
}
return { .sm = vkShaderModule,
.pushConstantsSize = pushConstantsSize };
}

This function is used throughout the LightweightVK library to create all Vulkan shader modules. It is located in deps/src/lightweightvk/lvk/vulkan/VulkanClasses.cpp.

While it may be convenient to include a full compiler during the development phase, shipping a large compiler with the release version of your application is generally not recommended. Unless your application specifically needs to compile shaders at runtime, it’s better to include precompiled SPIR-V shader binaries in the release version. One way to handle this is by implementing a shader caching mechanism. When a shader is needed, the application can first check if a compiled version already exists. If it doesn’t, the app can load the glslang compiler from a .dll or .so file at runtime to compile the shader. Once all shaders are cached, the cached shaders can be shipped with the app without any GLSL source code. This approach ensures that compiled shaders are always available in the release version without bundling the compiler’s shared libraries.

A major downside of high-resolution texture data is that it uses a lot of GPU memory for storage. To address this, all modern real-time rendering APIs offer texture compression, which lets us store textures in compressed formats on the GPU. One common format is BC7, a standard texture compression format for Vulkan that is supported on many devices.

bc7enc is an open-source library that can compress RGBA bitmaps into the BC7 format. In this recipe, you will learn how to integrate this library into your own applications to create tools for your custom graphics pre-processing pipelines.

The BC7 format is described in great detail in https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format and we will use it in our book to store textures for the large Lumberyard Bistro dataset.

Let’s learn how to compress 2D .jpg or .png images into BC7.

The source code for this recipe is located at Chapter01/05_BC7Compression. We use an the STB_Image library by Sean Barrett https://github.com/nothings/stb to load .jpg and .png files, and an open-source library KTX-Software from Khronos https://github.com/KhronosGroup/KTX-Software to compress images and save the compressed BC7 images in the .ktx file format, making them suitable for runtime use.

Let’s check the code in Chapter01/05_BC7Compression/src/main.cpp to load a .jpg file data/wood.jpg, compress it and save into .cache/image.ktx:

  1. First, we load the file using the STB_Image library.
    int main()
    {
    const int numChannels = 4;
    int origW, origH;
    const uint8_t* pixels = stbi_load(
    "data/Chapter02/03_STB.jpg",
    &origW, &origH, nullptr, numChannels);
  2. Next, we create a KTX texture object to store the compressed image. We calculate the number of mip-levels to generate the full BC7 -compressed mip-pyramid for this image.
    const uint32_t numMipLevels =
    lvk::calcNumMipLevels(origW, origH);
    ktxTextureCreateInfo createInfo = {
    .glInternalformat = GL_COMPRESSED_RGBA_BPTC_UNORM,
    .vkFormat = VK_FORMAT_BC7_UNORM_BLOCK,
    .baseWidth = (uint32_t)origW,
    .baseHeight = (uint32_t)origH,
    .baseDepth = 1u,
    .numDimensions = 2u,
    .numLevels = numMipLevels,
    .numLayers = 1u,
    .numFaces = 1u,
    .generateMipmaps = KTX_FALSE,
    };
    ktxTexture1* texture = nullptr;
    ktxTexture1_Create(&createInfo,
    KTX_TEXTURE_CREATE_ALLOC_STORAGE, &texture);
  3. Let’s go through each mip-level, generate a down-sampled version of the image for each one, and store it in the KTX texture.
    int w = origW;
    int h = origH;
    for (uint32_t i = 0; i != numMipLevels; ++i) {
    size_t offset = 0;
    ktxTexture_GetImageOffset(
    ktxTexture(textureKTX2), i, 0, 0, &offset);
    stbir_resize_uint8_linear(
    (const unsigned char*)pixels, origW, origH, 0,
    ktxTexture_GetData(ktxTexture(textureKTX2)) + offset,
    w, h, 0, STBIR_RGBA);
    h = h > 1 ? h >> 1 : 1;
    w = w > 1 ? w >> 1 : 1;
    }
  4. Use KTX-Software to compress the image, including its entire mip-pyramid, into the Basis format. Then, transcode the Basis format to BC7.
    ktxTexture2_CompressBasis(textureKTX2, 255);
    ktxTexture2_TranscodeBasis(
    textureKTX2, KTX_TTF_BC7_RGBA, 0);
  5. Use KTX-Software to save the image in the KTX1 file format. We choose the older KTX1 format because viewing tools for it are more widely available than those for KTX2. For instance, you can use PicoPixel to view the resulting files.
    ktxTextureCreateInfo createInfoKTX1 = {
    .glInternalformat = GL_COMPRESSED_RGBA_BPTC_UNORM,
    .vkFormat = VK_FORMAT_BC7_UNORM_BLOCK,
    .baseWidth = (uint32_t)origW,
    .baseHeight = (uint32_t)origH,
    .baseDepth = 1u,
    .numDimensions = 2u,
    .numLevels = numMipLevels,
    .numLayers = 1u,
    .numFaces = 1u,
    .generateMipmaps = KTX_FALSE,
    };
    ktxTexture1* textureKTX1 = nullptr;
    ktxTexture1_Create(&createInfoKTX1,
    KTX_TEXTURE_CREATE_ALLOC_STORAGE, &textureKTX1);
    for (uint32_t i = 0; i != numMipLevels; ++i) {
    size_t offset1 = 0;
    ktxTexture_GetImageOffset(
    ktxTexture(textureKTX1), i, 0, 0, &offset1);
    size_t offset2 = 0;
    ktxTexture_GetImageOffset(ktxTexture(
    textureKTX2), i, 0, 0, &offset2);
    memcpy(
    ktxTexture_GetData(ktxTexture(textureKTX1)) + offset1,
    ktxTexture_GetData(ktxTexture(textureKTX2)) + offset2,
    ktxTexture_GetImageSize(ktxTexture(textureKTX1), i));
    }
    ktxTexture_WriteToNamedFile(
    ktxTexture(textureKTX1), ".cache/image.ktx");
    ktxTexture_Destroy(ktxTexture(textureKTX1));
    ktxTexture_Destroy(ktxTexture(textureKTX2));
    stbi_image_free(pixels);
    return 0;
    }

The image is now saved in the cache/image.ktx file. In the following chapters, we’ll load it into a Vulkan texture.

The KTX File Format Specification is maintained by Khronos and is located at https://registry.khronos.org/KTX/specs/1.0/ktxspec.v1.html. We use KTX Version 1.0 throughout this book for compatibility with PicoPixel.

PicoPixel is a great tool that you can use to view .ktx files and other texture formats https://pixelandpolygon.com. It is freeware but not open source. There is a publicly available issues tracker on GitHub. You can find it at https://github.com/inalogic/pico-pixel-public/issues.

For those who want to jump into the latest state-of-the-art texture compression techniques, check out please refer to the Basis project from Binomial at https://github.com/BinomialLLC/basis_universal.

Let’s move on to the next chapter and learn how to start working with Vulkan.