vulkan 绘制三角形
时间: 2023-09-20 22:04:33 浏览: 103
要使用Vulkan绘制一个三角形,需要经过以下步骤:
1. 创建一个Vulkan实例
2. 创建一个逻辑设备
3. 创建一个窗口表面
4. 创建一个交换链
5. 创建渲染通道和帧缓冲区
6. 创建着色器模块
7. 创建管线布局和管线
8. 分配顶点缓冲区
9. 开始绘制
下面是一个简单的示例代码,用于绘制一个三角形:
```
// 顶点数据
std::vector<Vertex> vertices = {
{ { 0.0f, -0.5f },{ 1.0f, 0.0f, 0.0f } },
{ { 0.5f, 0.5f },{ 0.0f, 1.0f, 0.0f } },
{ { -0.5f, 0.5f },{ 0.0f, 0.0f, 1.0f } }
};
// 创建顶点缓冲区
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
createBuffer(sizeof(vertices[0]) * vertices.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, vertexBuffer, vertexBufferMemory);
// 在CPU上填充顶点缓冲区
void* data;
vkMapMemory(device, vertexBufferMemory, 0, sizeof(vertices[0]) * vertices.size(), 0, &data);
memcpy(data, vertices.data(), sizeof(vertices[0]) * vertices.size());
vkUnmapMemory(device, vertexBufferMemory);
// 创建渲染通道和帧缓冲区
VkRenderPass renderPass;
createRenderPass(renderPass);
VkFramebuffer framebuffer;
createFramebuffer(framebuffer);
// 创建着色器模块
VkShaderModule vertShaderModule;
VkShaderModule fragShaderModule;
createShaderModule("vert.spv", vertShaderModule);
createShaderModule("frag.spv", fragShaderModule);
// 创建管线布局和管线
VkPipelineLayout pipelineLayout;
VkPipeline pipeline;
createPipelineLayout(pipelineLayout);
createPipeline(pipeline, pipelineLayout, renderPass, vertShaderModule, fragShaderModule);
// 开始绘制
VkCommandBuffer commandBuffer = beginSingleTimeCommands();
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
VkRenderPassBeginInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffer;
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
VkBuffer vertexBuffers[] = { vertexBuffer };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets);
vkCmdDraw(commandBuffer, 3, 1, 0, 0);
vkCmdEndRenderPass(commandBuffer);
endSingleTimeCommands(commandBuffer);
```
这段代码中,我们首先创建一个包含三个顶点的顶点缓冲区,然后使用着色器模块、管线布局和管线来定义如何渲染这些顶点。最后,我们通过调用`vkCmdDraw`函数来绘制三角形。
阅读全文