4
社区成员
发帖
与我相关
我的任务
分享#version 450
layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec3 inColor;
layout(location = 0) out vec3 fragColor;
void main() {
gl_Position = vec4(inPosition, 0.0, 1.0);
fragColor = inColor;
}
--------------------------------------------------------------------------------------------------------------------------------
#version 450
layout(location = 0) in vec3 fragColor;
layout(location = 0) out vec4 outColor;
void main() {
outColor = vec4(fragColor, 1.0);
}
--------------------------------------------------------------------------------------------------------------------------------
#define GLFW_INCLUDE_VULKAN // 让GLFW自动包含Vulkan头文件
#include <GLFW/glfw3.h> // GLFW窗口库
#include <glm/glm.hpp> // 数学库(向量/矩阵)
#include <iostream> // 标准输入输出流
#include <fstream> // 文件读写(着色器)
#include <stdexcept> // 标准异常
#include <algorithm> // 算法(如clamp)
#include <vector> // 动态数组
#include <cstring> // 内存操作
#include <cstdlib> // 通用工具
#include <cstdint> // 固定宽度整数类型
#include <limits> // 数值极限
#include <array> // 固定大小数组
#include <optional> // 可选值(C++17)
#include <set> // 集合(去重)
const uint32_t WIDTH = 800; // 窗口宽度
const uint32_t HEIGHT = 600; // 窗口高度
const int MAX_FRAMES_IN_FLIGHT = 2; // 最大飞行帧数(双缓冲)
const std::vector<const char*> validationLayers = { "VK_LAYER_KHRONOS_validation" }; // 启用标准验证层
const std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; // 需要交换链扩展
#ifdef NDEBUG // 如果是Release模式(NDEBUG定义)
const bool enableValidationLayers = false; // 关闭验证层
#else // 否则Debug模式
const bool enableValidationLayers = true; // 开启验证层
#endif
// 创建调试信使(扩展函数)
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) {
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"); // 获取函数指针
if (func != nullptr) { // 如果获取成功
return func(instance, pCreateInfo, pAllocator, pDebugMessenger); // 调用创建
}
else { // 否则
return VK_ERROR_EXTENSION_NOT_PRESENT; // 返回扩展不存在错误
}
}
// 销毁调试信使
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator) {
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT"); // 获取函数指针
if (func != nullptr) { // 如果成功
func(instance, debugMessenger, pAllocator); // 调用销毁
}
}
// 队列族索引结构
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily; // 图形队列族索引(可选)
std::optional<uint32_t> presentFamily; // 呈现队列族索引(可选)
bool isComplete() { // 判断是否都已找到
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
// 交换链支持详情
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities; // 表面能力
std::vector<VkSurfaceFormatKHR> formats; // 支持的格式列表
std::vector<VkPresentModeKHR> presentModes; // 支持的呈现模式列表
};
// 顶点结构体
struct Vertex {
glm::vec2 pos; // 位置(x,y)
glm::vec3 color; // 颜色(r,g,b)
static VkVertexInputBindingDescription getBindingDescription() { // 获取顶点绑定描述
VkVertexInputBindingDescription bindingDescription{}; // 初始化
bindingDescription.binding = 0; // 绑定索引0
bindingDescription.stride = sizeof(Vertex); // 步长=顶点大小
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; // 逐顶点
return bindingDescription;
}
static std::array<VkVertexInputAttributeDescription, 2> getAttributeDescriptions() { // 获取属性描述
std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions{}; // 两个属性
attributeDescriptions[0].binding = 0; // 绑定索引0
attributeDescriptions[0].location = 0; // location=0
attributeDescriptions[0].format = VK_FORMAT_R32G32_SFLOAT; // 两个float(位置)
attributeDescriptions[0].offset = offsetof(Vertex, pos); // 偏移量
attributeDescriptions[1].binding = 0; // 绑定索引0
attributeDescriptions[1].location = 1; // location=1
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; // 三个float(颜色)
attributeDescriptions[1].offset = offsetof(Vertex, color); // 偏移量
return attributeDescriptions;
}
};
// 预定义顶点数据(正方形四个顶点)
const std::vector<Vertex> vertices = {
{{-0.5f, -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}}, // 右上角蓝色
{{-0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}} // 左上角白色
};
// 索引数据(两个三角形构成矩形)
const std::vector<uint16_t> indices = {
0, 1, 2, // 第一个三角形
2, 3, 0 // 第二个三角形
};
// 主应用类
class HelloTriangleApplication {
public:
void run() { // 运行入口
initWindow(); // 初始化窗口
initVulkan(); // 初始化Vulkan
mainLoop(); // 进入主循环
cleanup(); // 清理资源
}
private:
GLFWwindow* window; // GLFW窗口指针
VkInstance instance; // Vulkan实例
VkDebugUtilsMessengerEXT debugMessenger; // 调试信使对象
VkSurfaceKHR surface; // 窗口表面
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; // 物理设备句柄
VkDevice device; // 逻辑设备
VkQueue graphicsQueue; // 图形队列
VkQueue presentQueue; // 呈现队列
VkSwapchainKHR swapChain; // 交换链
std::vector<VkImage> swapChainImages; // 交换链图像
VkFormat swapChainImageFormat; // 图像格式
VkExtent2D swapChainExtent; // 图像尺寸
std::vector<VkImageView> swapChainImageViews; // 图像视图列表
std::vector<VkFramebuffer> swapChainFramebuffers; // 帧缓冲列表
VkRenderPass renderPass; // 渲染过程
VkPipelineLayout pipelineLayout; // 管线布局
VkPipeline graphicsPipeline; // 图形管线
VkCommandPool commandPool; // 命令池
VkBuffer vertexBuffer; // 顶点缓冲
VkDeviceMemory vertexBufferMemory; // 顶点缓冲内存
VkBuffer indexBuffer; // 索引缓冲
VkDeviceMemory indexBufferMemory; // 索引缓冲内存
std::vector<VkCommandBuffer> commandBuffers; // 命令缓冲(每帧一个)
std::vector<VkSemaphore> imageAvailableSemaphores; // 图像可用信号量
std::vector<VkSemaphore> renderFinishedSemaphores; // 渲染完成信号量
std::vector<VkFence> inFlightFences; // 飞行中围栏
uint32_t currentFrame = 0; // 当前帧索引
bool framebufferResized = false; // 帧缓冲尺寸变化标志
void initWindow() { // 初始化GLFW窗口
glfwInit(); // 初始化GLFW库
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // 不创建OpenGL上下文
window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", nullptr, nullptr); // 创建窗口
glfwSetWindowUserPointer(window, this); // 保存this指针到窗口
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback); // 注册尺寸回调
}
static void framebufferResizeCallback(GLFWwindow* window, int width, int height) { // 回调函数
auto app = reinterpret_cast<HelloTriangleApplication*>(glfwGetWindowUserPointer(window)); // 获取应用实例
app->framebufferResized = true; // 标记尺寸变化
}
void initVulkan() { // 初始化Vulkan
createInstance(); // 创建实例
setupDebugMessenger(); // 设置调试信使
createSurface(); // 创建表面
pickPhysicalDevice(); // 选择物理设备
createLogicalDevice(); // 创建设备
createSwapChain(); // 创建交换链
createImageViews(); // 创建图像视图
createRenderPass(); // 创建渲染过程
createGraphicsPipeline(); // 创建图形管线
createFramebuffers(); // 创建帧缓冲
createCommandPool(); // 创建命令池
createVertexBuffer(); // 创建顶点缓冲
createIndexBuffer(); // 创建索引缓冲
createCommandBuffers(); // 创建命令缓冲
createSyncObjects(); // 创建同步对象
}
void mainLoop() { // 主循环
while (!glfwWindowShouldClose(window)) { // 窗口未关闭
glfwPollEvents(); // 处理事件
drawFrame(); // 绘制一帧
}
vkDeviceWaitIdle(device); // 等待设备空闲
}
void cleanupSwapChain() { // 清理交换链相关资源
for (auto framebuffer : swapChainFramebuffers) { // 遍历帧缓冲
vkDestroyFramebuffer(device, framebuffer, nullptr); // 销毁
}
for (auto imageView : swapChainImageViews) { // 遍历图像视图
vkDestroyImageView(device, imageView, nullptr); // 销毁
}
vkDestroySwapchainKHR(device, swapChain, nullptr); // 销毁交换链
}
void cleanup() { // 全部清理
cleanupSwapChain(); // 先清理交换链
vkDestroyPipeline(device, graphicsPipeline, nullptr); // 销毁管线
vkDestroyPipelineLayout(device, pipelineLayout, nullptr); // 销毁管线布局
vkDestroyRenderPass(device, renderPass, nullptr); // 销毁渲染过程
vkDestroyBuffer(device, indexBuffer, nullptr); // 销毁索引缓冲
vkFreeMemory(device, indexBufferMemory, nullptr); // 释放索引缓冲内存
vkDestroyBuffer(device, vertexBuffer, nullptr); // 销毁顶点缓冲
vkFreeMemory(device, vertexBufferMemory, nullptr); // 释放顶点缓冲内存
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { // 遍历所有帧
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr); // 销毁渲染完成信号量
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr); // 销毁图像可用信号量
vkDestroyFence(device, inFlightFences[i], nullptr); // 销毁围栏
}
vkDestroyCommandPool(device, commandPool, nullptr); // 销毁命令池
vkDestroyDevice(device, nullptr); // 销毁逻辑设备
if (enableValidationLayers) { // 如果启用验证层
DestroyDebugUtilsMessengerEXT(instance, debugMessenger, nullptr); // 销毁调试信使
}
vkDestroySurfaceKHR(instance, surface, nullptr); // 销毁表面
vkDestroyInstance(instance, nullptr); // 销毁实例
glfwDestroyWindow(window); // 销毁窗口
glfwTerminate(); // 终止GLFW
}
void recreateSwapChain() { // 重建交换链
int width = 0, height = 0; // 获取当前窗口尺寸
glfwGetFramebufferSize(window, &width, &height);
while (width == 0 || height == 0) { // 若尺寸无效则等待
glfwGetFramebufferSize(window, &width, &height);
glfwWaitEvents();
}
vkDeviceWaitIdle(device); // 等待设备空闲
cleanupSwapChain(); // 清理旧交换链
createSwapChain(); // 重建
createImageViews(); // 重建图像视图
createFramebuffers(); // 重建帧缓冲
}
void createInstance() { // 创建实例
if (enableValidationLayers && !checkValidationLayerSupport()) { // 验证层不可用则抛异常
throw std::runtime_error("validation layers requested, but not available!");
}
VkApplicationInfo appInfo{}; // 应用信息
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; // sType
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; // 使用的Vulkan API版本
VkInstanceCreateInfo createInfo{}; // 实例创建信息
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; // sType
createInfo.pApplicationInfo = &appInfo; // 应用信息指针
auto extensions = getRequiredExtensions(); // 获取所需扩展
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size()); // 扩展数量
createInfo.ppEnabledExtensionNames = extensions.data(); // 扩展名称列表
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo{}; // 调试创建信息
if (enableValidationLayers) { // 如果启用验证层
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); // 层数
createInfo.ppEnabledLayerNames = validationLayers.data(); // 层名称列表
populateDebugMessengerCreateInfo(debugCreateInfo); // 填充调试信息
createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo; // pNext指向调试信息
}
else {
createInfo.enabledLayerCount = 0; // 无验证层
createInfo.ppEnabledLayerNames = nullptr; // 层名称列表为空
createInfo.pNext = nullptr; // pNext为空
}
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { // 创建实例
throw std::runtime_error("failed to create instance!"); // 失败抛异常
}
}
void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT& createInfo) { // 填充调试创建信息
createInfo = {}; // 置零
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; // sType
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; // 消息严重性
createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; // 消息类型
createInfo.pfnUserCallback = debugCallback; // 回调函数
createInfo.pUserData = nullptr; // 用户数据(可选)
}
void setupDebugMessenger() { // 设置调试信使
if (!enableValidationLayers) return; // 未启用则返回
VkDebugUtilsMessengerCreateInfoEXT createInfo; // 创建信息
populateDebugMessengerCreateInfo(createInfo); // 填充
if (CreateDebugUtilsMessengerEXT(instance, &createInfo, nullptr, &debugMessenger) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to set up debug messenger!"); // 失败抛异常
}
}
void createSurface() { // 创建表面
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create window surface!"); // 失败抛异常
}
}
void pickPhysicalDevice() { // 选择物理设备
uint32_t deviceCount = 0; // 设备数量
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); // 获取数量
if (deviceCount == 0) { // 如果没有设备
throw std::runtime_error("failed to find GPUs with Vulkan support!"); // 抛异常
}
std::vector<VkPhysicalDevice> devices(deviceCount); // 设备列表
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data()); // 获取设备
for (const auto& device : devices) { // 遍历所有设备
if (isDeviceSuitable(device)) { // 如果合适
physicalDevice = device; // 选择该设备
break; // 跳出循环
}
}
if (physicalDevice == VK_NULL_HANDLE) { // 如果没有找到合适的设备
throw std::runtime_error("failed to find a suitable GPU!"); // 抛异常
}
}
void createLogicalDevice() { // 创建逻辑设备
QueueFamilyIndices indices = findQueueFamilies(physicalDevice); // 获取队列族索引
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; // 队列创建信息列表
std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() }; // 去重
float queuePriority = 1.0f; // 队列优先级
for (uint32_t queueFamily : uniqueQueueFamilies) { // 遍历每个队列族
VkDeviceQueueCreateInfo queueCreateInfo{}; // 队列创建信息
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; // sType
queueCreateInfo.queueFamilyIndex = queueFamily; // 队列族索引
queueCreateInfo.queueCount = 1; // 队列数量
queueCreateInfo.pQueuePriorities = &queuePriority; // 优先级指针
queueCreateInfos.push_back(queueCreateInfo); // 加入列表
}
VkPhysicalDeviceFeatures deviceFeatures{}; // 不启用特殊特性
VkDeviceCreateInfo createInfo{}; // 设备创建信息
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; // sType
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); // 队列创建信息数量
createInfo.pQueueCreateInfos = queueCreateInfos.data(); // 队列创建信息指针
createInfo.pEnabledFeatures = &deviceFeatures; // 启用特性
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); // 扩展数量
createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // 扩展名称列表
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { // 创建设备
throw std::runtime_error("failed to create logical device!"); // 失败抛异常
}
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); // 获取图形队列
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); // 获取呈现队列
}
void createSwapChain() { // 创建交换链
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice); // 查询支持
VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); // 选择格式
VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); // 选择呈现模式
VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities); // 选择尺寸
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; // 图像数量=最小+1
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
imageCount = swapChainSupport.capabilities.maxImageCount; // 不超过最大
}
VkSwapchainCreateInfoKHR createInfo{}; // 交换链创建信息
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; // sType
createInfo.surface = surface; // 表面
createInfo.minImageCount = imageCount; // 最小图像数
createInfo.imageFormat = surfaceFormat.format; // 图像格式
createInfo.imageColorSpace = surfaceFormat.colorSpace; // 颜色空间
createInfo.imageExtent = extent; // 图像尺寸
createInfo.imageArrayLayers = 1; // 层数1
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // 用作颜色附件
QueueFamilyIndices indices = findQueueFamilies(physicalDevice); // 获取队列族
uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; // 队列族数组
if (indices.graphicsFamily != indices.presentFamily) { // 如果队列族不同
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; // 并发共享
createInfo.queueFamilyIndexCount = 2; // 队列族数量
createInfo.pQueueFamilyIndices = queueFamilyIndices; // 队列族索引列表
}
else {
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // 独占
createInfo.queueFamilyIndexCount = 0; // 队列族数量为0
createInfo.pQueueFamilyIndices = nullptr; // 队列族索引列表为空
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform; // 变换
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; // 复合Alpha
createInfo.presentMode = presentMode; // 呈现模式
createInfo.clipped = VK_TRUE; // 启用裁剪
createInfo.oldSwapchain = VK_NULL_HANDLE; // 无旧交换链
if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create swap chain!"); // 失败抛异常
}
vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr); // 先获取数量
swapChainImages.resize(imageCount); // 调整大小
vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data()); // 获取图像
swapChainImageFormat = surfaceFormat.format; // 保存格式
swapChainExtent = extent; // 保存尺寸
}
void createImageViews() { // 创建图像视图
swapChainImageViews.resize(swapChainImages.size()); // 调整大小
for (size_t i = 0; i < swapChainImages.size(); i++) { // 遍历每个图像
VkImageViewCreateInfo createInfo{}; // 图像视图创建信息
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; // sType
createInfo.image = swapChainImages[i]; // 图像
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; // 视图类型2D
createInfo.format = swapChainImageFormat; // 格式
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; // R分量映射
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; // G分量映射
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; // B分量映射
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; // A分量映射
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // 颜色方面
createInfo.subresourceRange.baseMipLevel = 0; // 基础Mip层级
createInfo.subresourceRange.levelCount = 1; // 层级数量
createInfo.subresourceRange.baseArrayLayer = 0; // 基础数组层
createInfo.subresourceRange.layerCount = 1; // 数组层数量
if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create image views!"); // 失败抛异常
}
}
}
void createRenderPass() { // 创建渲染过程
VkAttachmentDescription colorAttachment{}; // 颜色附件描述
colorAttachment.format = swapChainImageFormat; // 格式
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; // 采样数1
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; // 加载操作:清除
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // 存储操作:存储
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // 模板加载:不关心
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; // 模板存储:不关心
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // 初始布局:未定义
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; // 最终布局:呈现源
VkAttachmentReference colorAttachmentRef{}; // 附件引用
colorAttachmentRef.attachment = 0; // 附件索引0
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; // 布局:颜色附件最优
VkSubpassDescription subpass{}; // 子通道
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; // 图形管线绑定点
subpass.colorAttachmentCount = 1; // 颜色附件数量
subpass.pColorAttachments = &colorAttachmentRef; // 颜色附件指针
subpass.pDepthStencilAttachment = nullptr; // 无深度模板附件
VkSubpassDependency dependency{}; // 子通道依赖
dependency.srcSubpass = VK_SUBPASS_EXTERNAL; // 外部子通道
dependency.dstSubpass = 0; // 目标子通道索引0
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; // 源阶段
dependency.srcAccessMask = 0; // 源访问掩码
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; // 目标阶段
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; // 目标访问掩码
VkRenderPassCreateInfo renderPassInfo{}; // 渲染过程创建信息
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; // sType
renderPassInfo.attachmentCount = 1; // 附件数量
renderPassInfo.pAttachments = &colorAttachment; // 附件指针
renderPassInfo.subpassCount = 1; // 子通道数量
renderPassInfo.pSubpasses = &subpass; // 子通道指针
renderPassInfo.dependencyCount = 1; // 依赖数量
renderPassInfo.pDependencies = &dependency; // 依赖指针
if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create render pass!"); // 失败抛异常
}
}
void createGraphicsPipeline() { // 创建图形管线
auto vertShaderCode = readFile("shaders/18_shader_vertexbuffer.vert.spv"); // 读取顶点着色器
auto fragShaderCode = readFile("shaders/18_shader_vertexbuffer.frag.spv"); // 读取片段着色器
VkShaderModule vertShaderModule = createShaderModule(vertShaderCode); // 创建顶点着色器模块
VkShaderModule fragShaderModule = createShaderModule(fragShaderCode); // 创建片段着色器模块
VkPipelineShaderStageCreateInfo vertShaderStageInfo{}; // 顶点着色器阶段
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; // sType
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT; // 阶段类型:顶点
vertShaderStageInfo.module = vertShaderModule; // 着色器模块
vertShaderStageInfo.pName = "main"; // 入口函数名
vertShaderStageInfo.pSpecializationInfo = nullptr; // 无特化信息
VkPipelineShaderStageCreateInfo fragShaderStageInfo{}; // 片段着色器阶段
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; // sType
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT; // 阶段类型:片段
fragShaderStageInfo.module = fragShaderModule; // 着色器模块
fragShaderStageInfo.pName = "main"; // 入口函数名
fragShaderStageInfo.pSpecializationInfo = nullptr; // 无特化信息
VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo }; // 阶段数组
VkPipelineVertexInputStateCreateInfo vertexInputInfo{}; // 顶点输入
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; // sType
auto bindingDescription = Vertex::getBindingDescription(); // 绑定描述
auto attributeDescriptions = Vertex::getAttributeDescriptions(); // 属性描述
vertexInputInfo.vertexBindingDescriptionCount = 1; // 绑定描述数量
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()); // 属性描述数量
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; // 绑定描述指针
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); // 属性描述指针
VkPipelineInputAssemblyStateCreateInfo inputAssembly{}; // 输入装配
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; // sType
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // 三角形列表
inputAssembly.primitiveRestartEnable = VK_FALSE; // 禁止图元重启
VkPipelineViewportStateCreateInfo viewportState{}; // 视口状态
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; // sType
viewportState.viewportCount = 1; // 视口数量
viewportState.scissorCount = 1; // 裁剪矩形数量
VkPipelineRasterizationStateCreateInfo rasterizer{}; // 光栅化
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; // sType
rasterizer.depthClampEnable = VK_FALSE; // 禁用深度钳位
rasterizer.rasterizerDiscardEnable = VK_FALSE; // 不禁用光栅化
rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // 填充模式
rasterizer.lineWidth = 1.0f; // 线宽1.0
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; // 剔除背面
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; // 顺时针为正面
rasterizer.depthBiasEnable = VK_FALSE; // 禁用深度偏移
rasterizer.depthBiasConstantFactor = 0.0f; // 深度偏移常量因子
rasterizer.depthBiasClamp = 0.0f; // 深度偏移钳位
rasterizer.depthBiasSlopeFactor = 0.0f; // 深度偏移斜率因子
VkPipelineMultisampleStateCreateInfo multisampling{}; // 多重采样
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; // sType
multisampling.sampleShadingEnable = VK_FALSE; // 禁用采样着色
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; // 采样数1
multisampling.minSampleShading = 1.0f; // 最小采样着色
multisampling.pSampleMask = nullptr; // 无采样掩码
VkPipelineColorBlendAttachmentState colorBlendAttachment{}; // 颜色混合附件
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; // 写入所有通道
colorBlendAttachment.blendEnable = VK_FALSE; // 禁用混合
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // 源颜色因子
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // 目标颜色因子
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD; // 颜色混合操作
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // 源Alpha因子
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // 目标Alpha因子
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD; // Alpha混合操作
VkPipelineColorBlendStateCreateInfo colorBlending{}; // 颜色混合状态
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; // sType
colorBlending.logicOpEnable = VK_FALSE; // 禁用逻辑操作
colorBlending.logicOp = VK_LOGIC_OP_COPY; // 逻辑操作:复制
colorBlending.attachmentCount = 1; // 附件数量
colorBlending.pAttachments = &colorBlendAttachment; // 附件指针
colorBlending.blendConstants[0] = 0.0f; // 混合常量R
colorBlending.blendConstants[1] = 0.0f; // 混合常量G
colorBlending.blendConstants[2] = 0.0f; // 混合常量B
colorBlending.blendConstants[3] = 0.0f; // 混合常量A
std::vector<VkDynamicState> dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; // 动态状态列表
VkPipelineDynamicStateCreateInfo dynamicState{}; // 动态状态
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; // sType
dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size()); // 动态状态数量
dynamicState.pDynamicStates = dynamicStates.data(); // 动态状态列表
VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; // 管线布局
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; // sType
pipelineLayoutInfo.setLayoutCount = 0; // 无描述符集
pipelineLayoutInfo.pSetLayouts = nullptr; // 无描述符集布局
pipelineLayoutInfo.pushConstantRangeCount = 0; // 无推送常量
pipelineLayoutInfo.pPushConstantRanges = nullptr; // 无推送常量范围
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create pipeline layout!"); // 失败抛异常
}
VkGraphicsPipelineCreateInfo pipelineInfo{}; // 图形管线创建信息
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; // sType
pipelineInfo.stageCount = 2; // 着色器阶段数量
pipelineInfo.pStages = shaderStages; // 阶段数组指针
pipelineInfo.pVertexInputState = &vertexInputInfo; // 顶点输入状态
pipelineInfo.pInputAssemblyState = &inputAssembly; // 输入装配状态
pipelineInfo.pViewportState = &viewportState; // 视口状态
pipelineInfo.pRasterizationState = &rasterizer; // 光栅化状态
pipelineInfo.pMultisampleState = &multisampling; // 多重采样状态
pipelineInfo.pDepthStencilState = nullptr; // 无深度模板状态
pipelineInfo.pColorBlendState = &colorBlending; // 颜色混合状态
pipelineInfo.pDynamicState = &dynamicState; // 动态状态
pipelineInfo.layout = pipelineLayout; // 管线布局
pipelineInfo.renderPass = renderPass; // 渲染过程
pipelineInfo.subpass = 0; // 子通道索引0
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE; // 无基础管线
pipelineInfo.basePipelineIndex = -1; // 基础管线索引
if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create graphics pipeline!"); // 失败抛异常
}
vkDestroyShaderModule(device, fragShaderModule, nullptr); // 销毁片段着色器模块
vkDestroyShaderModule(device, vertShaderModule, nullptr); // 销毁顶点着色器模块
}
void createFramebuffers() { // 创建帧缓冲
swapChainFramebuffers.resize(swapChainImageViews.size()); // 调整大小
for (size_t i = 0; i < swapChainImageViews.size(); i++) { // 遍历每个图像视图
VkImageView attachments[] = { swapChainImageViews[i] }; // 附件数组
VkFramebufferCreateInfo framebufferInfo{}; // 帧缓冲创建信息
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; // sType
framebufferInfo.renderPass = renderPass; // 渲染过程
framebufferInfo.attachmentCount = 1; // 附件数量
framebufferInfo.pAttachments = attachments; // 附件数组
framebufferInfo.width = swapChainExtent.width; // 宽度
framebufferInfo.height = swapChainExtent.height; // 高度
framebufferInfo.layers = 1; // 层数1
if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create framebuffer!"); // 失败抛异常
}
}
}
void createCommandPool() { // 创建命令池
QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice); // 获取队列族
VkCommandPoolCreateInfo poolInfo{}; // 命令池创建信息
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; // sType
poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; // 允许单独重置命令缓冲
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); // 图形队列族
if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create graphics command pool!"); // 失败抛异常
}
}
void createVertexBuffer() { // 创建顶点缓冲区
VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); // 缓冲大小
VkBuffer stagingBuffer; // 暂存缓冲
VkDeviceMemory stagingBufferMemory; // 暂存缓冲内存
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); // 创建暂存缓冲
void* data; // 数据指针
vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); // 映射内存
memcpy(data, vertices.data(), (size_t)bufferSize); // 拷贝顶点数据
vkUnmapMemory(device, stagingBufferMemory); // 取消映射
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); // 创建顶点缓冲
copyBuffer(stagingBuffer, vertexBuffer, bufferSize); // 复制数据
vkDestroyBuffer(device, stagingBuffer, nullptr); // 销毁暂存缓冲
vkFreeMemory(device, stagingBufferMemory, nullptr); // 释放暂存缓冲内存
}
void createIndexBuffer() { // 创建索引缓冲区
VkDeviceSize bufferSize = sizeof(indices[0]) * indices.size(); // 缓冲大小
VkBuffer stagingBuffer; // 暂存缓冲
VkDeviceMemory stagingBufferMemory; // 暂存缓冲内存
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); // 创建暂存缓冲
void* data; // 数据指针
vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); // 映射内存
memcpy(data, indices.data(), (size_t)bufferSize); // 拷贝索引数据
vkUnmapMemory(device, stagingBufferMemory); // 取消映射
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); // 创建索引缓冲
copyBuffer(stagingBuffer, indexBuffer, bufferSize); // 复制数据
vkDestroyBuffer(device, stagingBuffer, nullptr); // 销毁暂存缓冲
vkFreeMemory(device, stagingBufferMemory, nullptr); // 释放暂存缓冲内存
}
void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { // 创建缓冲
VkBufferCreateInfo bufferInfo{}; // 缓冲创建信息
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; // sType
bufferInfo.size = size; // 大小
bufferInfo.usage = usage; // 用途
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // 独占模式
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create buffer!"); // 失败抛异常
}
VkMemoryRequirements memRequirements; // 内存需求
vkGetBufferMemoryRequirements(device, buffer, &memRequirements); // 获取内存需求
VkMemoryAllocateInfo allocInfo{}; // 内存分配信息
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; // sType
allocInfo.allocationSize = memRequirements.size; // 分配大小
allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties); // 内存类型索引
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { // 分配内存
throw std::runtime_error("failed to allocate buffer memory!"); // 失败抛异常
}
vkBindBufferMemory(device, buffer, bufferMemory, 0); // 绑定内存
}
void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { // 复制缓冲
VkCommandBufferAllocateInfo allocInfo{}; // 命令缓冲分配信息
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; // sType
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; // 主命令缓冲
allocInfo.commandPool = commandPool; // 命令池
allocInfo.commandBufferCount = 1; // 数量1
VkCommandBuffer commandBuffer; // 命令缓冲
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); // 分配
VkCommandBufferBeginInfo beginInfo{}; // 开始信息
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; // sType
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; // 一次性提交
vkBeginCommandBuffer(commandBuffer, &beginInfo); // 开始记录
VkBufferCopy copyRegion{}; // 复制区域
copyRegion.size = size; // 大小
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region); // 复制命令
vkEndCommandBuffer(commandBuffer); // 结束记录
VkSubmitInfo submitInfo{}; // 提交信息
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; // sType
submitInfo.commandBufferCount = 1; // 命令缓冲数量
submitInfo.pCommandBuffers = &commandBuffer; // 命令缓冲指针
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); // 提交
vkQueueWaitIdle(graphicsQueue); // 等待队列空闲
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); // 释放命令缓冲
}
uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties) { // 查找内存类型
VkPhysicalDeviceMemoryProperties memProperties; // 内存属性
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); // 获取
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { // 遍历
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { // 匹配
return i; // 返回索引
}
}
throw std::runtime_error("failed to find suitable memory type!"); // 未找到抛异常
}
void createCommandBuffers() { // 创建命令缓冲
commandBuffers.resize(MAX_FRAMES_IN_FLIGHT); // 调整大小
VkCommandBufferAllocateInfo allocInfo{}; // 分配信息
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; // sType
allocInfo.commandPool = commandPool; // 命令池
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; // 主命令缓冲
allocInfo.commandBufferCount = (uint32_t)commandBuffers.size(); // 数量
if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { // 分配
throw std::runtime_error("failed to allocate command buffers!"); // 失败抛异常
}
}
void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex) { // 记录命令缓冲
VkCommandBufferBeginInfo beginInfo{}; // 开始信息
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; // sType
if (vkBeginCommandBuffer(commandBuffer, &beginInfo) != VK_SUCCESS) { // 开始记录
throw std::runtime_error("failed to begin recording command buffer!"); // 失败抛异常
}
VkRenderPassBeginInfo renderPassInfo{}; // 渲染过程开始信息
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; // sType
renderPassInfo.renderPass = renderPass; // 渲染过程
renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex]; // 帧缓冲
renderPassInfo.renderArea.offset = { 0, 0 }; // 偏移(0,0)
renderPassInfo.renderArea.extent = swapChainExtent; // 尺寸
VkClearValue clearColor = { {{0.0f, 0.0f, 0.0f, 1.0f}} }; // 清除颜色黑色
renderPassInfo.clearValueCount = 1; // 清除值数量
renderPassInfo.pClearValues = &clearColor; // 清除值指针
vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); // 开始渲染过程
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline); // 绑定管线
VkViewport viewport{}; // 视口
viewport.x = 0.0f; // x起始
viewport.y = 0.0f; // y起始
viewport.width = (float)swapChainExtent.width; // 宽度
viewport.height = (float)swapChainExtent.height; // 高度
viewport.minDepth = 0.0f; // 最小深度
viewport.maxDepth = 1.0f; // 最大深度
vkCmdSetViewport(commandBuffer, 0, 1, &viewport); // 设置视口
VkRect2D scissor{}; // 裁剪矩形
scissor.offset = { 0, 0 }; // 偏移(0,0)
scissor.extent = swapChainExtent; // 尺寸
vkCmdSetScissor(commandBuffer, 0, 1, &scissor); // 设置裁剪矩形
VkBuffer vertexBuffers[] = { vertexBuffer }; // 顶点缓冲数组
VkDeviceSize offsets[] = { 0 }; // 偏移数组
vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets); // 绑定顶点缓冲
vkCmdBindIndexBuffer(commandBuffer, indexBuffer, 0, VK_INDEX_TYPE_UINT16); // 绑定索引缓冲
vkCmdDrawIndexed(commandBuffer, static_cast<uint32_t>(indices.size()), 1, 0, 0, 0); // 绘制索引
vkCmdEndRenderPass(commandBuffer); // 结束渲染过程
if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) { // 结束记录
throw std::runtime_error("failed to record command buffer!"); // 失败抛异常
}
}
void createSyncObjects() { // 创建同步对象
imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT); // 调整大小
renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT); // 调整大小
inFlightFences.resize(MAX_FRAMES_IN_FLIGHT); // 调整大小
VkSemaphoreCreateInfo semaphoreInfo{}; // 信号量创建信息
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; // sType
VkFenceCreateInfo fenceInfo{}; // 围栏创建信息
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; // sType
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; // 初始为有信号状态
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) { // 遍历
if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || // 创建图像可用信号量
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || // 创建渲染完成信号量
vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { // 创建围栏
throw std::runtime_error("failed to create synchronization objects for a frame!"); // 失败抛异常
}
}
}
void drawFrame() { // 绘制一帧
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); // 等待当前帧围栏
uint32_t imageIndex; // 图像索引
VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); // 获取下一张图像
if (result == VK_ERROR_OUT_OF_DATE_KHR) { // 如果交换链过时
recreateSwapChain(); // 重建
return; // 返回
}
else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) { // 其他错误
throw std::runtime_error("failed to acquire swap chain image!"); // 抛异常
}
vkResetFences(device, 1, &inFlightFences[currentFrame]); // 重置围栏
vkResetCommandBuffer(commandBuffers[currentFrame], /*VkCommandBufferResetFlagBits*/ 0); // 重置命令缓冲
recordCommandBuffer(commandBuffers[currentFrame], imageIndex); // 记录命令缓冲
VkSubmitInfo submitInfo{}; // 提交信息
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; // sType
VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] }; // 等待信号量
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; // 等待阶段
submitInfo.waitSemaphoreCount = 1; // 等待信号量数量
submitInfo.pWaitSemaphores = waitSemaphores; // 等待信号量指针
submitInfo.pWaitDstStageMask = waitStages; // 等待阶段指针
submitInfo.commandBufferCount = 1; // 命令缓冲数量
submitInfo.pCommandBuffers = &commandBuffers[currentFrame]; // 命令缓冲指针
VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] }; // 信号信号量
submitInfo.signalSemaphoreCount = 1; // 信号信号量数量
submitInfo.pSignalSemaphores = signalSemaphores; // 信号信号量指针
if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) { // 提交
throw std::runtime_error("failed to submit draw command buffer!"); // 失败抛异常
}
VkPresentInfoKHR presentInfo{}; // 呈现信息
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; // sType
presentInfo.waitSemaphoreCount = 1; // 等待信号量数量
presentInfo.pWaitSemaphores = signalSemaphores; // 等待信号量指针
VkSwapchainKHR swapChains[] = { swapChain }; // 交换链数组
presentInfo.swapchainCount = 1; // 交换链数量
presentInfo.pSwapchains = swapChains; // 交换链指针
presentInfo.pImageIndices = &imageIndex; // 图像索引指针
result = vkQueuePresentKHR(presentQueue, &presentInfo); // 呈现
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) { // 需要重建
framebufferResized = false; // 重置标志
recreateSwapChain(); // 重建
}
else if (result != VK_SUCCESS) { // 其他错误
throw std::runtime_error("failed to present swap chain image!"); // 抛异常
}
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT; // 更新当前帧
}
VkShaderModule createShaderModule(const std::vector<char>& code) { // 创建着色器模块
VkShaderModuleCreateInfo createInfo{}; // 创建信息
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; // sType
createInfo.codeSize = code.size(); // 代码大小
createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data()); // 代码指针
VkShaderModule shaderModule; // 着色器模块
if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) { // 创建
throw std::runtime_error("failed to create shader module!"); // 失败抛异常
}
return shaderModule; // 返回模块
}
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { // 选择表面格式
for (const auto& availableFormat : availableFormats) { // 遍历
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { // 首选
return availableFormat; // 返回
}
}
return availableFormats[0]; // 返回第一个
}
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { // 选择呈现模式
for (const auto& availablePresentMode : availablePresentModes) { // 遍历
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { // 首选MAILBOX
return availablePresentMode; // 返回
}
}
return VK_PRESENT_MODE_FIFO_KHR; // 否则FIFO
}
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) { // 选择交换链尺寸
if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) { // 如果已有尺寸
return capabilities.currentExtent; // 直接返回
}
else {
int width, height; // 窗口尺寸
glfwGetFramebufferSize(window, &width, &height); // 获取
VkExtent2D actualExtent = { // 实际尺寸
static_cast<uint32_t>(width),
static_cast<uint32_t>(height)
};
actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width); // 限制宽度
actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height); // 限制高度
return actualExtent; // 返回
}
}
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) { // 查询交换链支持
SwapChainSupportDetails details; // 详情
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // 获取能力
uint32_t formatCount; // 格式数量
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); // 获取数量
if (formatCount != 0) { // 如果有格式
details.formats.resize(formatCount); // 调整大小
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); // 获取格式
}
uint32_t presentModeCount; // 呈现模式数量
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); // 获取数量
if (presentModeCount != 0) { // 如果有模式
details.presentModes.resize(presentModeCount); // 调整大小
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); // 获取模式
}
return details; // 返回详情
}
bool isDeviceSuitable(VkPhysicalDevice device) { // 判断设备是否合适
QueueFamilyIndices indices = findQueueFamilies(device); // 获取队列族
bool extensionsSupported = checkDeviceExtensionSupport(device); // 检查扩展
bool swapChainAdequate = false; // 交换链是否足够
if (extensionsSupported) { // 如果扩展支持
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device); // 查询交换链
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); // 非空
}
return indices.isComplete() && extensionsSupported && swapChainAdequate; // 返回
}
bool checkDeviceExtensionSupport(VkPhysicalDevice device) { // 检查设备扩展支持
uint32_t extensionCount; // 扩展数量
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr); // 获取数量
std::vector<VkExtensionProperties> availableExtensions(extensionCount); // 可用扩展列表
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data()); // 获取
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); // 所需扩展集合
for (const auto& extension : availableExtensions) { // 遍历
requiredExtensions.erase(extension.extensionName); // 移除已支持的
}
return requiredExtensions.empty(); // 全部支持则返回true
}
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device) { // 查找队列族
QueueFamilyIndices indices; // 索引
uint32_t queueFamilyCount = 0; // 队列族数量
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr); // 获取数量
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); // 队列族属性
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data()); // 获取
int i = 0; // 计数器
for (const auto& queueFamily : queueFamilies) { // 遍历
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { // 支持图形
indices.graphicsFamily = i; // 设置图形索引
}
VkBool32 presentSupport = false; // 呈现支持
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport); // 检查
if (presentSupport) { // 支持呈现
indices.presentFamily = i; // 设置呈现索引
}
if (indices.isComplete()) { // 如果都找到
break; // 跳出
}
i++; // 递增
}
return indices; // 返回
}
std::vector<const char*> getRequiredExtensions() { // 获取所需扩展
uint32_t glfwExtensionCount = 0; // GLFW扩展数量
const char** glfwExtensions; // GLFW扩展列表
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); // 获取
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); // 复制
if (enableValidationLayers) { // 如果启用验证层
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); // 添加调试扩展
}
return extensions; // 返回
}
bool checkValidationLayerSupport() { // 检查验证层支持
uint32_t layerCount; // 层数量
vkEnumerateInstanceLayerProperties(&layerCount, nullptr); // 获取数量
std::vector<VkLayerProperties> availableLayers(layerCount); // 可用层
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); // 获取
for (const char* layerName : validationLayers) { // 遍历所需层
bool layerFound = false; // 是否找到
for (const auto& layerProperties : availableLayers) { // 遍历可用层
if (strcmp(layerName, layerProperties.layerName) == 0) { // 比较
layerFound = true; // 找到
break; // 跳出内层循环
}
}
if (!layerFound) { // 未找到
return false; // 返回false
}
}
return true; // 全部找到
}
static std::vector<char> readFile(const std::string& filename) { // 读取文件
std::ifstream file(filename, std::ios::ate | std::ios::binary); // 打开文件
if (!file.is_open()) { // 如果打开失败
throw std::runtime_error("failed to open file!"); // 抛异常
}
size_t fileSize = (size_t)file.tellg(); // 文件大小
std::vector<char> buffer(fileSize); // 缓冲
file.seekg(0); // 移动到开头
file.read(buffer.data(), fileSize); // 读取
file.close(); // 关闭
return buffer; // 返回
}
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { // 调试回调
std::cerr << "validation layer: " << pCallbackData->pMessage << std::endl; // 输出
return VK_FALSE; // 返回false
}
};
int main() { // 主函数
HelloTriangleApplication app; // 创建应用实例
try { // 尝试
app.run(); // 运行应用
} // 结束try
catch (const std::exception& e) { // 捕获异常
std::cerr << e.what() << std::endl; // 输出错误信息
return EXIT_FAILURE; // 返回失败
} // 结束catch
return EXIT_SUCCESS; // 返回成功
} // 结束main