diff --git a/homework/homework1/homework1.cpp b/homework/homework1/homework1.cpp index fc848b5..869031c 100644 --- a/homework/homework1/homework1.cpp +++ b/homework/homework1/homework1.cpp @@ -16,12 +16,8 @@ * * If you are looking for a complete glTF implementation, check out https://github.com/SaschaWillems/Vulkan-glTF-PBR/ */ - - #include "homework1.h" - - /* glTF loading functions @@ -30,6 +26,8 @@ void VulkanglTFModel::loadImages(tinygltf::Model& input) { + // Images can be stored inside the glTF (which is the case for the sample model), so instead of directly + // loading them from disk, we fetch them from the glTF loader and upload the buffers images.resize(input.images.size()); for (size_t i = 0; i < input.images.size(); i++) { tinygltf::Image& glTFImage = input.images[i]; @@ -70,6 +68,95 @@ } } + void VulkanglTFModel::loadAnimations(tinygltf::Model& input) + { + animations.resize(input.animations.size()); + + for (size_t i = 0; i < input.animations.size(); ++i) + { + auto glTFAnimation = input.animations[i]; + animations[i].name = glTFAnimation.name; + + //Samplers + animations[i].samplers.resize(glTFAnimation.samplers.size()); + for (size_t j = 0; j < glTFAnimation.samplers.size(); ++j) + { + auto glTFSampler = glTFAnimation.samplers[j]; + auto& dstSampler = animations[i].samplers[j]; + dstSampler.interpolation = glTFSampler.interpolation; + + // Read sampler keyframe input time values + { + const auto& accessor = input.accessors[glTFSampler.input]; + const auto& bufferView = input.bufferViews[accessor.bufferView]; + const auto& buffer = input.buffers[bufferView.buffer]; + const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset]; + const float* buf = static_cast(dataPtr); + for (size_t index = 0; index < accessor.count; ++index) + { + dstSampler.inputs.push_back(buf[index]); + } + // Adjust animation's start and end times + for (auto input : animations[i].samplers[j].inputs) + { + if (input < animations[i].start) + { + animations[i].start = input; + }; + if (input > animations[i].end) + { + animations[i].end = input; + } + } + } + + // Read sampler keyframe output translate/rotate/scale values + { + const auto& accessor = input.accessors[glTFSampler.output]; + const auto& bufferView = input.bufferViews[accessor.bufferView]; + const auto& buffer = input.buffers[bufferView.buffer]; + const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset]; + switch (accessor.type) + { + case TINYGLTF_TYPE_VEC3: + { + const glm::vec3* buf = static_cast(dataPtr); + for (size_t index = 0; index < accessor.count; index++) + { + dstSampler.outputsVec4.push_back(glm::vec4(buf[index], 0.0f)); + } + break; + } + case TINYGLTF_TYPE_VEC4: + { + const glm::vec4* buf = static_cast(dataPtr); + for (size_t index = 0; index < accessor.count; index++) + { + dstSampler.outputsVec4.push_back(buf[index]); + } + break; + } + default: + { + std::cout << "unknown type" << std::endl; + break; + } + } + } + } + + animations[i].channels.resize(glTFAnimation.channels.size()); + for (size_t j = 0; j < glTFAnimation.channels.size(); ++j) + { + auto glTFChannel = glTFAnimation.channels[j]; + auto& dstChannel = animations[i].channels[j]; + dstChannel.path = glTFChannel.target_path; + dstChannel.samplerIndex = glTFChannel.sampler; + dstChannel.node = nodeFromIndex(glTFChannel.target_node); + } + } + } + void VulkanglTFModel::loadMaterials(tinygltf::Model& input) { materials.resize(input.materials.size()); @@ -99,193 +186,15 @@ { materials[i].materialData.values.emissiveFactor = glm::make_vec3(glTFMaterial.emissiveFactor.data()); } - + if (glTFMaterial.values.find("baseColorFactor") != glTFMaterial.values.end()) { materials[i].materialData.values.baseColorFactor = glm::make_vec4(glTFMaterial.values["baseColorFactor"].ColorFactor().data()); } } } - - - //animation loader - void VulkanglTFModel::loadAnimations(tinygltf::Model& input) - { - animations.resize(input.animations.size()); - for (size_t i = 0; i < input.animations.size(); i++) - { - tinygltf::Animation glTFAnimation = input.animations[i]; - animations[i].name = glTFAnimation.name; - - // Samplers - animations[i].samplers.resize(glTFAnimation.samplers.size()); - for (size_t j = 0; j < glTFAnimation.samplers.size(); j++) - { - tinygltf::AnimationSampler glTFSampler = glTFAnimation.samplers[j]; - AnimationSampler& dstSampler = animations[i].samplers[j]; - dstSampler.interpolation = glTFSampler.interpolation; - - // Read sampler keyframe input time values - { - const tinygltf::Accessor& accessor = input.accessors[glTFSampler.input]; - const tinygltf::BufferView& bufferView = input.bufferViews[accessor.bufferView]; - const tinygltf::Buffer& buffer = input.buffers[bufferView.buffer]; - const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset]; - const float* buf = static_cast(dataPtr); - for (size_t index = 0; index < accessor.count; index++) - { - dstSampler.inputs.push_back(buf[index]); - } - // Adjust animation's start and end times - for (auto input : animations[i].samplers[j].inputs) - { - if (input < animations[i].start) - { - animations[i].start = input; - }; - if (input > animations[i].end) - { - animations[i].end = input; - } - } - } - - // Read sampler keyframe output translate/rotate/scale values - { - const tinygltf::Accessor& accessor = input.accessors[glTFSampler.output]; - const tinygltf::BufferView& bufferView = input.bufferViews[accessor.bufferView]; - const tinygltf::Buffer& buffer = input.buffers[bufferView.buffer]; - const void* dataPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset]; - switch (accessor.type) - { - case TINYGLTF_TYPE_VEC3: { - const glm::vec3* buf = static_cast(dataPtr); - for (size_t index = 0; index < accessor.count; index++) - { - dstSampler.outputsVec4.push_back(glm::vec4(buf[index], 0.0f)); - } - break; - } - case TINYGLTF_TYPE_VEC4: { - const glm::vec4* buf = static_cast(dataPtr); - for (size_t index = 0; index < accessor.count; index++) - { - dstSampler.outputsVec4.push_back(buf[index]); - } - break; - } - default: { - std::cout << "unknown type" << std::endl; - break; - } - } - } - } - - // Channels - animations[i].channels.resize(glTFAnimation.channels.size()); - for (size_t j = 0; j < glTFAnimation.channels.size(); j++) - { - tinygltf::AnimationChannel glTFChannel = glTFAnimation.channels[j]; - AnimationChannel& dstChannel = animations[i].channels[j]; - dstChannel.path = glTFChannel.target_path; - dstChannel.samplerIndex = glTFChannel.sampler; - dstChannel.node = nodeFromIndex(glTFChannel.target_node); - } - } - - - } - /* - // load skins from glTF model - void VulkanglTFModel::loadSkins(tinygltf::Model& input) - { - - skins.resize(input.skins.size()); - if (skins.size() > 0) - { - for (size_t i = 0; i < input.skins.size(); i++) - { - tinygltf::Skin glTFSkin = input.skins[i]; - - skins[i].name = glTFSkin.name; - //follow the tree structure,find the root node of skeleton by index - skins[i].skeletonRoot = nodeFromIndex(glTFSkin.skeleton); - - //join nodes - for (int jointIndex : glTFSkin.joints) - { - Node* node = nodeFromIndex(jointIndex); - if (node) - { - skins[i].joints.push_back(node); - } - } - //get the inverse bind matrices - if (glTFSkin.inverseBindMatrices > -1) - { - const tinygltf::Accessor& accessor = input.accessors[glTFSkin.inverseBindMatrices]; - const tinygltf::BufferView& bufferview = input.bufferViews[accessor.bufferView]; - const tinygltf::Buffer& buffer = input.buffers[bufferview.buffer]; - skins[i].inverseBindMatrices.resize(accessor.count); - memcpy(skins[i].inverseBindMatrices.data(), &buffer.data[accessor.byteOffset + bufferview.byteOffset], accessor.count * sizeof(glm::mat4)); - - //create a host visible shader buffer to store inverse bind matrices for this skin - VK_CHECK_RESULT( - vulkanDevice->createBuffer( - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - &skins[i].ssbo, - sizeof(glm::mat4) * skins[i].inverseBindMatrices.size(), - skins[i].inverseBindMatrices.data())); - VK_CHECK_RESULT(skins[i].ssbo.map()); - } - } - - } - - - - }*/ - - //glTF nodes loading helper function - //rewrite node loader,simplify logic - //Search node from parent to children by index - VulkanglTFModel::Node* VulkanglTFModel::findNode(Node* parent, uint32_t index) - { - Node* nodeFound = nullptr; - if (parent->index == index) - { - return parent; - } - for (auto& child : parent->children) - { - nodeFound = findNode(child, index); - if (nodeFound) - { - break; - } - } - return nodeFound; - } //iterate vector of nodes to check weather nodes exist or not - VulkanglTFModel::Node* VulkanglTFModel::nodeFromIndex(uint32_t index) - { - Node* nodeFound = nullptr; - for (auto& node : nodes) - { - nodeFound = findNode(node, index); - if (nodeFound) - { - break; - } - } - return nodeFound; - } - - - //node loader - void VulkanglTFModel::loadNode(const tinygltf::Node& inputNode, const tinygltf::Model& input, VulkanglTFModel::Node* parent, uint32_t nodeIndex, std::vector& indexBuffer, std::vector& vertexBuffer) + void VulkanglTFModel::loadNode(const tinygltf::Node& inputNode, const tinygltf::Model& input, VulkanglTFModel::Node* parent, uint32_t nodeIndex,std::vector& indexBuffer, std::vector& vertexBuffer) { VulkanglTFModel::Node* node = new VulkanglTFModel::Node{}; node->matrix = glm::mat4(1.0f); @@ -311,7 +220,7 @@ // Load node's children if (inputNode.children.size() > 0) { for (size_t i = 0; i < inputNode.children.size(); i++) { - loadNode(input.nodes[inputNode.children[i]], input, node, inputNode.children[i], indexBuffer, vertexBuffer); + loadNode(input.nodes[inputNode.children[i]], input , node, inputNode.children[i],indexBuffer, vertexBuffer); } } @@ -424,63 +333,41 @@ } } - - /* - vertex skinning functions - */ - glm::mat4 VulkanglTFModel::getNodeMatrix(VulkanglTFModel::Node* node) + VulkanglTFModel::Node* VulkanglTFModel::findNode(Node* parent, uint32_t index) { - glm::mat4 nodeMatrix = node->getLocalMatrix(); - VulkanglTFModel::Node* currentParent = node->parent; - while (currentParent) + Node* nodeFound = nullptr; + if (parent->index == index) { - nodeMatrix = currentParent->getLocalMatrix() * nodeMatrix; - currentParent = currentParent->parent; + return parent; } - return nodeMatrix; - } - - void VulkanglTFModel::updateNodeMatrix(Node* node, std::vector& nodeMatrics) - { - if (node->skin <= -1) + for (auto& child : parent->children) { - nodeMatrics[node->index] = getNodeMatrix(node); - for (auto& child : node->children) + nodeFound = findNode(child, index); + if (nodeFound) { - updateNodeMatrix(child, nodeMatrics); + break; } } - + return nodeFound; } - void VulkanglTFModel::updateJoints(VulkanglTFModel::Node* node) + VulkanglTFModel::Node* VulkanglTFModel::nodeFromIndex(uint32_t index) { - if (node->skin > -1) + Node* nodeFound = nullptr; + for (auto& node : nodes) { - glm::mat4 inversTransform = glm::inverse(getNodeMatrix(node)); - Skin skin = skins[node->skin]; - size_t numJoints = (uint32_t)skin.joints.size(); - std::vector jointMatrices(numJoints); - for (size_t i = 0; i < numJoints; i++) + nodeFound = findNode(node, index); + if (nodeFound) { - jointMatrices[i] = getNodeMatrix(skin.joints[i]) * skin.inverseBindMatrices[i]; - jointMatrices[i] = inversTransform * jointMatrices[i]; + break; } - skin.ssbo.copyTo(jointMatrices.data(), jointMatrices.size() * sizeof(glm::mat4)); - } - for (auto& child : node->children) - { - updateJoints(child); } + return nodeFound; } - void VulkanglTFModel::updateAnimation(float deltaTime,vks::Buffer buffer) + void VulkanglTFModel::updateAnimation(float deltaTime, vks::Buffer& buffer) { - if (activeAnimation > static_cast(animations.size()) - 1) - { - std::cout << "No animation with index " << activeAnimation << std::endl; - return; - } + constexpr uint32_t activeAnimation = 0; Animation& animation = animations[activeAnimation]; animation.currentTime += deltaTime; if (animation.currentTime > animation.end) @@ -490,7 +377,7 @@ for (auto& channel : animation.channels) { - AnimationSampler& sampler = animation.samplers[channel.samplerIndex]; + auto& sampler = animation.samplers[channel.samplerIndex]; for (size_t i = 0; i < sampler.inputs.size() - 1; ++i) { if (sampler.interpolation != "LINEAR") @@ -498,8 +385,6 @@ std::cout << "This sample only supports linear interpolations\n"; continue; } - - // Get the input keyframe values for the current time stamp if ((animation.currentTime >= sampler.inputs[i]) && (animation.currentTime <= sampler.inputs[i + 1])) { float ratio = (animation.currentTime - sampler.inputs[i]) / (sampler.inputs[i + 1] - sampler.inputs[i]); @@ -533,48 +418,67 @@ } } } - //if no skin in model , update node matrix to update animation stage std::vector nodeMatrics(nodeCount); for (auto& node : nodes) { - //updateJoints(node); updateNodeMatrix(node, nodeMatrics); } buffer.copyTo(nodeMatrics.data(), nodeCount * sizeof(glm::mat4)); - } + + void VulkanglTFModel::updateNodeMatrix(Node* node, std::vector& nodeMatrics) + { + nodeMatrics[node->index] = getNodeMatrix(node); + for (auto& child : node->children) + { + updateNodeMatrix(child, nodeMatrics); + } + } + + glm::mat4 VulkanglTFModel::getNodeMatrix(Node* node) + { + glm::mat4 nodeMatrix = node->getLocalMatrix(); + Node* currentParent = node->parent; + while (currentParent) + { + nodeMatrix = currentParent->getLocalMatrix() * nodeMatrix; + currentParent = currentParent->parent; + } + return nodeMatrix; + } + /* glTF rendering functions */ // Draw a single node including child nodes (if present) - void VulkanglTFModel::drawNode(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout, VulkanglTFModel::Node node) + void VulkanglTFModel::drawNode(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout, VulkanglTFModel::Node* node, bool bPushConstants) { - if (node.mesh.primitives.size() > 0) { + if (node->mesh.primitives.size() > 0) { // Pass the node's matrix via push constants // Traverse the node hierarchy to the top-most parent to get the final matrix of the current node - glm::mat4 nodeMatrix = node.matrix; - VulkanglTFModel::Node* currentParent = node.parent; + glm::mat4 nodeMatrix = node->matrix; + VulkanglTFModel::Node* currentParent = node->parent; while (currentParent) { nodeMatrix = currentParent->matrix * nodeMatrix; currentParent = currentParent->parent; } - - for (VulkanglTFModel::Primitive& primitive : node.mesh.primitives) { + + for (VulkanglTFModel::Primitive& primitive : node->mesh.primitives) { if (primitive.indexCount > 0) { // Get the texture index for this primitive if (textures.size() > 0) { VulkanglTFModel::Texture texture = textures[materials[primitive.materialIndex].baseColorTextureIndex]; - VulkanglTFModel::Texture normalMap = textures[materials[primitive.materialIndex].normalMapTextureIndex]; - VulkanglTFModel::Texture roughMetalMap = textures[materials[primitive.materialIndex].matalicRoughTextureIndex]; - + auto normalMap = textures[materials[primitive.materialIndex].normalMapTextureIndex]; + auto roughMetalMap = textures[materials[primitive.materialIndex].matalicRoughTextureIndex]; + if (materials[primitive.materialIndex].emissiveTextureIndex >= 0) { - VulkanglTFModel::Texture emissiveMap = textures[materials[primitive.materialIndex].emissiveTextureIndex]; + auto emissiveMap = textures[materials[primitive.materialIndex].emissiveTextureIndex]; vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 4, 1, &images[emissiveMap.imageIndex].descriptorSet, 0, nullptr); } - + // Bind the descriptor for the current primitive's texture vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 1, 1, &images[texture.imageIndex].descriptorSet, 0, nullptr); vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 2, 1, &images[normalMap.imageIndex].descriptorSet, 0, nullptr); @@ -585,13 +489,13 @@ } } } - for (auto &child : node.children) { - drawNode(commandBuffer, pipelineLayout, *child); + for (auto& child : node->children) { + drawNode(commandBuffer, pipelineLayout, child, bPushConstants); } } // Draw the glTF scene starting at the top-level-nodes - void VulkanglTFModel::draw(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout ) + void VulkanglTFModel::draw(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout, bool flag = true) { // All vertices and indices are stored in single buffers, so we only need to bind once VkDeviceSize offsets[1] = { 0 }; @@ -599,15 +503,16 @@ vkCmdBindIndexBuffer(commandBuffer, indices.buffer, 0, VK_INDEX_TYPE_UINT32); // Render all nodes at top-level for (auto& node : nodes) { - drawNode(commandBuffer, pipelineLayout, *node); + drawNode(commandBuffer, pipelineLayout, node, flag); } } -VulkanExample::VulkanExample(): - VulkanExampleBase(ENABLE_VALIDATION) + + VulkanExample::VulkanExample(): + VulkanExampleBase(ENABLE_VALIDATION) { title = "homework1"; camera.type = Camera::CameraType::lookat; @@ -617,121 +522,125 @@ VulkanExample::VulkanExample(): camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 256.0f); } -void VulkanExample::setupFrameBuffer() -{ - VulkanExampleBase::setupFrameBuffer(); - if (pbrFrameBuffer.bCreate && (pbrFrameBuffer.fbo.width != width || pbrFrameBuffer.fbo.height != height)) + void VulkanExample::getEnabledFeatures() { - pbrFrameBuffer.color.destroy(device); - pbrFrameBuffer.depth.destroy(device); - pbrFrameBuffer.fbo.destroy(device); - vkDestroySampler(device, colorSampler, nullptr); + // Fill mode non solid is required for wireframe display + if (deviceFeatures.fillModeNonSolid) { + enabledFeatures.fillModeNonSolid = VK_TRUE; + }; } - pbrFrameBuffer.fbo.setSize(width, height); - VkFormat attachDepthFormat; - VkBool32 validDepthFormat = vks::tools::getSupportedDepthFormat(physicalDevice, &attachDepthFormat); - assert(validDepthFormat); - - VulkanExample::createAttachment(VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, &pbrFrameBuffer.color, width, height); - VulkanExample::createAttachment(attachDepthFormat, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, &pbrFrameBuffer.depth, width, height); - - - std::array attachs = {}; - for (uint32_t i = 0; i < static_cast(attachs.size()); i++) + void VulkanExample::setupFrameBuffer() { - attachs[i].samples = VK_SAMPLE_COUNT_1_BIT; - attachs[i].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachs[i].storeOp = VK_ATTACHMENT_STORE_OP_STORE; - attachs[i].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachs[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachs[i].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - attachs[i].finalLayout = 1 ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL; + VulkanExampleBase::setupFrameBuffer(); + if (pbrFrameBuffer.bCreate && (pbrFrameBuffer.fbo.width != width || pbrFrameBuffer.fbo.height != height)) + { + pbrFrameBuffer.color.destroy(device); + pbrFrameBuffer.depth.destroy(device); + pbrFrameBuffer.fbo.destroy(device); + vkDestroySampler(device, colorSampler, nullptr); + } + + //Create image color attachment + pbrFrameBuffer.fbo.setSize(width, height); + VkFormat attDepthFormat; + VkBool32 validDepthFormat = vks::tools::getSupportedDepthFormat(physicalDevice, &attDepthFormat); + assert(validDepthFormat); + + createAttachment(VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, &pbrFrameBuffer.color, width, height); + createAttachment(attDepthFormat, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, &pbrFrameBuffer.depth, width, height); + { + std::array attachs = {}; + for (uint32_t i = 0; i < static_cast(attachs.size()); ++i) + { + attachs[i].samples = VK_SAMPLE_COUNT_1_BIT; + attachs[i].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachs[i].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachs[i].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachs[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attachs[i].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachs[i].finalLayout = i == 1 ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + } + attachs[0].format = pbrFrameBuffer.color.format; + attachs[1].format = pbrFrameBuffer.depth.format; + + VkAttachmentReference colorReference = {}; + colorReference.attachment = 0; + colorReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + + VkAttachmentReference depthReference = {}; + depthReference.attachment = 1; + depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + + VkSubpassDescription subpass = {}; + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.pColorAttachments = &colorReference; + subpass.colorAttachmentCount = 1; + subpass.pDepthStencilAttachment = &depthReference; + + std::array dependencies; + //To test src 0 + dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; + dependencies[0].dstSubpass = 0; + dependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; + dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT; + dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; + + dependencies[1].srcSubpass = 0; + dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; + dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; + dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + dependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; + + VkRenderPassCreateInfo renderPassCI = {}; + renderPassCI.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + renderPassCI.pAttachments = attachs.data(); + renderPassCI.attachmentCount = static_cast(attachs.size()); + renderPassCI.pSubpasses = &subpass; + renderPassCI.subpassCount = 1; + renderPassCI.pDependencies = dependencies.data(); + renderPassCI.dependencyCount = 2; + VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &pbrFrameBuffer.fbo.renderPass)); + + //Create FBO + VkImageView attachments[2] = { pbrFrameBuffer.color.imageView, pbrFrameBuffer.depth.imageView }; + VkFramebufferCreateInfo fbufCreateInfo = vks::initializers::framebufferCreateInfo(); + fbufCreateInfo.renderPass = pbrFrameBuffer.fbo.renderPass; + fbufCreateInfo.pAttachments = attachments; + fbufCreateInfo.attachmentCount = 2; + fbufCreateInfo.width = pbrFrameBuffer.fbo.width; + fbufCreateInfo.height = pbrFrameBuffer.fbo.height; + fbufCreateInfo.layers = 1; + VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &pbrFrameBuffer.fbo.frameBuffer)); + } + + //Create Image sampler + VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo(); + samplerCI.magFilter = VK_FILTER_NEAREST; + samplerCI.minFilter = VK_FILTER_NEAREST; + samplerCI.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + samplerCI.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samplerCI.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + samplerCI.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + //samplerCI.mipLodBias = 0.0f; + //samplerCI.maxAnisotropy = 1.0f; + samplerCI.minLod = 0.0f; + samplerCI.maxLod = 1.0f; + samplerCI.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; + VK_CHECK_RESULT(vkCreateSampler(device, &samplerCI, nullptr, &colorSampler)); + + if (tonemappingDescriptorSet != VK_NULL_HANDLE) //Bad logic + { + auto imageInfo = vks::initializers::descriptorImageInfo(colorSampler, pbrFrameBuffer.color.imageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(tonemappingDescriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &imageInfo); + vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); + } + pbrFrameBuffer.bCreate = true; } - attachs[0].format = pbrFrameBuffer.color.format; - attachs[1].format = pbrFrameBuffer.depth.format; - - - VkAttachmentReference colorRefference = {}; - colorRefference.attachment = 0; - colorRefference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - - VkAttachmentReference depthRefference = {}; - colorRefference.attachment = 1; - colorRefference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - - VkSubpassDescription subpass = {}; - subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpass.pColorAttachments = &colorRefference; - subpass.colorAttachmentCount = 1; - subpass.pDepthStencilAttachment = &depthRefference; - - std::array dependencies; - //To test src 0 - dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; - dependencies[0].dstSubpass = 0; - dependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT; - dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - - dependencies[1].srcSubpass = 0; - dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; - dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - dependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - - VkRenderPassCreateInfo renderPassCI = {}; - renderPassCI.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; - renderPassCI.pAttachments = attachs.data(); - renderPassCI.attachmentCount = static_cast(attachs.size()); - renderPassCI.pSubpasses = &subpass; - renderPassCI.pDependencies = dependencies.data(); - renderPassCI.dependencyCount = 2; - VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &pbrFrameBuffer.fbo.renderPass)); - // FBO - VkImageView attachments[2] = { pbrFrameBuffer.color.imageView,pbrFrameBuffer.depth.imageView }; - VkFramebufferCreateInfo frameBufferCreateInfo = vks::initializers::framebufferCreateInfo(); - frameBufferCreateInfo.renderPass = pbrFrameBuffer.fbo.renderPass; - frameBufferCreateInfo.pAttachments = attachments; - frameBufferCreateInfo.attachmentCount = 2; - frameBufferCreateInfo.width = pbrFrameBuffer.fbo.width; - frameBufferCreateInfo.height = pbrFrameBuffer.fbo.height; - frameBufferCreateInfo.layers = 1; - VK_CHECK_RESULT(vkCreateFramebuffer(device, &frameBufferCreateInfo, nullptr, &pbrFrameBuffer.fbo.frameBuffer)); - - VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo(); - samplerCI.magFilter = VK_FILTER_NEAREST; - samplerCI.minFilter = VK_FILTER_NEAREST; - samplerCI.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; - samplerCI.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerCI.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerCI.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - - samplerCI.minLod = 0.0f; - samplerCI.maxLod = 1.0f; - samplerCI.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; - VK_CHECK_RESULT(vkCreateSampler(device, &samplerCI, nullptr, &colorSampler)); - if (tonemappingDescriptorSet != VK_NULL_HANDLE) - { - auto imageInfo = vks::initializers::descriptorImageInfo(colorSampler, pbrFrameBuffer.color.imageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(tonemappingDescriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &imageInfo); - vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); - - } - pbrFrameBuffer.bCreate = true; -} - -void VulkanExample::getEnabledFeatures() -{ - // Fill mode non solid is required for wireframe display - if (deviceFeatures.fillModeNonSolid) { - enabledFeatures.fillModeNonSolid = VK_TRUE; - }; -} void VulkanExample::buildCommandBuffers() { @@ -790,7 +699,7 @@ void VulkanExample::getEnabledFeatures() } } - void VulkanExample::loadglTFFile(std::string filename, VulkanglTFModel& model, bool bSkyboxFlag) + void VulkanExample::loadglTFFile(std::string filename, VulkanglTFModel& model, bool bSkyboxFlag = false) { tinygltf::Model glTFInput; tinygltf::TinyGLTF gltfContext; @@ -837,6 +746,11 @@ void VulkanExample::getEnabledFeatures() size_t indexBufferSize = indexBuffer.size() * sizeof(uint32_t); model.indices.count = static_cast(indexBuffer.size()); + struct StagingBuffer { + VkBuffer buffer; + VkDeviceMemory memory; + } vertexStaging, indexStaging; + // Create host visible staging buffers (source) VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_TRANSFER_SRC_BIT, @@ -899,10 +813,9 @@ void VulkanExample::getEnabledFeatures() void VulkanExample::loadAssets() { - loadglTFFile(getAssetPath() + "buster_drone/busterDrone.gltf",glTFModel); + loadglTFFile(getAssetPath() + "buster_drone/busterDrone.gltf", glTFModel); loadglTFFile(getAssetPath() + "models/cube.gltf", skyboxModel, true); ibltextures.skyboxCube.loadFromFile(getAssetPath() + "textures/hdr/pisa_cube.ktx", VK_FORMAT_R16G16B16A16_SFLOAT, vulkanDevice, queue); - } void VulkanExample::setupDescriptors() @@ -910,26 +823,24 @@ void VulkanExample::getEnabledFeatures() /* This sample uses separate descriptor sets (and layouts) for the matrices and materials (textures) */ + //Descriptor Pool Alloc + { + std::vector poolSizes = { + vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), + // One combined image sampler per model image/texture + vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast(glTFModel.images.size())), + vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 4), // Add aditional sampler descriptor + vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1) + }; + // One set for matrices and one per model image/texture + const uint32_t maxSetCount = static_cast(glTFModel.images.size()) + 6; + VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, maxSetCount); + VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); + } - std::vector poolSizes = { - vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), - // One combined image sampler per material image/texture - vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast(glTFModel.images.size())), - // One ssbo per skin - //vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, static_cast(glTFModel.skins.size())), - // sampler descriptor - vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,4), - //animation storage buffer - vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1) - }; - // One set for matrices and one per model image/texture - const uint32_t maxSetCount = static_cast(glTFModel.images.size()) + 6; - VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, maxSetCount); - VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); - - // Descriptor set layouts - std::vector setLayoutBindings = + // Descriptor set layout for passing matrices ---and precompute texture add in this descriptor + std::vector setLayoutBindings = { vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), @@ -950,75 +861,69 @@ void VulkanExample::getEnabledFeatures() setLayoutBinding = vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorSetLayoutCI, nullptr, &descriptorSetLayouts.ssbo)); - // Descriptor set layout for passing skin joint matrices - - //setLayoutBinding = vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0); - //VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorSetLayoutCI, nullptr, &descriptorSetLayouts.jointMatrices)); - - // The pipeline layout uses three sets: - // Set 0 = Scene matrices (VS) - // Set 1 = Joint matrices (VS) - // Set 2 = Material texture (FS) - std::array setLayouts = { - descriptorSetLayouts.matrices, - descriptorSetLayouts.textures, - descriptorSetLayouts.textures, - descriptorSetLayouts.textures, - descriptorSetLayouts.textures, - descriptorSetLayouts.materialUniform, - descriptorSetLayouts.ssbo, - }; - VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(setLayouts.data(), static_cast(setLayouts.size())); - VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelineLayouts.pbrLayout)); - // Descriptor set for scene matrices - VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.matrices, 1); - VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); - std::vector writeDescriptorSets = + //Pbr pipeline layout { - vks::initializers::writeDescriptorSet(descriptorSet,VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,0,&shaderData.buffer.descriptor), - vks::initializers::writeDescriptorSet(descriptorSet,VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,1,&ibltextures.irradianceCube.descriptor), - vks::initializers::writeDescriptorSet(descriptorSet,VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,2,&ibltextures.lutBrdf.descriptor), - vks::initializers::writeDescriptorSet(descriptorSet,VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,3,&ibltextures.prefilteredCube.descriptor), - }; + // Pipeline layout using both descriptor sets (set 0 = matrices, set 1 = material) + std::array setLayouts = + { descriptorSetLayouts.matrices, + descriptorSetLayouts.textures, + descriptorSetLayouts.textures, + descriptorSetLayouts.textures, + descriptorSetLayouts.textures, + descriptorSetLayouts.materialUniform, + descriptorSetLayouts.ssbo + }; + VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(setLayouts.data(), static_cast(setLayouts.size())); + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelineLayouts.pbrLayout)); - vkUpdateDescriptorSets(device, 4, writeDescriptorSets.data(), 0, nullptr); - - for (auto& material : glTFModel.materials) - { - const VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.materialUniform, 1); - VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &material.materialData.descriptorSet)); - VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet( - material.materialData.descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &material.materialData.buffer.descriptor); - vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); + // Descriptor set for scene matrices + VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.matrices, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); + std::vector writeDescriptorSets = + { + vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &shaderData.buffer.descriptor), + vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &ibltextures.irradianceCube.descriptor), + vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &ibltextures.lutBrdf.descriptor), + vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3, &ibltextures.prefilteredCube.descriptor), + }; + vkUpdateDescriptorSets(device, 4, writeDescriptorSets.data(), 0, nullptr); + + for (auto& material : glTFModel.materials) + { + const VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.materialUniform, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &material.materialData.descriptorSet)); + VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet( + material.materialData.descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &material.materialData.buffer.descriptor); + vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); + } + + // Descriptor sets for materials + for (auto& image : glTFModel.images) { + const VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.textures, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &image.descriptorSet)); + VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(image.descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &image.texture.descriptor); + vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); + } + { + const VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.ssbo, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &skinDescriptorSet)); + VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(skinDescriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, &shaderData.skinSSBO.descriptor); + vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); + } } + //Tone Mapping pipeline layout + { + auto pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayouts.textures, 1); + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelineLayouts.tonemappingLayout)); - // Descriptor sets for materials - for (auto& image : glTFModel.images) { const VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.textures, 1); - VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &image.descriptorSet)); - VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(image.descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &image.texture.descriptor); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &tonemappingDescriptorSet)); + + auto imageInfo = vks::initializers::descriptorImageInfo(colorSampler, pbrFrameBuffer.color.imageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(tonemappingDescriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &imageInfo); vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); } - { - const VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.ssbo, 1); - VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &skinDescriptorSet)); - VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(skinDescriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, &shaderData.skinSSBO.descriptor); - vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); - } - - //Tone Mapping pipeline layout - { - auto pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayouts.textures, 1); - VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelineLayouts.tonemappingLayout)); - const VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.textures, 1); - VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &tonemappingDescriptorSet)); - - auto imageInfo = vks::initializers::descriptorImageInfo(colorSampler, pbrFrameBuffer.color.imageView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(tonemappingDescriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &imageInfo); - vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); - } - } void VulkanExample::preparePipelines() @@ -1076,10 +981,10 @@ void VulkanExample::getEnabledFeatures() VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.wireframe)); } //Create Tone Mapping render pipeline - prepareToneMappingPipeline(); + CreateToneMappingPipeline(); } - void VulkanExample::prepareToneMappingPipeline() + void VulkanExample::CreateToneMappingPipeline() { if (pipelines.toneMapping != VK_NULL_HANDLE) { @@ -1087,16 +992,17 @@ void VulkanExample::getEnabledFeatures() pipelines.toneMapping = VK_NULL_HANDLE; } VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCI = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterizationStateCI = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineRasterizationStateCreateInfo rasterizationStateCI = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentStateCI = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendStateCI = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentStateCI); - VkPipelineDepthStencilStateCreateInfo depthStencilStateCI = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); + VkPipelineDepthStencilStateCreateInfo depthStencilStateCI = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportStateCI = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleStateCI = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0); const std::vector dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicStateCI = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables.data(), static_cast(dynamicStateEnables.size()), 0); VkPipelineVertexInputStateCreateInfo emptyInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); + const std::string fragPath = ToneMapping ? "homework1/tonemapping_enable.frag.spv" : "homework1/tonemapping_disable.frag.spv"; std::array shaderStages = { loadShader(getHomeworkShadersPath() + "homework1/genbrdflut.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), @@ -1118,55 +1024,10 @@ void VulkanExample::getEnabledFeatures() VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.toneMapping)); } - // Prepare and initialize uniform buffer containing shader uniforms - void VulkanExample::prepareUniformBuffers() - { - // Vertex shader uniform buffer block - VK_CHECK_RESULT(vulkanDevice->createBuffer( - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - &shaderData.buffer, - sizeof(shaderData.values))); - VK_CHECK_RESULT(vulkanDevice->createBuffer( - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - &shaderData.skinSSBO, - sizeof(glm::mat4) * glTFModel.nodeCount)); - // Map persistent - VK_CHECK_RESULT(shaderData.buffer.map()); - VK_CHECK_RESULT(shaderData.skinSSBO.map()); - - for (auto& material : glTFModel.materials) - { - VK_CHECK_RESULT(vulkanDevice->createBuffer( - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - &material.materialData.buffer, - sizeof(VulkanglTFModel::MaterialData::Values), - &material.materialData.values - )); - - } - - - - updateUniformBuffers(); - } - - void VulkanExample::updateUniformBuffers() - { - shaderData.values.projection = camera.matrices.perspective; - shaderData.values.model = camera.matrices.view; - shaderData.values.viewPos = camera.viewPos; - shaderData.values.bFlagSet.x = normalMapping; - shaderData.values.bFlagSet.y = pbrEnabled; - - memcpy(shaderData.buffer.mapped, &shaderData.values, sizeof(shaderData.values)); - } - -// --------- BRDF LUT precompute preparation ---------------- - void VulkanExample::generateIrradianceCubemap() + //----------------------------Prepare precompute Lighting or BRDF LUT-----------------------------------------------// + //Irradiance map for diffuse lighting + void VulkanExample::GenerateIrradianceCubemap() { auto tStart = std::chrono::high_resolution_clock::now(); @@ -1187,8 +1048,6 @@ void VulkanExample::getEnabledFeatures() imageCI.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; imageCI.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; VK_CHECK_RESULT(vkCreateImage(device, &imageCI, nullptr, &ibltextures.irradianceCube.image)) - - // allocate memory for irradiance cube map VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; vkGetImageMemoryRequirements(device, ibltextures.irradianceCube.image, &memReqs); @@ -1196,8 +1055,6 @@ void VulkanExample::getEnabledFeatures() memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &ibltextures.irradianceCube.deviceMemory)) VK_CHECK_RESULT(vkBindImageMemory(device, ibltextures.irradianceCube.image, ibltextures.irradianceCube.deviceMemory, 0)) - - VkImageViewCreateInfo viewCI = vks::initializers::imageViewCreateInfo(); viewCI.viewType = VK_IMAGE_VIEW_TYPE_CUBE; viewCI.format = format; @@ -1208,7 +1065,6 @@ void VulkanExample::getEnabledFeatures() viewCI.image = ibltextures.irradianceCube.image; VK_CHECK_RESULT(vkCreateImageView(device, &viewCI, nullptr, &ibltextures.irradianceCube.view)) - // set up sampler and image view VkSamplerCreateInfo samplerCI = vks::initializers::samplerCreateInfo(); samplerCI.magFilter = VK_FILTER_LINEAR; samplerCI.minFilter = VK_FILTER_LINEAR; @@ -1226,18 +1082,17 @@ void VulkanExample::getEnabledFeatures() ibltextures.irradianceCube.descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; ibltextures.irradianceCube.device = vulkanDevice; - //Setup Framebuffer and so on - VkAttachmentDescription attachDescription = {}; - attachDescription.format = format; - attachDescription.samples = VK_SAMPLE_COUNT_1_BIT; - attachDescription.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - attachDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - attachDescription.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - attachDescription.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - + VkAttachmentDescription attDesc = {}; + attDesc.format = format; + attDesc.samples = VK_SAMPLE_COUNT_1_BIT; + attDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + attDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attDesc.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + VkAttachmentReference colorReference = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }; VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; @@ -1259,10 +1114,10 @@ void VulkanExample::getEnabledFeatures() dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - //set up render pass + VkRenderPassCreateInfo renderPassCI = vks::initializers::renderPassCreateInfo(); renderPassCI.attachmentCount = 1; - renderPassCI.pAttachments = &attachDescription; + renderPassCI.pAttachments = &attDesc; renderPassCI.subpassCount = 1; renderPassCI.pSubpasses = &subpassDescription; renderPassCI.dependencyCount = 2; @@ -1270,89 +1125,87 @@ void VulkanExample::getEnabledFeatures() VkRenderPass renderpass; VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &renderpass)); - // create offscreen image - VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo(); - imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; - imageCreateInfo.format = format; - imageCreateInfo.extent.width = dim; - imageCreateInfo.extent.height = dim; - imageCreateInfo.extent.depth = 1; - imageCreateInfo.mipLevels = 1; - imageCreateInfo.arrayLayers = 1; - imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; - imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; - imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - imageCreateInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &offscreen.image)) + { + VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo(); + imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; + imageCreateInfo.format = format; + imageCreateInfo.extent.width = dim; + imageCreateInfo.extent.height = dim; + imageCreateInfo.extent.depth = 1; + imageCreateInfo.mipLevels = 1; + imageCreateInfo.arrayLayers = 1; + imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; + imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; + imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + imageCreateInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &offscreen.image)) - // allocate memory - VkMemoryAllocateInfo imageCIMemAlloc = vks::initializers::memoryAllocateInfo(); - VkMemoryRequirements imageCIMemReqs; - vkGetImageMemoryRequirements(device, offscreen.image, &imageCIMemReqs); - imageCIMemAlloc.allocationSize = imageCIMemReqs.size; - imageCIMemAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(imageCIMemReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VK_CHECK_RESULT(vkAllocateMemory(device, &imageCIMemAlloc, nullptr, &offscreen.memory)) - VK_CHECK_RESULT(vkBindImageMemory(device, offscreen.image, offscreen.memory, 0)) + VkMemoryAllocateInfo memAlloc = vks::initializers::memoryAllocateInfo(); + VkMemoryRequirements memReqs; + vkGetImageMemoryRequirements(device, offscreen.image, &memReqs); + memAlloc.allocationSize = memReqs.size; + memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &offscreen.memory)) + VK_CHECK_RESULT(vkBindImageMemory(device, offscreen.image, offscreen.memory, 0)) - // create color image view - VkImageViewCreateInfo colorImageView = vks::initializers::imageViewCreateInfo(); - colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D; - colorImageView.format = format; - colorImageView.flags = 0; - colorImageView.subresourceRange = {}; - colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - colorImageView.subresourceRange.baseMipLevel = 0; - colorImageView.subresourceRange.levelCount = 1; - colorImageView.subresourceRange.baseArrayLayer = 0; - colorImageView.subresourceRange.layerCount = 1; - colorImageView.image = offscreen.image; - VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &offscreen.view)) + VkImageViewCreateInfo colorImageView = vks::initializers::imageViewCreateInfo(); + colorImageView.viewType = VK_IMAGE_VIEW_TYPE_2D; + colorImageView.format = format; + colorImageView.flags = 0; + colorImageView.subresourceRange = {}; + colorImageView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + colorImageView.subresourceRange.baseMipLevel = 0; + colorImageView.subresourceRange.levelCount = 1; + colorImageView.subresourceRange.baseArrayLayer = 0; + colorImageView.subresourceRange.layerCount = 1; + colorImageView.image = offscreen.image; + VK_CHECK_RESULT(vkCreateImageView(device, &colorImageView, nullptr, &offscreen.view)) - // set up framebuffer for offscreen image - VkFramebufferCreateInfo fbufCreateInfo = vks::initializers::framebufferCreateInfo(); - fbufCreateInfo.renderPass = renderpass; - fbufCreateInfo.attachmentCount = 1; - fbufCreateInfo.pAttachments = &offscreen.view; - fbufCreateInfo.width = dim; - fbufCreateInfo.height = dim; - fbufCreateInfo.layers = 1; - VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &offscreen.framebuffer)) + VkFramebufferCreateInfo fbufCreateInfo = vks::initializers::framebufferCreateInfo(); + fbufCreateInfo.renderPass = renderpass; + fbufCreateInfo.attachmentCount = 1; + fbufCreateInfo.pAttachments = &offscreen.view; + fbufCreateInfo.width = dim; + fbufCreateInfo.height = dim; + fbufCreateInfo.layers = 1; + VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &offscreen.framebuffer)) - VkCommandBuffer layoutCmd = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vks::tools::setImageLayout( - layoutCmd, - offscreen.image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - vulkanDevice->flushCommandBuffer(layoutCmd, queue, true); - - // create descriptor set layout + VkCommandBuffer layoutCmd = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); + vks::tools::setImageLayout( + layoutCmd, + offscreen.image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + vulkanDevice->flushCommandBuffer(layoutCmd, queue, true); + } VkDescriptorSetLayout descriptorsetlayout; std::vector setLayoutBindings = - { - vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0), - }; + { + vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0), + }; VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout)); - // allocate pool + std::vector poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) }; VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); VkDescriptorPool descriptorpool; VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool)); - //write to poos + VkDescriptorSet descriptorset; - VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1); + VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset)); VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(descriptorset, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &ibltextures.skyboxCube.descriptor); vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); - // push matrix + + + VkPipelineLayout pipelinelayout; std::vector pushConstantRanges = - { - vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(IrradiancePushBlock), 0) - }; + { + vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(IrradiancePushBlock), 0) + }; VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1); pipelineLayoutCI.pushConstantRangeCount = 1; pipelineLayoutCI.pPushConstantRanges = pushConstantRanges.data(); @@ -1370,13 +1223,17 @@ void VulkanExample::getEnabledFeatures() VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); std::array shaderStages; - const std::vector vertexInputBindings = + const std::vector vertexInputBindings = { vks::initializers::vertexInputBindingDescription(0, sizeof(VulkanglTFModel::Vertex), VK_VERTEX_INPUT_RATE_VERTEX), }; const std::vector vertexInputAttributes = { vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VulkanglTFModel::Vertex, pos)), // Location 0: Position + //vks::initializers::vertexInputAttributeDescription(0, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VulkanglTFModel::Vertex, normal)),// Location 1: Normal + //vks::initializers::vertexInputAttributeDescription(0, 2, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VulkanglTFModel::Vertex, uv)), // Location 2: Texture coordinates + //vks::initializers::vertexInputAttributeDescription(0, 3, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VulkanglTFModel::Vertex, color)), // Location 3: Color + //vks::initializers::vertexInputAttributeDescription(0, 4, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VulkanglTFModel::Vertex, tangent)), // Location 4 : Tangent }; VkPipelineVertexInputStateCreateInfo vertexInputStateCI = vks::initializers::pipelineVertexInputStateCreateInfo(); vertexInputStateCI.vertexBindingDescriptionCount = static_cast(vertexInputBindings.size()); @@ -1402,7 +1259,7 @@ void VulkanExample::getEnabledFeatures() VkPipeline pipeline; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipeline)); - // offscreen Render pass begin + //Render VkClearValue clearValues[1]; clearValues[0].color = { { 0.0f, 0.0f, 0.2f, 0.0f } }; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); @@ -1431,38 +1288,38 @@ void VulkanExample::getEnabledFeatures() VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f); VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0); - + vkCmdSetViewport(cmdBuf, 0, 1, &viewport); vkCmdSetScissor(cmdBuf, 0, 1, &scissor); - + VkImageSubresourceRange subresourceRange = {}; subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = numMips; subresourceRange.layerCount = 6; - + vks::tools::setImageLayout( - cmdBuf, - ibltextures.irradianceCube.image, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - subresourceRange); + cmdBuf, + ibltextures.irradianceCube.image, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + subresourceRange); - for (uint32_t m = 0; m < numMips; ++m) + for(uint32_t m = 0; m < numMips; ++m) { - for (uint32_t f = 0; f < 6; ++f) + for(uint32_t f = 0; f < 6; ++f) { viewport.width = static_cast(dim * std::pow(0.5f, m)); viewport.height = static_cast(dim * std::pow(0.5f, m)); vkCmdSetViewport(cmdBuf, 0, 1, &viewport); // Render scene from cube face's point of view vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); - irradinacePushBlock.mvp = glm::perspective((float)(M_PI / 2.0), 1.0f, 0.1f, 512.0f) * matrices[f]; - vkCmdPushConstants(cmdBuf, pipelinelayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(IrradiancePushBlock), &irradinacePushBlock); - + irradiancePushBlock.mvp = glm::perspective((float)(M_PI / 2.0), 1.0f, 0.1f, 512.0f) * matrices[f]; + vkCmdPushConstants(cmdBuf, pipelinelayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(IrradiancePushBlock), &irradiancePushBlock); + vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelinelayout, 0, 1, &descriptorset, 0, NULL); - skyboxModel.draw(cmdBuf, pipelinelayout); + skyboxModel.draw(cmdBuf, pipelinelayout, false); vkCmdEndRenderPass(cmdBuf); vks::tools::setImageLayout( @@ -1500,7 +1357,7 @@ void VulkanExample::getEnabledFeatures() VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL - ); + ); } } @@ -1524,11 +1381,9 @@ void VulkanExample::getEnabledFeatures() auto tEnd = std::chrono::high_resolution_clock::now(); auto tDiff = std::chrono::duration(tEnd - tStart).count(); std::cout << "Generating irradiance cube with " << numMips << " mip levels took " << tDiff << " ms" << std::endl; - } - - void VulkanExample::generatePrefilteredCubemap() + void VulkanExample::GeneratePrefilteredCubemap() { auto tStart = std::chrono::high_resolution_clock::now(); @@ -1633,6 +1488,12 @@ void VulkanExample::getEnabledFeatures() VkRenderPass renderpass; VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassCI, nullptr, &renderpass)); + struct { + VkImage image; + VkImageView view; + VkDeviceMemory memory; + VkFramebuffer framebuffer; + } offscreen; //framebuffer { // Color attachment @@ -1691,218 +1552,223 @@ void VulkanExample::getEnabledFeatures() vulkanDevice->flushCommandBuffer(layoutCmd, queue, true); } - // Descriptors - VkDescriptorSetLayout descriptorsetlayout; - std::vector setLayoutBindings = { - vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0), - }; - VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); - VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout)); + // Descriptors + VkDescriptorSetLayout descriptorsetlayout; + std::vector setLayoutBindings = { + vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0), + }; + VkDescriptorSetLayoutCreateInfo descriptorsetlayoutCI = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); + VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorsetlayoutCI, nullptr, &descriptorsetlayout)); - // Descriptor Pool - std::vector poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) }; - VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); - VkDescriptorPool descriptorpool; - VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool)); + // Descriptor Pool + std::vector poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1) }; + VkDescriptorPoolCreateInfo descriptorPoolCI = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2); + VkDescriptorPool descriptorpool; + VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCI, nullptr, &descriptorpool)); - VkDescriptorSet descriptorset; - VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1); - VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset)); - VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(descriptorset, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &ibltextures.skyboxCube.descriptor); - vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); + VkDescriptorSet descriptorset; + VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorpool, &descriptorsetlayout, 1); + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorset)); + VkWriteDescriptorSet writeDescriptorSet = vks::initializers::writeDescriptorSet(descriptorset, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &ibltextures.skyboxCube.descriptor); + vkUpdateDescriptorSets(device, 1, &writeDescriptorSet, 0, nullptr); + struct PushBlock { + glm::mat4 mvp; + float roughness; + uint32_t numSamples = 32u; + } pushBlock; - std::vector pushConstantRanges = { - vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(PrefilterPushBlock), 0), - }; - VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1); - pipelineLayoutCI.pushConstantRangeCount = 1; - pipelineLayoutCI.pPushConstantRanges = pushConstantRanges.data(); - VkPipelineLayout pipelinelayout; - VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelinelayout)); + std::vector pushConstantRanges = { + vks::initializers::pushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(PushBlock), 0), + }; + VkPipelineLayoutCreateInfo pipelineLayoutCI = vks::initializers::pipelineLayoutCreateInfo(&descriptorsetlayout, 1); + pipelineLayoutCI.pushConstantRangeCount = 1; + pipelineLayoutCI.pPushConstantRanges = pushConstantRanges.data(); + VkPipelineLayout pipelinelayout; + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCI, nullptr, &pipelinelayout)); - 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); - VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); - VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL); - VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1); - VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT); - std::vector dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; - VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); - std::array shaderStages; + 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); + VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); + VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); + VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL); + VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1); + VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT); + std::vector dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); + std::array shaderStages; - const std::vector vertexInputBindings = + const std::vector vertexInputBindings = + { + vks::initializers::vertexInputBindingDescription(0, sizeof(VulkanglTFModel::Vertex), VK_VERTEX_INPUT_RATE_VERTEX), + }; + + const std::vector vertexInputAttributes = { + vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VulkanglTFModel::Vertex, pos)), // Location 0: Position + }; + VkPipelineVertexInputStateCreateInfo vertexInputStateCI = vks::initializers::pipelineVertexInputStateCreateInfo(); + vertexInputStateCI.vertexBindingDescriptionCount = static_cast(vertexInputBindings.size()); + vertexInputStateCI.pVertexBindingDescriptions = vertexInputBindings.data(); + vertexInputStateCI.vertexAttributeDescriptionCount = static_cast(vertexInputAttributes.size()); + vertexInputStateCI.pVertexAttributeDescriptions = vertexInputAttributes.data(); + + VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelinelayout, renderpass); + pipelineCI.pInputAssemblyState = &inputAssemblyState; + pipelineCI.pRasterizationState = &rasterizationState; + pipelineCI.pColorBlendState = &colorBlendState; + pipelineCI.pMultisampleState = &multisampleState; + pipelineCI.pViewportState = &viewportState; + pipelineCI.pDepthStencilState = &depthStencilState; + pipelineCI.pDynamicState = &dynamicState; + pipelineCI.stageCount = 2; + pipelineCI.pStages = shaderStages.data(); + pipelineCI.renderPass = renderpass; + pipelineCI.pVertexInputState = &vertexInputStateCI; + + shaderStages[0] = loadShader(getHomeworkShadersPath() + "homework1/filtercube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + shaderStages[1] = loadShader(getHomeworkShadersPath() + "homework1/prefilterenvmap.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + + VkPipeline pipeline; + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipeline)); + + //Render & build cmd + VkClearValue clearValues[1]; + clearValues[0].color = { { 0.0f, 0.0f, 0.2f, 0.0f } }; + + VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); + // Reuse render pass from example pass + renderPassBeginInfo.renderPass = renderpass; + renderPassBeginInfo.framebuffer = offscreen.framebuffer; + renderPassBeginInfo.renderArea.extent.width = dim; + renderPassBeginInfo.renderArea.extent.height = dim; + renderPassBeginInfo.clearValueCount = 1; + renderPassBeginInfo.pClearValues = clearValues; + + std::vector matrices = { + // POSITIVE_X + glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), + // NEGATIVE_X + glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), + // POSITIVE_Y + glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)), + // NEGATIVE_Y + glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)), + // POSITIVE_Z + glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), + // NEGATIVE_Z + glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)), + }; + VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); + + VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f); + VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0); + + vkCmdSetViewport(cmdBuf, 0, 1, &viewport); + vkCmdSetScissor(cmdBuf, 0, 1, &scissor); + + VkImageSubresourceRange subresourceRange = {}; + subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + subresourceRange.baseMipLevel = 0; + subresourceRange.levelCount = numMips; + subresourceRange.layerCount = 6; + + vks::tools::setImageLayout( + cmdBuf, + ibltextures.prefilteredCube.image, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + subresourceRange); + + for (uint32_t m = 0; m < numMips; ++m) + { + //mip level according to roughness + pushBlock.roughness = float(m) / float(numMips - 1); + for (uint32_t f = 0; f < 6; ++f) { - vks::initializers::vertexInputBindingDescription(0, sizeof(VulkanglTFModel::Vertex), VK_VERTEX_INPUT_RATE_VERTEX), - }; + viewport.width = static_cast(dim * std::pow(0.5f, m)); + viewport.height = static_cast(dim * std::pow(0.5f, m)); + vkCmdSetViewport(cmdBuf, 0, 1, &viewport); + // Render scene from cube face's point of view + vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); - const std::vector vertexInputAttributes = { - vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VulkanglTFModel::Vertex, pos)), // Location 0: Position - }; - VkPipelineVertexInputStateCreateInfo vertexInputStateCI = vks::initializers::pipelineVertexInputStateCreateInfo(); - vertexInputStateCI.vertexBindingDescriptionCount = static_cast(vertexInputBindings.size()); - vertexInputStateCI.pVertexBindingDescriptions = vertexInputBindings.data(); - vertexInputStateCI.vertexAttributeDescriptionCount = static_cast(vertexInputAttributes.size()); - vertexInputStateCI.pVertexAttributeDescriptions = vertexInputAttributes.data(); + // Update shader push constant block + pushBlock.mvp = glm::perspective((float)(M_PI / 2.0), 1.0f, 0.1f, 512.0f) * matrices[f]; - VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelinelayout, renderpass); - pipelineCI.pInputAssemblyState = &inputAssemblyState; - pipelineCI.pRasterizationState = &rasterizationState; - pipelineCI.pColorBlendState = &colorBlendState; - pipelineCI.pMultisampleState = &multisampleState; - pipelineCI.pViewportState = &viewportState; - pipelineCI.pDepthStencilState = &depthStencilState; - pipelineCI.pDynamicState = &dynamicState; - pipelineCI.stageCount = 2; - pipelineCI.pStages = shaderStages.data(); - pipelineCI.renderPass = renderpass; - pipelineCI.pVertexInputState = &vertexInputStateCI; + vkCmdPushConstants(cmdBuf, pipelinelayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushBlock), &pushBlock); + vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelinelayout, 0, 1, &descriptorset, 0, nullptr); + skyboxModel.draw(cmdBuf, pipelinelayout, false); + vkCmdEndRenderPass(cmdBuf); - shaderStages[0] = loadShader(getHomeworkShadersPath() + "homework1/filtercube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); - shaderStages[1] = loadShader(getHomeworkShadersPath() + "homework1/prefilterenvmap.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + vks::tools::setImageLayout( + cmdBuf, + offscreen.image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - VkPipeline pipeline; - VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipeline)); + VkImageCopy copyRegion{}; + copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copyRegion.srcSubresource.baseArrayLayer = 0; + copyRegion.srcSubresource.mipLevel = 0; + copyRegion.srcSubresource.layerCount = 1; + copyRegion.srcOffset = { 0, 0, 0 }; - //Render & build cmd - VkClearValue clearValues[1]; - clearValues[0].color = { { 0.0f, 0.0f, 0.2f, 0.0f } }; + copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copyRegion.dstSubresource.baseArrayLayer = f; + copyRegion.dstSubresource.mipLevel = m; + copyRegion.dstSubresource.layerCount = 1; + copyRegion.dstOffset = { 0, 0, 0 }; - VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); - // Reuse render pass from example pass - renderPassBeginInfo.renderPass = renderpass; - renderPassBeginInfo.framebuffer = offscreen.framebuffer; - renderPassBeginInfo.renderArea.extent.width = dim; - renderPassBeginInfo.renderArea.extent.height = dim; - renderPassBeginInfo.clearValueCount = 1; - renderPassBeginInfo.pClearValues = clearValues; + copyRegion.extent.width = static_cast(viewport.width); + copyRegion.extent.height = static_cast(viewport.height); + copyRegion.extent.depth = 1; - std::vector matrices = { - // POSITIVE_X - glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), - // NEGATIVE_X - glm::rotate(glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), - // POSITIVE_Y - glm::rotate(glm::mat4(1.0f), glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)), - // NEGATIVE_Y - glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)), - // POSITIVE_Z - glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(1.0f, 0.0f, 0.0f)), - // NEGATIVE_Z - glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)), - }; - VkCommandBuffer cmdBuf = vulkanDevice->createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); + vkCmdCopyImage( + cmdBuf, + offscreen.image, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + ibltextures.prefilteredCube.image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + 1, + ©Region); - VkViewport viewport = vks::initializers::viewport((float)dim, (float)dim, 0.0f, 1.0f); - VkRect2D scissor = vks::initializers::rect2D(dim, dim, 0, 0); - - vkCmdSetViewport(cmdBuf, 0, 1, &viewport); - vkCmdSetScissor(cmdBuf, 0, 1, &scissor); - - VkImageSubresourceRange subresourceRange = {}; - subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - subresourceRange.baseMipLevel = 0; - subresourceRange.levelCount = numMips; - subresourceRange.layerCount = 6; - - vks::tools::setImageLayout( - cmdBuf, - ibltextures.prefilteredCube.image, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - subresourceRange); - - for (uint32_t m = 0; m < numMips; ++m) - { - //mip level according to roughness - prefilterPushBlock.roughness = float(m) / float(numMips - 1); - for (uint32_t f = 0; f < 6; ++f) - { - viewport.width = static_cast(dim * std::pow(0.5f, m)); - viewport.height = static_cast(dim * std::pow(0.5f, m)); - vkCmdSetViewport(cmdBuf, 0, 1, &viewport); - // Render scene from cube face's point of view - vkCmdBeginRenderPass(cmdBuf, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); - - // Update shader push constant block - prefilterPushBlock.mvp = glm::perspective((float)(M_PI / 2.0), 1.0f, 0.1f, 512.0f) * matrices[f]; - - vkCmdPushConstants(cmdBuf, pipelinelayout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PrefilterPushBlock), &prefilterPushBlock); - vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelinelayout, 0, 1, &descriptorset, 0, nullptr); - skyboxModel.draw(cmdBuf, pipelinelayout); - vkCmdEndRenderPass(cmdBuf); - - vks::tools::setImageLayout( - cmdBuf, - offscreen.image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - - VkImageCopy copyRegion{}; - copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyRegion.srcSubresource.baseArrayLayer = 0; - copyRegion.srcSubresource.mipLevel = 0; - copyRegion.srcSubresource.layerCount = 1; - copyRegion.srcOffset = { 0, 0, 0 }; - - copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyRegion.dstSubresource.baseArrayLayer = f; - copyRegion.dstSubresource.mipLevel = m; - copyRegion.dstSubresource.layerCount = 1; - copyRegion.dstOffset = { 0, 0, 0 }; - - copyRegion.extent.width = static_cast(viewport.width); - copyRegion.extent.height = static_cast(viewport.height); - copyRegion.extent.depth = 1; - - vkCmdCopyImage( - cmdBuf, - offscreen.image, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - ibltextures.prefilteredCube.image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1, - ©Region); - - //Reset frame buffer image layout - vks::tools::setImageLayout( - cmdBuf, - offscreen.image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - } + //Reset frame buffer image layout + vks::tools::setImageLayout( + cmdBuf, + offscreen.image, + VK_IMAGE_ASPECT_COLOR_BIT, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); } - - //Set format shader read - vks::tools::setImageLayout( - cmdBuf, - ibltextures.prefilteredCube.image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - subresourceRange); - - vulkanDevice->flushCommandBuffer(cmdBuf, queue); - - vkDestroyRenderPass(device, renderpass, nullptr); - vkDestroyFramebuffer(device, offscreen.framebuffer, nullptr); - vkFreeMemory(device, offscreen.memory, nullptr); - vkDestroyImageView(device, offscreen.view, nullptr); - vkDestroyImage(device, offscreen.image, nullptr); - vkDestroyDescriptorPool(device, descriptorpool, nullptr); - vkDestroyDescriptorSetLayout(device, descriptorsetlayout, nullptr); - vkDestroyPipeline(device, pipeline, nullptr); - vkDestroyPipelineLayout(device, pipelinelayout, nullptr); - - auto tEnd = std::chrono::high_resolution_clock::now(); - auto tDiff = std::chrono::duration(tEnd - tStart).count(); - std::cout << "Generating pre-filtered enivornment cube with " << numMips << " mip levels took " << tDiff << " ms" << std::endl; } - void VulkanExample::generateBRDFLUT() + //Set format shader read + vks::tools::setImageLayout( + cmdBuf, + ibltextures.prefilteredCube.image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + subresourceRange); + + vulkanDevice->flushCommandBuffer(cmdBuf, queue); + + vkDestroyRenderPass(device, renderpass, nullptr); + vkDestroyFramebuffer(device, offscreen.framebuffer, nullptr); + vkFreeMemory(device, offscreen.memory, nullptr); + vkDestroyImageView(device, offscreen.view, nullptr); + vkDestroyImage(device, offscreen.image, nullptr); + vkDestroyDescriptorPool(device, descriptorpool, nullptr); + vkDestroyDescriptorSetLayout(device, descriptorsetlayout, nullptr); + vkDestroyPipeline(device, pipeline, nullptr); + vkDestroyPipelineLayout(device, pipelinelayout, nullptr); + + auto tEnd = std::chrono::high_resolution_clock::now(); + auto tDiff = std::chrono::duration(tEnd - tStart).count(); + std::cout << "Generating pre-filtered enivornment cube with " << numMips << " mip levels took " << tDiff << " ms" << std::endl; +} + + void VulkanExample::GenerateBRDFLUT() { auto tStart = std::chrono::high_resolution_clock::now(); @@ -2105,13 +1971,16 @@ void VulkanExample::getEnabledFeatures() auto tEnd = std::chrono::high_resolution_clock::now(); auto tDiff = std::chrono::duration(tEnd - tStart).count(); std::cout << "Generating BRDF LUT took " << tDiff << " ms" << std::endl; -} - -//-------------------------- pbr precompute start ---------------------------------- - + } + //----------------------------End Precompute brick------------------------------------------------------------------// #pragma region pbr render pass setting - void VulkanExample::createAttachment(VkFormat format, VkImageUsageFlagBits usage, VulkanExample::FrameBufferAttachment* attachment, uint32_t width, uint32_t height) + void VulkanExample::createAttachment( + VkFormat format, + VkImageUsageFlagBits usage, + FrameBufferAttachment* attachment, + uint32_t width, + uint32_t height) { VkImageAspectFlags aspectMask = 0; VkImageUsageFlags imageUsage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT; @@ -2164,22 +2033,58 @@ void VulkanExample::getEnabledFeatures() imageView.image = attachment->image; VK_CHECK_RESULT(vkCreateImageView(device, &imageView, nullptr, &attachment->imageView)); } - #pragma endregion - -// ----------------------- pbr precompute end --------------------------------------- + // Prepare and initialize uniform buffer containing shader uniforms + void VulkanExample::prepareUniformBuffers() + { + // Vertex shader uniform buffer block + VK_CHECK_RESULT(vulkanDevice->createBuffer( + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + &shaderData.buffer, + sizeof(shaderData.values))); + VK_CHECK_RESULT(vulkanDevice->createBuffer( + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + &shaderData.skinSSBO, + sizeof(glm::mat4) * glTFModel.nodeCount)); + // Map persistent + VK_CHECK_RESULT(shaderData.buffer.map()); + VK_CHECK_RESULT(shaderData.skinSSBO.map()); + + for (auto& material : glTFModel.materials) + { + VK_CHECK_RESULT(vulkanDevice->createBuffer( + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, + &material.materialData.buffer, + sizeof(VulkanglTFModel::MaterialData::Values), + &material.materialData.values)); + } + + updateUniformBuffers(); + } + + void VulkanExample::updateUniformBuffers() + { + shaderData.values.projection = camera.matrices.perspective; + shaderData.values.model = camera.matrices.view; + shaderData.values.viewPos = camera.viewPos; + shaderData.values.bFlagSet.x = normalMapping; + shaderData.values.bFlagSet.y = pbrEnabled; + memcpy(shaderData.buffer.mapped, &shaderData.values, sizeof(shaderData.values)); + } - void VulkanExample::prepare() { VulkanExampleBase::prepare(); loadAssets(); - generateBRDFLUT(); - generateIrradianceCubemap(); - generatePrefilteredCubemap(); + GenerateBRDFLUT(); + GenerateIrradianceCubemap(); + GeneratePrefilteredCubemap(); prepareUniformBuffers(); setupDescriptors(); preparePipelines(); @@ -2193,10 +2098,8 @@ void VulkanExample::getEnabledFeatures() if (camera.updated) { updateUniformBuffers(); } - if (!paused) - { - glTFModel.updateAnimation(frameTimer,shaderData.skinSSBO); - } + if(!paused) + glTFModel.updateAnimation(frameTimer, shaderData.skinSSBO); } void VulkanExample::viewChanged() @@ -2210,10 +2113,20 @@ void VulkanExample::getEnabledFeatures() if (overlay->checkBox("Wireframe", &wireframe)) { buildCommandBuffers(); } + if (overlay->checkBox("NormalMapping", &normalMapping)) + { + } + if (overlay->checkBox("ToneMapping", &ToneMapping)) + { + CreateToneMappingPipeline(); + } + if (overlay->checkBox("PbrIndirect", &pbrEnabled)) + { + } } if (overlay->header("Animation")) { - overlay->checkBox("pause", &paused); + overlay->checkBox("Pause", &paused); } } diff --git a/homework/homework1/homework1.h b/homework/homework1/homework1.h index 5b39c45..1385b9c 100644 --- a/homework/homework1/homework1.h +++ b/homework/homework1/homework1.h @@ -216,15 +216,15 @@ public: void loadMaterials(tinygltf::Model& input); Node* findNode(Node* parent, uint32_t index); Node* nodeFromIndex(uint32_t index); - void loadSkins(tinygltf::Model& input); + //void loadSkins(tinygltf::Model& input); void loadAnimations(tinygltf::Model& input); void loadNode(const tinygltf::Node& inputNode, const tinygltf::Model& input, VulkanglTFModel::Node* parent, uint32_t nodeIndex, std::vector& indexBuffer, std::vector& vertexBuffer); glm::mat4 getNodeMatrix(VulkanglTFModel::Node* node); void updateNodeMatrix(Node* node, std::vector& nodeMatrics); - void updateJoints(VulkanglTFModel::Node* node); - void updateAnimation(float deltaTime,vks::Buffer buffer); - void drawNode(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout, VulkanglTFModel::Node node); - void draw(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout); + //void updateJoints(VulkanglTFModel::Node* node); + void updateAnimation(float deltaTime, vks::Buffer& buffer); + void drawNode(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout, VulkanglTFModel::Node* node, bool bPushConstants); + void draw(VkCommandBuffer commandBuffer, VkPipelineLayout pipelineLayout, bool flag); }; class VulkanExample : public VulkanExampleBase @@ -344,7 +344,7 @@ public: // Sampling deltas float deltaPhi = (2.0f * float(M_PI)) / 180.0f; float deltaTheta = (0.5f * float(M_PI)) / 64.0f; - } irradinacePushBlock; + } irradiancePushBlock; struct PrefilterPushBlock { glm::mat4 mvp; @@ -383,7 +383,7 @@ public: shaderData.buffer.destroy(); shaderData.skinSSBO.destroy(); } - void loadglTFFile(std::string filename, VulkanglTFModel& model, bool bSkyboxFlag = false); + void loadglTFFile(std::string filename, VulkanglTFModel& model, bool bSkyboxFlag); virtual void getEnabledFeatures(); void createAttachment(VkFormat format, VkImageUsageFlagBits usage, FrameBufferAttachment* attachment, uint32_t width, uint32_t height); virtual void setupFrameBuffer(); @@ -391,10 +391,10 @@ public: void loadAssets(); void setupDescriptors(); void preparePipelines(); - void prepareToneMappingPipeline(); - void generateIrradianceCubemap(); - void generatePrefilteredCubemap(); - void generateBRDFLUT(); + void CreateToneMappingPipeline(); + void GenerateIrradianceCubemap(); + void GeneratePrefilteredCubemap(); + void GenerateBRDFLUT(); void prepareUniformBuffers(); void updateUniformBuffers(); void prepare();