8. 着色器
一个着色器指定了在图形和计算管线对应各阶段的每个顶点、控制点、细分顶点、图元、片元或者工作组 上执行的可编程的操作。
图形管线包括作为primitive assembly结果的顶点着色器执行, 紧接着是在patches之上的 细分控制、求值着色器(如果开启了)操作,作用在图元之上的几何着色器(如果开启了), 操作于 Rasterization产生的片元之上的片元着色器。 在本规范中,顶细分控制、细分求值、几何着色器都是指顶点处理阶段,发生在逻辑管线中栅格化之前。 片元着色器程序在栅格化之后运行。
只有计算着色器阶段被包含在计算管线中。计算着色器操作一个工作组中的一些调用。
着色器可以从输入变量中读取,从输出变量中读取或者写入。 输入和输出变量可以被用来在不同着色器阶段之间转移数据,或者允许着色器和执行环境中变量值直接交互。 同样的,执行环境也提供了描述性能的常量。
着色器变量和执行环境提供的着色器内部_built-in_修饰的输入和输出变量相关。 对于每个阶段可用的修饰符在下面小节中列出。
8.1. 着色器模块
Shader modules 包含 shader code 和一个或多个入口点。 可通过指定一个入口点作为创建pipeline的一部分来从着色器模块中选择着色器。 管线的阶段可以使用来自不同模块的着色器。定义了一个着色器模块的着色器代码必须是SPIR-V格式, 在附录 Vulkan Environment for SPIR-V 有描述。
着色器模块通过VkShaderModule
handles表示:
VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkShaderModule)
可调用如下命令来创建着色器模块:
VkResult vkCreateShaderModule(
VkDevice device,
const VkShaderModuleCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkShaderModule* pShaderModule);
-
device
是创建着色器模块的逻辑设备。 -
pCreateInfo
参数是一个指针,指向了一个VkShaderModuleCreateInfo
类型的数据结构实例。 -
pAllocator
控制了主机端内存如何分配,如Memory Allocation一章所述。 -
pShaderModule
指向了一个VkShaderModule
handle ,它接收返回的着色器模块。
一旦着色器模块被创建完成,它所包含的入口点在Compute Pipelines 和 Graphics Pipelines中描述的管线阶段。
VkShaderModuleCreateInfo
数据结构定义如下:
typedef struct VkShaderModuleCreateInfo {
VkStructureType sType;
const void* pNext;
VkShaderModuleCreateFlags flags;
size_t codeSize;
const uint32_t* pCode;
} VkShaderModuleCreateInfo;
-
sType
是数据结构的类型 -
pNext
是NULL
或者指向一个指向拓展特定的数据结构的指针 -
flags
被保留 -
codeSize
是pCode
指明的代码的大小,以字节为单位 -
pCode
指向了将用来创建着色器模块的代码。代码的类型和格式由pCode
所指向的内存内容所决定
可调用如下命令来销毁着色器模块:
void vkDestroyShaderModule(
VkDevice device,
VkShaderModule shaderModule,
const VkAllocationCallbacks* pAllocator);
-
device
是销毁着色器模块的逻辑设备 -
shaderModule
是需要被销毁的着色器模块 -
pAllocator
控制了CPU端内存分配,如 Memory Allocation 一章所述
一个着色器模块可以在使用它的着色器的管线仍在使用中的时候被销毁。