Vulkan 编程指南 - 实例 (Vulkan Tutorial / Instance / 01_instance_creation.cpp)

2023-11-27 22:20

本文主要是介绍Vulkan 编程指南 - 实例 (Vulkan Tutorial / Instance / 01_instance_creation.cpp),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Vulkan 编程指南 - 实例 (Vulkan Tutorial / Instance / 01_instance_creation.cpp)

仅供个人学习、研究使用,建议大家阅读 Vulkan Tutorial

Drawing a triangle / Setup / Instance
https://vulkan-tutorial.com/Drawing_a_triangle/Setup/Instance

Vulkan Tutorial
https://vulkan-tutorial.com/

GitHub Repository
https://github.com/Overv/VulkanTutorial

1 Instance (实例)

1.1 Creating an instance

The very first thing you need to do is initialize the Vulkan library by creating an instance. The instance is the connection between your application and the Vulkan library and creating it involves specifying some details about your application to the driver.
我们首先创建一个实例来初始化 Vulkan 库。这个实例是你的应用程序和 Vulkan 库之间的连接,创建它需要向驱动指定一些关于你的应用程序的信息。

Start by adding a createInstance function and invoking it in the initVulkan function.

void initVulkan() {createInstance();
}

Additionally add a data member to hold the handle to the instance (添加了一个存储实例句柄的私有成员):

private:
VkInstance instance;

Now, to create an instance we’ll first have to fill in a struct with some information about our application. This data is technically optional, but it may provide some useful information to the driver in order to optimize our specific application (e.g. because it uses a well-known graphics engine with certain special behavior).
现在,为了创建一个实例,我们首先要在一个结构中填写关于我们应用程序的一些信息。这些数据在技术上是可选的,但填写的信息可能会作为驱动程序的优化依据,让驱动程序进行一些特殊的优化。例如,应用程序使用了某个引擎,驱动程序对这个引擎有一些特殊处理,这时就可能有很大的优化提升。

This struct is called VkApplicationInfo:

void createInstance() {VkApplicationInfo appInfo{};appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;appInfo.pApplicationName = "Hello Triangle";appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);appInfo.pEngineName = "No Engine";appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);appInfo.apiVersion = VK_API_VERSION_1_0;
}

As mentioned before, many structs in Vulkan require you to explicitly specify the type in the sType member. This is also one of the many structs with a pNext member that can point to extension information in the future. We’re using value initialization here to leave it as nullptr.
之前提到,Vulkan 的很多结构体需要我们显式地在 sType 成员变量中指定结构体的类型。此外,许多 Vulkan 结构体还有一个 pNext 成员变量,用来指向未来可能扩展的参数信息,现在,我们并没有使用它,将其设置为 nullptr

A lot of information in Vulkan is passed through structs instead of function parameters and we’ll have to fill in one more struct to provide sufficient information for creating an instance. This next struct is not optional and tells the Vulkan driver which global extensions and validation layers we want to use. Global here means that they apply to the entire program and not a specific device, which will become clear in the next few chapters.
Vulkan 倾向于通过结构体传递信息,我们需要填写一个或多个结构体来提供足够的信息创建 Vulkan 实例。下面的这个结构体是必须的,它告诉 Vulkan 的驱动程序需要使用的全局扩展和校验层。全局是指这里的设置对于整个应用程序都有效,而不仅仅对一个设备有效。

VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;

The first two parameters are straightforward. The next two layers specify the desired global extensions. As mentioned in the overview chapter, Vulkan is a platform agnostic API, which means that you need an extension to interface with the window system. GLFW has a handy built-in function that returns the extension(s) it needs to do that which we can pass to the struct.

上面代码中填写得两个参数非常直白,不用多解释。接下来,我们需要指定需要的全局扩展。正如在概述章节中提到的,Vulkan 是一个与平台无关的 API,这意味着你需要一个扩展来与窗口系统对接。GLFW 有一个方便的内置函数,可以返回它所需要的扩展,我们可以将其传递给结构。

uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;

The last two members of the struct determine the global validation layers to enable. We’ll talk about these more in-depth in the next chapter, so just leave these empty for now.
结构体的最后两个成员变量用来指定全局校验层。在这里,我们将其设置为 0,不使用它。

