From 3e55366434de65e8f1b0ac2729f363a031ed6f6d Mon Sep 17 00:00:00 2001 From: Sascha Willems Date: Sat, 6 Nov 2021 19:45:22 +0100 Subject: [PATCH] Added sample fro dynamic rendering using VK_KHR_dynamic_rendering --- base/vulkanexamplebase.cpp | 5 +- base/vulkanexamplebase.h | 2 +- .../glsl/dynamicrendering/texture.frag | 26 ++ .../glsl/dynamicrendering/texture.frag.spv | Bin 0 -> 1972 bytes .../glsl/dynamicrendering/texture.vert | 33 ++ .../glsl/dynamicrendering/texture.vert.spv | Bin 0 -> 3224 bytes examples/CMakeLists.txt | 1 + .../dynamicrendering/dynamicrendering.cpp | 281 ++++++++++++++++++ 8 files changed, 346 insertions(+), 2 deletions(-) create mode 100644 data/shaders/glsl/dynamicrendering/texture.frag create mode 100644 data/shaders/glsl/dynamicrendering/texture.frag.spv create mode 100644 data/shaders/glsl/dynamicrendering/texture.vert create mode 100644 data/shaders/glsl/dynamicrendering/texture.vert.spv create mode 100644 examples/dynamicrendering/dynamicrendering.cpp diff --git a/base/vulkanexamplebase.cpp b/base/vulkanexamplebase.cpp index 19c51b28..106145a5 100644 --- a/base/vulkanexamplebase.cpp +++ b/base/vulkanexamplebase.cpp @@ -823,7 +823,10 @@ VulkanExampleBase::~VulkanExampleBase() vkDestroyDescriptorPool(device, descriptorPool, nullptr); } destroyCommandBuffers(); - vkDestroyRenderPass(device, renderPass, nullptr); + if (renderPass != VK_NULL_HANDLE) + { + vkDestroyRenderPass(device, renderPass, nullptr); + } for (uint32_t i = 0; i < frameBuffers.size(); i++) { vkDestroyFramebuffer(device, frameBuffers[i], nullptr); diff --git a/base/vulkanexamplebase.h b/base/vulkanexamplebase.h index 6f7e2bf8..14644f6b 100644 --- a/base/vulkanexamplebase.h +++ b/base/vulkanexamplebase.h @@ -153,7 +153,7 @@ protected: // Command buffers used for rendering std::vector drawCmdBuffers; // Global render pass for frame buffer writes - VkRenderPass renderPass; + VkRenderPass renderPass = VK_NULL_HANDLE; // List of available frame buffers (same as number of swap chain images) std::vectorframeBuffers; // Active frame buffer index diff --git a/data/shaders/glsl/dynamicrendering/texture.frag b/data/shaders/glsl/dynamicrendering/texture.frag new file mode 100644 index 00000000..c86d35de --- /dev/null +++ b/data/shaders/glsl/dynamicrendering/texture.frag @@ -0,0 +1,26 @@ +#version 450 + +layout (set = 1, binding = 0) uniform sampler2D samplerColor; + +layout (location = 0) in vec2 inUV; +layout (location = 1) in vec3 inNormal; +layout (location = 2) in vec3 inViewVec; +layout (location = 3) in vec3 inLightVec; + +layout (location = 0) out vec4 outFragColor; + +void main() +{ + vec4 color = texture(samplerColor, inUV); + + vec3 N = normalize(inNormal); + vec3 L = normalize(inLightVec); + vec3 V = normalize(inViewVec); + vec3 R = reflect(-L, N); + vec3 diffuse = max(dot(N, L), 0.0) * vec3(1.0); + float specular = pow(max(dot(R, V), 0.0), 16.0) * color.a; + + outFragColor = vec4(diffuse * color.rgb + specular, 1.0); + + outFragColor = texture(samplerColor, inUV); +} \ No newline at end of file diff --git a/data/shaders/glsl/dynamicrendering/texture.frag.spv b/data/shaders/glsl/dynamicrendering/texture.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..78f2d155dff88159b2ff6e3d00399acbe14bf3c8 GIT binary patch literal 1972 zcmZ9MSyNL%5QRrVA_B6AfQZTsaTntTh$2fwiAzM(GCrq5z+07t%2Gax55D^3FY;IU zVwL9`rmb5J)l8q$-80?OeUs|TopkPm8*~G1#~rV6*C)ogA(!!cvGk#o?{xR_i%WO$ z7;!1@h|j1Z`?VvDO5DUSE;%Q;Ac-U!k}<{LqsyeFbc1uhbU<2cG8TMFwrZ>1YHLp` zhtt|SmBwMc*4_%VkK>-W`LV1`IOV3aQ$t#R+#ff0TJ1)qF4fy-wU@k}_PNE)Qhe~a zTdq})?Q^nm81a$zxLJ;CU%c7J=fu7D_I`I=`(C`i-|N)8|9#=kVXfM$S4dl2#@F5I zb+_A&H6q@@w$Zw~*zB$}yS?TgK-fO7uC23E zl!w;SzS7?_OTK9LmWn?e0}*|jXJfnGDzV(&=qDEKIQ1F^1C86V5o z_~YpMnp6Bzwpo+;#NKJdTi+{4N)NA?|4p=pkY#@HTZsNA!Edu0BR7WT{Y9VJ6wf`y z?p(BcuGrtHT-5z8x=a6$*|nKVe39L`2mTCQd-Nfm$(*zOGTZctK7Bvd?RnPx4dOZt zGS3}EF2p$V`pzPccr)Xu`&V$hA-^l?)_I;gRrh{f=J*$;#%^xkhu`XWPxk2dDzJ9H zMOEx~NPLNS_k+kNa+&PDRq<6$@ZL`#z7^kt{=R`15qYsapG3U>Tf{gMe?M}r;9f4j0@(BQv1Wf4pCJBr?90Bz`bAHd&u}SE{@Sbc-vE2IKGy2{mWx_v(FbdtgOk6V-|Xk;atC>#-p3b+HBBJe ztk*X-k7#o(@HO{+e}%{^F5|2{Vs4^GzKB_XlUH1WF^h1BOft$(d8A_V9d{O##Cpr3YJ$~5fd}H2WKtj);DIdhHkGhlXY}`<(-4yK)LY$ z1zk?;JJ>*cXHon8%*nf=j=%EE3pjJ=XZ|L;oO5omZz0av?|hum&U~EF0m~__I3xVG d;i@(L29{G?;U6`1;moO@HEpuXJ;w6_@*hns#rpsN literal 0 HcmV?d00001 diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index b2db1356..1a4e49c5 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -79,6 +79,7 @@ set(EXAMPLES descriptorsets displacement distancefieldfonts + dynamicrendering dynamicuniformbuffer gears geometryshader diff --git a/examples/dynamicrendering/dynamicrendering.cpp b/examples/dynamicrendering/dynamicrendering.cpp new file mode 100644 index 00000000..d1a01672 --- /dev/null +++ b/examples/dynamicrendering/dynamicrendering.cpp @@ -0,0 +1,281 @@ +/* + * Vulkan Example - Using VK_KHR_dynamic_rendering for rendering without framebuffers and render passes (wip) + * + * Copyright (C) 2021 by Sascha Willems - www.saschawillems.de + * + * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) + */ + +#include "vulkanexamplebase.h" +#include "VulkanglTFModel.h" + +#define ENABLE_VALIDATION false + +class VulkanExample : public VulkanExampleBase +{ +public: + PFN_vkCmdBeginRenderingKHR vkCmdBeginRenderingKHR; + PFN_vkCmdEndRenderingKHR vkCmdEndRenderingKHR; + + VkPhysicalDeviceDynamicRenderingFeaturesKHR dynamicRenderingFeaturesKHR{}; + + vks::Texture2D texture; + vkglTF::Model model; + + struct UniformData { + glm::mat4 projection; + glm::mat4 modelView; + glm::vec4 viewPos; + } uniformData; + vks::Buffer uniformBuffer; + + VkPipeline pipeline; + VkPipelineLayout pipelineLayout; + VkDescriptorSet descriptorSet; + VkDescriptorSetLayout descriptorSetLayout; + + VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) + { + title = "Dynamic rendering"; + camera.type = Camera::CameraType::lookat; + camera.setPosition(glm::vec3(0.0f, 0.0f, -10.0f)); + camera.setRotation(glm::vec3(-7.5f, 72.0f, 0.0f)); + camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 256.0f); + + enabledDeviceExtensions.push_back(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME); + } + + ~VulkanExample() + { + if (device) { + vkDestroyPipeline(device, pipeline, nullptr); + vkDestroyPipelineLayout(device, pipelineLayout, nullptr); + vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); + uniformBuffer.destroy(); + } + } + + void setupRenderPass() + { + // With VK_KHR_dynamic_rendering we no longer need a render pass, so skip the sample base render pass setup + renderPass = VK_NULL_HANDLE; + } + + // Enable physical device features required for this example + virtual void getEnabledFeatures() + { + // Enable anisotropic filtering if supported + if (deviceFeatures.samplerAnisotropy) { + enabledFeatures.samplerAnisotropy = VK_TRUE; + }; + + dynamicRenderingFeaturesKHR.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR; + dynamicRenderingFeaturesKHR.dynamicRendering = VK_TRUE; + + deviceCreatepNextChain = &dynamicRenderingFeaturesKHR; + } + + void loadAssets() + { + const uint32_t glTFLoadingFlags = vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::PreMultiplyVertexColors | vkglTF::FileLoadingFlags::FlipY; + model.loadFromFile(getAssetPath() + "models/voyager.gltf", vulkanDevice, queue, glTFLoadingFlags); + texture.loadFromFile(getAssetPath() + "textures/vulkan_11_rgba.ktx", VK_FORMAT_R8G8B8A8_UNORM, vulkanDevice, queue); + } + + void buildCommandBuffers() + { + VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); + + for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) + { + VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo)); + + // @todo: comment + VkRenderingAttachmentInfoKHR colorAttachment{}; + colorAttachment.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR; + colorAttachment.imageView = swapChain.buffers[i].view; + colorAttachment.imageLayout = VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR; + colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_NONE_KHR; + colorAttachment.clearValue.color = { 0.0f,0.0f,0.0f,0.0f }; + + // A single depth stencil attachment info can be used, but they can also be specified separately. + // When both are specified separately, the only requirement is that the image view is identical. + VkRenderingAttachmentInfoKHR depthStencilAttachment{}; + depthStencilAttachment.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR; + depthStencilAttachment.imageView = depthStencil.view; + depthStencilAttachment.imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL_KHR; + depthStencilAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + depthStencilAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + depthStencilAttachment.clearValue.depthStencil = { 1.0f, 0 }; + + VkRenderingInfoKHR renderingInfo{}; + renderingInfo.sType = VK_STRUCTURE_TYPE_RENDERING_INFO_KHR; + renderingInfo.renderArea = { 0, 0, width, height }; + renderingInfo.layerCount = 1; + renderingInfo.colorAttachmentCount = 1; + renderingInfo.pColorAttachments = &colorAttachment; + renderingInfo.pDepthAttachment = &depthStencilAttachment; + renderingInfo.pStencilAttachment = &depthStencilAttachment; + + // Begin dynamic rendering + vkCmdBeginRenderingKHR(drawCmdBuffers[i], &renderingInfo); + + VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); + vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); + + VkRect2D scissor = vks::initializers::rect2D(width, height, 0, 0); + vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); + + vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, nullptr); + vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + + model.draw(drawCmdBuffers[i], vkglTF::RenderFlags::BindImages, pipelineLayout); + + // End dynamic rendering + vkCmdEndRenderingKHR(drawCmdBuffers[i]); + + VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i])); + } + } + + void draw() + { + VulkanExampleBase::prepareFrame(); + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; + VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); + VulkanExampleBase::submitFrame(); + } + + void setupDescriptorPool() + { + // Example uses one ubo and one image sampler + std::vector poolSizes = { + vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) + }; + VkDescriptorPoolCreateInfo descriptorPoolInfo = + vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); + VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); + } + + void setupDescriptorSetLayout() + { + const std::vector setLayoutBindings = { + // Binding 0 : Vertex shader uniform buffer + vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + }; + VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); + VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); + + // Layout uses set 0 for passing vertex shader ubo and set 1 for fragment shader images (taken from glTF model) + const std::vector setLayouts = { + descriptorSetLayout, + vkglTF::descriptorSetLayoutImage, + }; + VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(setLayouts.data(), 2); + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout)); + } + + void setupDescriptorSet() + { + VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); + std::vector writeDescriptorSets = { + // Binding 0 : Vertex shader uniform buffer + vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffer.descriptor), + }; + vkUpdateDescriptorSets(device, writeDescriptorSets.size(), writeDescriptorSets.data(), 0, nullptr); + } + + void preparePipelines() + { + VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); + VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); + VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); + VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); + VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0); + std::vector dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); + std::array shaderStages{}; + + // We no longer need to set a renderpass for the pipeline create info + VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(); + pipelineCI.layout = pipelineLayout; + pipelineCI.pInputAssemblyState = &inputAssemblyState; + pipelineCI.pRasterizationState = &rasterizationState; + pipelineCI.pColorBlendState = &colorBlendState; + pipelineCI.pMultisampleState = &multisampleState; + pipelineCI.pViewportState = &viewportState; + pipelineCI.pDepthStencilState = &depthStencilState; + pipelineCI.pDynamicState = &dynamicState; + pipelineCI.stageCount = static_cast(shaderStages.size()); + pipelineCI.pStages = shaderStages.data(); + pipelineCI.pVertexInputState = vkglTF::Vertex::getPipelineVertexInputState({ vkglTF::VertexComponent::Position, vkglTF::VertexComponent::Normal, vkglTF::VertexComponent::UV }); + + // New create info to define color, depth and stencil attachments at pipeline create time + VkPipelineRenderingCreateInfoKHR pipelineRenderingCreateInfo{}; + pipelineRenderingCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR; + pipelineRenderingCreateInfo.colorAttachmentCount = 1; + pipelineRenderingCreateInfo.pColorAttachmentFormats = &swapChain.colorFormat; + pipelineRenderingCreateInfo.depthAttachmentFormat = depthFormat; + pipelineRenderingCreateInfo.stencilAttachmentFormat = depthFormat; + // Chain into the pipeline creat einfo + pipelineCI.pNext = &pipelineRenderingCreateInfo; + + shaderStages[0] = loadShader(getShadersPath() + "dynamicrendering/texture.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + shaderStages[1] = loadShader(getShadersPath() + "dynamicrendering/texture.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipeline)); + } + + // Prepare and initialize uniform buffer containing shader uniforms + void prepareUniformBuffers() + { + VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffer, sizeof(uniformData), &uniformData)); + VK_CHECK_RESULT(uniformBuffer.map()); + + updateUniformBuffers(); + } + + void updateUniformBuffers() + { + uniformData.projection = camera.matrices.perspective; + uniformData.modelView = camera.matrices.view; + uniformData.viewPos = camera.viewPos; + memcpy(uniformBuffer.mapped, &uniformData, sizeof(uniformData)); + } + + void prepare() + { + VulkanExampleBase::prepare(); + + vkCmdBeginRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdBeginRenderingKHR")); + vkCmdEndRenderingKHR = reinterpret_cast(vkGetDeviceProcAddr(device, "vkCmdEndRenderingKHR")); + + loadAssets(); + prepareUniformBuffers(); + setupDescriptorSetLayout(); + preparePipelines(); + setupDescriptorPool(); + setupDescriptorSet(); + buildCommandBuffers(); + prepared = true; + } + + virtual void render() + { + if (!prepared) + return; + draw(); + } + + virtual void viewChanged() + { + updateUniformBuffers(); + } +}; + +VULKAN_EXAMPLE_MAIN()