8.4 实例化
vkCmdDraw() and vkCmdDrawIndexed()的两个参数我们已经粗略的讲解过了。它们是firstInstance and instanceCount,用来控制实例化的。这是一种技术,一个几何对象的很多份复制可以发送到图形管线。每一份复制都被称为一个实例。首先,这看似没有什么用,但是有两种方式可以让你的应用程序在几何物体的每一份实例上做一些改变:
• Use the InstanceIndex built-in decoration on a vertex shader inputto receive the index of
the current instance as an input to theshader. This input variable can then be used to fetch
parameters from a uniform buffer orprogrammatically compute per-instance variation, for
example.
• Use instanced vertex attributes to have Vulkan feed your vertexshader with unique data for
each instance
Listing 8.4展示了通过GLSL内置的变量gl_InstanceIndex来使用实例索引的例子。这个例子使用实例化绘制了许多不同的立方体,立方体的每一个实例都有不同的颜色和形变。每一个立方体实例的形变矩阵和颜色都存储在一对union缓冲区中。着色器然后可以通过内置变量gl_InstanceIndex来索引这个数组。这个着色器渲染的结果在Figure8.3展示。
Listing8.4: Using the Instance Index in a Shader
#version450 core
layout (set = 0, binding = 0) uniform matrix_uniforms_b
{
mat4 mvp_matrix[1024];
};
layout (set = 0, binding = 1) uniform color_uniforms_b
{
vec4 cube_colors[1024];
};
layout (location = 0) in vec3 i_position;
out vs_fs
{
flat vec4 color;
};
void main(void)
{
float f = float(gl_VertexIndex / 6) / 6.0f;
vec4 color1 = cube_colors[gl_InstanceIndex];
vec4 color2 = cube_colors[gl_InstanceIndex & 512];
color = mix(color1, color2, f);
gl_Position = mvp_matrix[gl_InstanceIndex] * vec4(i_position, 1.0f);
}
Figure 8.3: Many Instanced Cubes