createInfo.enabledLayerCount = 0;

We’ve now specified everything Vulkan needs to create an instance and we can finally issue the vkCreateInstance call.
填写完所有必要的信息,我们就可以调用 vkCreateInstance 函数来创建 Vulkan 实例。

VkResult result = vkCreateInstance(&createInfo, nullptr, &instance);

As you’ll see, the general pattern that object creation function parameters in Vulkan follow is:

  • Pointer to struct with creation info (一个包含了创建信息的结构体指针)
  • Pointer to custom allocator callbacks, always nullptr in this tutorial (一个自定义的分配器回调函数,在本教程,我们没有使用自定义的分配器,总是将它设置为 nullptr)
  • Pointer to the variable that stores the handle to the new object (一个指向新对象句柄存储位置的指针)

If everything went well then the handle to the instance was stored in the VkInstance class member. Nearly all Vulkan functions return a value of type VkResult that is either VK_SUCCESS or an error code. To check if the instance was created successfully, we don’t need to store the result and can just use a check for the success value instead.
如果一切顺利,我们创建的实例的句柄就被存储在了类的 VkInstance 成员变量中。几乎所有 Vulkan 函数调用都会返回一个 VkResult 来反应函数调用的结果,它的值可以是 VK_SUCCESS 表示调用成功,或是一个错误代码,表示调用失败。为了检测实例是否创建成功,我们可以直接将创建函数在条件语句中使用,不需要存储它的返回值。

if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {throw std::runtime_error("failed to create instance!");
}

Now run the program to make sure that the instance is created successfully.

1.2 Encountered VK_ERROR_INCOMPATIBLE_DRIVER

If using MacOS with the latest MoltenVK sdk, you may get VK_ERROR_INCOMPATIBLE_DRIVER returned from vkCreateInstance. According to the Getting Start Notes. Beginning with the 1.3.216 Vulkan SDK, the VK_KHR_PORTABILITY_subset extension is mandatory.
从 Vulkan SDK 1.3.216 开始,VK_KHR_PORTABILITY_subset 扩展是强制性的。

To get over this error, first add the VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR bit to VkInstanceCreateInfo struct’s flags, then add VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME to instance enabled extension list.

Typically the code could be like this:

...std::vector<const char*> requiredExtensions;for(uint32_t i = 0; i < glfwExtensionCount; i++) {requiredExtensions.emplace_back(glfwExtensions[i]);
}requiredExtensions.emplace_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);createInfo.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;createInfo.enabledExtensionCount = (uint32_t) requiredExtensions.size();
createInfo.ppEnabledExtensionNames = requiredExtensions.data();if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {throw std::runtime_error("failed to create instance!");
}

1.3 Checking for extension support (检测扩展支持)

If you look at the vkCreateInstance documentation then you’ll see that one of the possible error codes is VK_ERROR_EXTENSION_NOT_PRESENT. We could simply specify the extensions we require and terminate if that error code comes back. That makes sense for essential extensions like the window system interface, but what if we want to check for optional functionality?
如果读者看过 vkCreateInstance 函数的官方文档,可能会知道它返回的中一个错误代码 VK_ERROR_EXTENSION_NOT_PRESENT。我们可以利用这个错误代码在扩展不能满足时直接结束我们的程序,这对于像窗口系统这种必要的扩展来说非常适合。但有时,我们请求的扩展可能是非必须的,有了很好,没有的话,程序仍然可以运行。

To retrieve a list of supported extensions before creating an instance, there’s the vkEnumerateInstanceExtensionProperties function. It takes a pointer to a variable that stores the number of extensions and an array of VkExtensionProperties to store details of the extensions. It also takes an optional first parameter that allows us to filter extensions by a specific validation layer, which we’ll ignore for now.
为了在创建实例之前检索支持的扩展列表,有一个 vkEnumerateInstanceExtensionProperties 函数。它需要一个存储扩展数量的变量指针和一个 VkExtensionProperties 的数组来存储扩展的细节。它还需要一个可选的第一个参数,允许我们通过一个特定的验证层来过滤扩展,我们现在将忽略这个参数。

To allocate an array to hold the extension details we first need to know how many there are. You can request just the number of extensions by leaving the latter parameter empty:
我们首先需要知道扩展的数量,以便分配合适的数组大小来存储信息。可以通过下面的代码来获取扩展的数量。

uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);

Now allocate an array to hold the extension details (include <vector>):

std::vector<VkExtensionProperties> extensions(extensionCount);

Finally we can query the extension details.
最后,我们可以查询扩展的详细信息。

vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions.data());

Each VkExtensionProperties struct contains the name and version of an extension. We can list them with a simple for loop (\t is a tab for indentation).
每个 VkExtensionProperties 结构包含一个扩展的名称和版本。

std::cout << "available extensions:\n";for (const auto& extension : extensions) {std::cout << '\t' << extension.extensionName << '\n';
}

You can add this code to the createInstance function if you’d like to provide some details about the Vulkan support. As a challenge, try to create a function that checks if all of the extensions returned by glfwGetRequiredInstanceExtensions are included in the supported extensions list.
如果你想提供一些关于 Vulkan 支持的细节,你可以在 createInstance 函数中加入这段代码。尝试创建一个函数,检查由 glfwGetRequiredInstanceExtensions 返回的所有扩展是否包含在支持的扩展列表中。

1.4 Cleaning up

The VkInstance should be only destroyed right before the program exits. It can be destroyed in cleanup with the vkDestroyInstance function.
VkInstance 应该只在程序退出前销毁,它可以在 cleanup 中用 vkDestroyInstance 函数销毁。

void cleanup() {vkDestroyInstance(instance, nullptr);glfwDestroyWindow(window);glfwTerminate();
}

The parameters for the vkDestroyInstance function are straightforward. As mentioned in the previous chapter, the allocation and deallocation functions in Vulkan have an optional allocator callback that we’ll ignore by passing nullptr to it. All of the other Vulkan resources that we’ll create in the following chapters should be cleaned up before the instance is destroyed.
vkDestroyInstance 函数的参数非常直白。之前提到,Vulkan 对象的分配和清除函数都有一个可选的分配器回调参数,在本教程,我们没有自定义的分配器,所以,将其设置为 nullptr。除了 Vulkan 实例,其余我们使用 Vulkan 创建的对象也需要被清除,且应该在 Vulkan 实例清除之前被清除。

Before continuing with the more complex steps after instance creation, it’s time to evaluate our debugging options by checking out validation layers.

01_instance_creation.cpp
https://github.com/Overv/VulkanTutorial/blob/main/code/01_instance_creation.cpp

01_instance_creation.cpp

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>#include <iostream>
#include <stdexcept>
#include <cstdlib>const uint32_t WIDTH = 800;
const uint32_t HEIGHT = 600;class HelloTriangleApplication {
public:void run() {initWindow();initVulkan();mainLoop();cleanup();}private:GLFWwindow* window;VkInstance instance;void initWindow() {glfwInit();glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);window = glfwCreateWindow(WIDTH, HEIGHT, "yongqiang", nullptr, nullptr);}void initVulkan() {createInstance();}void mainLoop() {while (!glfwWindowShouldClose(window)) {glfwPollEvents();}}void cleanup() {vkDestroyInstance(instance, nullptr);glfwDestroyWindow(window);glfwTerminate();}void createInstance() {VkApplicationInfo appInfo{};appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;appInfo.pApplicationName = "Hello Triangle";appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);appInfo.pEngineName = "No Engine";appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);appInfo.apiVersion = VK_API_VERSION_1_0;VkInstanceCreateInfo createInfo{};createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;createInfo.pApplicationInfo = &appInfo;uint32_t glfwExtensionCount = 0;const char** glfwExtensions;glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);createInfo.enabledExtensionCount = glfwExtensionCount;createInfo.ppEnabledExtensionNames = glfwExtensions;createInfo.enabledLayerCount = 0;if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {throw std::runtime_error("failed to create instance!");}}
};int main() {HelloTriangleApplication app;try {app.run();} catch (const std::exception& e) {std::cerr << e.what() << std::endl;return EXIT_FAILURE;}return EXIT_SUCCESS;
}

Makefile

CFLAGS = -std=c++17 -O2
LDFLAGS = -lglfw -lvulkan -ldl -lpthread -lX11 -lXxf86vm -lXrandr -lXiVulkanTest: instance_creation_01.cppg++ $(CFLAGS) -o VulkanTest instance_creation_01.cpp $(LDFLAGS).PHONY: test cleantest: VulkanTest./VulkanTestclean:rm -f VulkanTest
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$ make clean
rm -f VulkanTest
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$ make test
g++ -std=c++17 -O2 -o VulkanTest instance_creation_01.cpp -lglfw -lvulkan -ldl -lpthread -lX11 -lXxf86vm -lXrandr -lXi
./VulkanTest
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$ ls
Makefile  VulkanTest  instance_creation_01.cpp
yongqiang@yongqiang:~/vulkan_workspace/instance_creation_01$

在这里插入图片描述

References

https://yongqiang.blog.csdn.net/
Vulkan Tutorial https://vulkan-tutorial.com/
Vulkan 教程 https://geek-docs.com/vulkan/vulkan-tutorial/vulkan-tutorial-index.html

这篇关于Vulkan 编程指南 - 实例 (Vulkan Tutorial / Instance / 01_instance_creation.cpp)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/428561

相关文章

SQLite3命令行工具最佳实践指南

《SQLite3命令行工具最佳实践指南》SQLite3是轻量级嵌入式数据库,无需服务器支持,具备ACID事务与跨平台特性,适用于小型项目和学习,sqlite3.exe作为命令行工具,支持SQL执行、数... 目录1. SQLite3简介和特点2. sqlite3.exe使用概述2.1 sqlite3.exe

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

从基础到进阶详解Pandas时间数据处理指南

《从基础到进阶详解Pandas时间数据处理指南》Pandas构建了完整的时间数据处理生态,核心由四个基础类构成,Timestamp,DatetimeIndex,Period和Timedelta,下面我... 目录1. 时间数据类型与基础操作1.1 核心时间对象体系1.2 时间数据生成技巧2. 时间索引与数据

Java SWT库详解与安装指南(最新推荐)

《JavaSWT库详解与安装指南(最新推荐)》:本文主要介绍JavaSWT库详解与安装指南,在本章中,我们介绍了如何下载、安装SWTJAR包,并详述了在Eclipse以及命令行环境中配置Java... 目录1. Java SWT类库概述2. SWT与AWT和Swing的区别2.1 历史背景与设计理念2.1.

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

SpringBoot整合Apache Flink的详细指南

《SpringBoot整合ApacheFlink的详细指南》这篇文章主要为大家详细介绍了SpringBoot整合ApacheFlink的详细过程,涵盖环境准备,依赖配置,代码实现及运行步骤,感兴趣的... 目录1. 背景与目标2. 环境准备2.1 开发工具2.2 技术版本3. 创建 Spring Boot

Python远程控制MySQL的完整指南

《Python远程控制MySQL的完整指南》MySQL是最流行的关系型数据库之一,Python通过多种方式可以与MySQL进行交互,下面小编就为大家详细介绍一下Python操作MySQL的常用方法和最... 目录1. 准备工作2. 连接mysql数据库使用mysql-connector使用PyMySQL3.

Linux中修改Apache HTTP Server(httpd)默认端口的完整指南

《Linux中修改ApacheHTTPServer(httpd)默认端口的完整指南》ApacheHTTPServer(简称httpd)是Linux系统中最常用的Web服务器之一,本文将详细介绍如何... 目录一、修改 httpd 默认端口的步骤1. 查找 httpd 配置文件路径2. 编辑配置文件3. 保存

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

java String.join()方法实例详解

《javaString.join()方法实例详解》String.join()是Java提供的一个实用方法,用于将多个字符串按照指定的分隔符连接成一个字符串,这一方法是Java8中引入的,极大地简化了... 目录bVARxMJava String.join() 方法详解1. 方法定义2. 基本用法2.1 拼接