Compare commits

..

18 Commits

Author SHA1 Message Date
t ce8bc3a96b Implemented Maximal MSAA 2025-04-07 18:01:31 +02:00
t 2f485d11e6 Implemented Mipmaps 2025-04-07 17:31:34 +02:00
Ano-sys a4a1847f95 Now Models can be loaded 2025-04-06 00:36:45 +02:00
Ano-sys edc4931b67 Removed transitionImageLayout call in createDepthResources because renderPass takes care of this implicitly 2025-04-05 23:41:22 +02:00
Ano-sys b458f432ff Implemented Depth Buffering 2025-04-05 23:37:38 +02:00
Ano-sys 6d986f496e Image is projected onto the sqaure now 2025-04-05 15:04:30 +02:00
Ano-sys 881a43177e Example image of percy 2025-04-05 15:03:36 +02:00
Ano-sys 80012fc7e7 Implemented Sampler with Clamp to Edge (because I like this) and anisotrpic filtering to the graphics cards max 2025-04-05 14:40:32 +02:00
Ano-sys 45b362be82 Texture mapping functionallity implemented 2025-04-05 14:01:42 +02:00
Ano-sys b1c47589bc Added library requirements info at the top 2025-04-05 14:00:50 +02:00
Ano-sys 997e32f9bf Added entries to copy textures to cmake output dir 2025-04-05 14:00:19 +02:00
Ano-sys 71be91d2b1 Added set = 0 to layout for ubo 2025-04-04 18:05:35 +02:00
Ano-sys 3562c0308a Altered readme 2025-04-04 18:05:08 +02:00
Ano-sys 49d32224af added alignas(16) for right 16 byte offsets 2025-04-04 18:04:38 +02:00
Ano-sys cf88fecf08 Altered glm::rotate parameters 2025-04-04 18:03:31 +02:00
Ano-sys 8e0234c1fb Printing programpath added 2025-04-04 18:02:53 +02:00
Ano-sys e2e84eb42c The Square is rotating, oh damn vulkan 2025-04-04 16:29:13 +02:00
Ano-sys aa91619805 Static index buffering 2025-04-04 01:03:05 +02:00
10 changed files with 16915 additions and 103 deletions
+17 -9
View File
@@ -7,26 +7,37 @@ set(GLFW_USE_WAYLAND ON)
find_package(Vulkan REQUIRED) find_package(Vulkan REQUIRED)
find_package(glfw3 3.3 REQUIRED) find_package(glfw3 3.3 REQUIRED)
# Suche nach dem glslc Compiler
find_program(GLSLC glslc) find_program(GLSLC glslc)
if(NOT GLSLC) if(NOT GLSLC)
message(FATAL_ERROR "glslc compiler not found. Please install the Vulkan SDK.") message(FATAL_ERROR "glslc compiler not found. Please install the Vulkan SDK.")
endif() endif()
# Alle Shader-Dateien im Verzeichnis ./shaders sammeln # Copy textures into cmake output
file(GLOB TEXTURE_FILES
"${CMAKE_CURRENT_SOURCE_DIR}/textures/*"
)
foreach(TEXTURE ${TEXTURE_FILES})
file(COPY ${TEXTURE_FILES} DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/textures/")
endforeach()
# Copy models into cmake output
file(GLOB MODEL_FILES
"${CMAKE_CURRENT_SOURCE_DIR}/models/*"
)
foreach(MODEL ${MODEL_FILES})
file(COPY ${MODEL_FILES} DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/models/")
endforeach()
# Copy shaders into cmake output
file(GLOB SHADER_FILES file(GLOB SHADER_FILES
"${CMAKE_CURRENT_SOURCE_DIR}/shaders/*.vert" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/*.vert"
"${CMAKE_CURRENT_SOURCE_DIR}/shaders/*.frag" "${CMAKE_CURRENT_SOURCE_DIR}/shaders/*.frag"
) )
set(SPIRV_SHADERS "")
foreach(SHADER ${SHADER_FILES}) foreach(SHADER ${SHADER_FILES})
# Dateiname extrahieren
get_filename_component(SHADER_NAME ${SHADER} NAME) get_filename_component(SHADER_NAME ${SHADER} NAME)
# Zielpfad für die kompilierten Shader im Build-Verzeichnis
set(SPIRV "${CMAKE_CURRENT_BINARY_DIR}/shaders/${SHADER_NAME}.spv") set(SPIRV "${CMAKE_CURRENT_BINARY_DIR}/shaders/${SHADER_NAME}.spv")
# Custom Command zum Kompilieren des Shaders
add_custom_command( add_custom_command(
OUTPUT ${SPIRV} OUTPUT ${SPIRV}
COMMAND ${GLSLC} ${SHADER} -o ${SPIRV} COMMAND ${GLSLC} ${SHADER} -o ${SPIRV}
@@ -37,10 +48,8 @@ foreach(SHADER ${SHADER_FILES})
list(APPEND SPIRV_SHADERS ${SPIRV}) list(APPEND SPIRV_SHADERS ${SPIRV})
endforeach() endforeach()
# Custom Target, das alle Shader kompiliert
add_custom_target(compile_shaders ALL DEPENDS ${SPIRV_SHADERS}) add_custom_target(compile_shaders ALL DEPENDS ${SPIRV_SHADERS})
# Das eigentliche Executable
add_executable(vulkan_test add_executable(vulkan_test
main.cpp main.cpp
vulkan/vulkan_app.cpp vulkan/vulkan_app.cpp
@@ -49,5 +58,4 @@ add_executable(vulkan_test
target_link_libraries(vulkan_test PRIVATE Vulkan::Vulkan glfw) target_link_libraries(vulkan_test PRIVATE Vulkan::Vulkan glfw)
# Sicherstellen, dass die Shader vor dem Bauen des Executables kompiliert werden
add_dependencies(vulkan_test compile_shaders) add_dependencies(vulkan_test compile_shaders)
+1 -1
View File
@@ -1,3 +1,3 @@
# Vulkan_TestApp # Vulkan_TestApp
Triangle Test App with Vulkan API strictly following documentation. Test App with Vulkan API strictly following documentation.
+16 -3
View File
@@ -1,12 +1,25 @@
/**
* Required external Libraries:
* - Vulkan
* - glfw
* - glm
* - stb
* - tinyobjloader
*/
#define DEBUG 1 #define DEBUG 1
#include <iostream>
#include "vulkan/vulkan_app.hpp" #include "vulkan/vulkan_app.hpp"
int main(){ int main(int argc, char **argv){
std::cout << "Program path: " << argv[0] << std::endl;
try{ try{
vapp::Vulkan app; vapp::Vulkan app;
app.run("Vulkan", 1200, 900);
app.MODEL_PATH = "models/viking_room.obj";
app.TEXTURE_PATH = "textures/viking_room.png";
app.run("Vulkan", 800, 800);
} }
catch(const std::exception& e){ catch(const std::exception& e){
std::cerr << e.what() << std::endl; std::cerr << e.what() << std::endl;
+16053
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -1,9 +1,13 @@
#version 450 #version 450
layout(location = 0) in vec3 fragColor; layout(location = 0) in vec3 fragColor;
layout(location = 1) in vec2 fragTexCoord;
layout(location = 0) out vec4 outColor; layout(location = 0) out vec4 outColor;
layout(binding = 1) uniform sampler2D texSampler;
void main(){ void main(){
outColor = vec4(fragColor, 1.0); // outColor = vec4(fragTexCoord, 0.0, 1.0);
outColor = texture(texSampler, fragTexCoord);
} }
+11 -18
View File
@@ -1,27 +1,20 @@
#version 450 #version 450
layout(location = 0) in vec2 inPosition; layout(set = 0, binding = 0) uniform UniformBufferObject{
mat4 model;
mat4 view;
mat4 proj;
}ubo;
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inColor; layout(location = 1) in vec3 inColor;
layout(location = 2) in vec2 inTexCoord;
layout(location = 0) out vec3 fragColor; layout(location = 0) out vec3 fragColor;
layout(location = 1) out vec2 fragTexCoord;
/*
vec2 positions[3] = vec2[](
vec2(0.0, -0.5),
vec2(0.5, 0.5),
vec2(-0.5, 0.5)
);
vec3 colors[3] = vec3[](
vec3(0.0, 1.0, 1.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0)
);
*/
void main(){ void main(){
// gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0); gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0);
// fragColor = colors[gl_VertexIndex];
gl_Position = vec4(inPosition, 0.0, 1.0);
fragColor = inColor; fragColor = inColor;
fragTexCoord = inTexCoord;
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 940 KiB

+691 -54
View File
@@ -3,6 +3,13 @@
// //
#include "vulkan_app.hpp" #include "vulkan_app.hpp"
// throws duplicate include errors when in vulkan_app.hpp
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
// same as stb
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
namespace vapp{ namespace vapp{
const std::vector<const char*> validationLayers = { const std::vector<const char*> validationLayers = {
@@ -94,6 +101,23 @@ namespace vapp{
return extensions; return extensions;
} }
VkSampleCountFlagBits Vulkan::getMaxUsableSampleCount()
{
VkPhysicalDeviceProperties physicalDeviceProperties;
vkGetPhysicalDeviceProperties(physicalDevice, &physicalDeviceProperties);
VkSampleCountFlags counts = physicalDeviceProperties.limits.framebufferDepthSampleCounts;
if (counts & VK_SAMPLE_COUNT_64_BIT) return VK_SAMPLE_COUNT_64_BIT;
if (counts & VK_SAMPLE_COUNT_32_BIT) return VK_SAMPLE_COUNT_32_BIT;
if (counts & VK_SAMPLE_COUNT_16_BIT) return VK_SAMPLE_COUNT_16_BIT;
if (counts & VK_SAMPLE_COUNT_8_BIT) return VK_SAMPLE_COUNT_8_BIT;
if (counts & VK_SAMPLE_COUNT_4_BIT) return VK_SAMPLE_COUNT_4_BIT;
if (counts & VK_SAMPLE_COUNT_2_BIT) return VK_SAMPLE_COUNT_2_BIT;
return VK_SAMPLE_COUNT_1_BIT;
}
void Vulkan::createInstance(){ void Vulkan::createInstance(){
if(enableValidationLayers && !checkValidationLayerSupport()){ if(enableValidationLayers && !checkValidationLayerSupport()){
throw std::runtime_error("Func: createInstance\nError: Validation Layers requested, but not available!\n"); throw std::runtime_error("Func: createInstance\nError: Validation Layers requested, but not available!\n");
@@ -167,6 +191,7 @@ namespace vapp{
for(VkPhysicalDevice device : devices){ for(VkPhysicalDevice device : devices){
if(isDeviceSuitable(device)){ if(isDeviceSuitable(device)){
physicalDevice = device; physicalDevice = device;
msaaSamples = getMaxUsableSampleCount();
break; break;
} }
} }
@@ -193,6 +218,7 @@ namespace vapp{
} }
VkPhysicalDeviceFeatures deviceFeatures{}; VkPhysicalDeviceFeatures deviceFeatures{};
deviceFeatures.samplerAnisotropy = VK_TRUE;
VkDeviceCreateInfo createInfo{}; VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
@@ -260,15 +286,6 @@ namespace vapp{
} }
bool Vulkan::isDeviceSuitable(VkPhysicalDevice device){ bool Vulkan::isDeviceSuitable(VkPhysicalDevice device){
/*
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
return deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU && deviceFeatures.geometryShader;
*/
QueueFamilyIndices indices = findQueueFamilies(device); QueueFamilyIndices indices = findQueueFamilies(device);
bool extensionSupported = checkDeviceExtensionSupport(device); bool extensionSupported = checkDeviceExtensionSupport(device);
bool swapChainAdequate = false; bool swapChainAdequate = false;
@@ -276,7 +293,11 @@ namespace vapp{
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device); SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty(); swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
} }
return indices.isComplete() && extensionSupported && swapChainAdequate;
VkPhysicalDeviceFeatures supportedFeatures;
vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
return indices.isComplete() && extensionSupported && swapChainAdequate && supportedFeatures.samplerAnisotropy;
} }
void Vulkan::createSurface(){ void Vulkan::createSurface(){
@@ -311,7 +332,7 @@ namespace vapp{
VkSurfaceFormatKHR Vulkan::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats){ VkSurfaceFormatKHR Vulkan::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats){
for(const VkSurfaceFormatKHR availableFormat : availableFormats){ for(const VkSurfaceFormatKHR availableFormat : availableFormats){
if(availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == if(availableFormat.format == VK_FORMAT_R8G8B8A8_SRGB && availableFormat.colorSpace ==
VK_COLOR_SPACE_SRGB_NONLINEAR_KHR){ VK_COLOR_SPACE_SRGB_NONLINEAR_KHR){
return availableFormat; return availableFormat;
} }
@@ -408,40 +429,45 @@ namespace vapp{
void Vulkan::createImageViews(){ void Vulkan::createImageViews(){
swapChainImageViews.resize(swapChainImages.size()); swapChainImageViews.resize(swapChainImages.size());
for(size_t i = 0; i < swapChainImages.size(); i++){ for(uint32_t i = 0; i < swapChainImages.size(); i++){
VkImageViewCreateInfo createInfo{}; swapChainImageViews[i] = createImageView(swapChainImages[i], swapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT, 1);
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; }
createInfo.image = swapChainImages[i]; }
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; void Vulkan::createDescriptorSetLayout(){
createInfo.format = swapChainImageFormat; VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; VkDescriptorSetLayoutBinding samplerLayoutBinding{};
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; samplerLayoutBinding.binding = 1;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; samplerLayoutBinding.descriptorCount = 1;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.pImmutableSamplers = nullptr;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
if(vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS){ VkDescriptorSetLayoutCreateInfo layoutInfo{};
throw std::runtime_error("Func: createImageViews\nError: Failed to create Image Views!\n"); layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
} layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
if(vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS){
throw std::runtime_error("Func: createDescriptorSetLayout\nError: Failed to create Descriptor Set Layout!\n");
} }
} }
void Vulkan::createGraphicsPipeline(){ void Vulkan::createGraphicsPipeline(){
// TODO: find solution for file location
std::vector<char> vertShaderCode; std::vector<char> vertShaderCode;
std::vector<char> fragShaderCode; std::vector<char> fragShaderCode;
try{ try{
vertShaderCode = readFile("shaders/shader.vert.spv"); vertShaderCode = readFile("shaders/shader.vert.spv");
fragShaderCode = readFile("shaders/shader.frag.spv"); fragShaderCode = readFile("shaders/shader.frag.spv");
} }
catch(std::exception e){ catch(const std::exception &e){
std::cout << "Failed to read ./shaders/...\nTrying fallback folders!\n"; std::cout << "Failed to read ./shaders/...\nTrying fallback folders!\n";
vertShaderCode = readFile("../shaders/shader.vert.spv"); vertShaderCode = readFile("../shaders/shader.vert.spv");
fragShaderCode = readFile("../shaders/shader.frag.spv"); fragShaderCode = readFile("../shaders/shader.frag.spv");
@@ -520,13 +546,14 @@ namespace vapp{
rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // INFO: Other render effects rasterizer.polygonMode = VK_POLYGON_MODE_FILL; // INFO: Other render effects
rasterizer.lineWidth = 1.0f; rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; // rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; with descriptor sets this causes backface culling to occure
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE; rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling{}; VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE; multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisampling.rasterizationSamples = msaaSamples;
VkPipelineColorBlendAttachmentState colorBlendAttachment{}; VkPipelineColorBlendAttachmentState colorBlendAttachment{};
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT
@@ -547,8 +574,22 @@ namespace vapp{
colorBlending.attachmentCount = 1; colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment; colorBlending.pAttachments = &colorBlendAttachment;
VkPipelineDepthStencilStateCreateInfo depthStencil{};
depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
depthStencil.depthTestEnable = VK_TRUE;
depthStencil.depthWriteEnable = VK_TRUE;
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencil.depthBoundsTestEnable = VK_FALSE;
depthStencil.minDepthBounds = 0.0f;
depthStencil.maxDepthBounds = 1.0f;
depthStencil.stencilTestEnable = VK_FALSE;
depthStencil.front = {};
depthStencil.back = {};
VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if(vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS){ if(vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS){
throw std::runtime_error("Func; createGraphicsPipeline\nError: Failed to create pipeline layout!\n"); throw std::runtime_error("Func; createGraphicsPipeline\nError: Failed to create pipeline layout!\n");
@@ -567,6 +608,7 @@ namespace vapp{
pipelineInfo.pDepthStencilState = nullptr; // Optional because {} as initializer pipelineInfo.pDepthStencilState = nullptr; // Optional because {} as initializer
pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = &dynamicState; pipelineInfo.pDynamicState = &dynamicState;
pipelineInfo.pDepthStencilState = &depthStencil;
pipelineInfo.layout = pipelineLayout; pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = renderPass; pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0; pipelineInfo.subpass = 0;
@@ -600,37 +642,69 @@ namespace vapp{
} }
void Vulkan::createRenderPass(){ void Vulkan::createRenderPass(){
VkAttachmentDescription depthAttachment{};
depthAttachment.format = findDepthFormat();
depthAttachment.samples = msaaSamples;
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;;
depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthAttachmentRef{};
depthAttachmentRef.attachment = 1;
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentDescription colorAttachment{}; VkAttachmentDescription colorAttachment{};
colorAttachment.format = swapChainImageFormat; colorAttachment.format = swapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.samples = msaaSamples;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference colorAttachmentRef{}; VkAttachmentReference colorAttachmentRef{};
colorAttachmentRef.attachment = 0; colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentDescription colorAttachmentResolve{};
colorAttachmentResolve.format = swapChainImageFormat;
colorAttachmentResolve.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachmentResolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachmentResolve.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachmentResolve.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachmentResolve.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachmentResolve.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachmentResolve.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentResolveRef{};
colorAttachmentResolveRef.attachment = 2;
colorAttachmentResolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{}; VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1; subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef; subpass.pColorAttachments = &colorAttachmentRef;
subpass.pDepthStencilAttachment = &depthAttachmentRef;
subpass.pResolveAttachments = &colorAttachmentResolveRef;
VkSubpassDependency dependency{}; VkSubpassDependency dependency{};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0; dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
dependency.srcAccessMask = 0; dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;;
std::array<VkAttachmentDescription, 3> attachments = { colorAttachment, depthAttachment, colorAttachmentResolve };
VkRenderPassCreateInfo renderPassInfo{}; VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = 1; renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = 1; renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass; renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1; renderPassInfo.dependencyCount = 1;
@@ -641,23 +715,23 @@ namespace vapp{
} }
} }
void Vulkan::createFrameBuffers(){ void Vulkan::createFramebuffers(){
swapChainFramebuffers.resize(swapChainImageViews.size()); swapChainFramebuffers.resize(swapChainImageViews.size());
for(size_t i = 0; i < swapChainImageViews.size(); i++){ for(size_t i = 0; i < swapChainImageViews.size(); i++){
VkImageView attachements[] = {swapChainImageViews[i]}; std::array<VkImageView, 3> attachments = { colorImageView, depthImageView, swapChainImageViews[i] };
VkFramebufferCreateInfo framebufferInfo{}; VkFramebufferCreateInfo framebufferInfo{};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.renderPass = renderPass; framebufferInfo.renderPass = renderPass;
framebufferInfo.attachmentCount = 1; framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
framebufferInfo.pAttachments = attachements; framebufferInfo.pAttachments = attachments.data();
framebufferInfo.width = swapChainExtent.width; framebufferInfo.width = swapChainExtent.width;
framebufferInfo.height = swapChainExtent.height; framebufferInfo.height = swapChainExtent.height;
framebufferInfo.layers = 1; framebufferInfo.layers = 1;
if(vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS){ if(vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS){
throw std::runtime_error("Func: createFrameBuffers\nError: Failed to create Framebuffer!\n"); throw std::runtime_error("Func: createFramebuffers\nError: Failed to create Framebuffer!\n");
} }
} }
} }
@@ -674,6 +748,358 @@ namespace vapp{
} }
} }
VkFormat Vulkan::findSupportedFormat(const std::vector<VkFormat> &candidates, VkImageTiling tiling, VkFormatFeatureFlags features){
for(VkFormat format : candidates){
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props);
if(tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features){
return format;
}
if(tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features){
return format;
}
throw std::runtime_error("Func: findSupportedFormat\nError: Failed to find supported Format!\n");
}
}
VkFormat Vulkan::findDepthFormat(){
return findSupportedFormat(
{ VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
VK_IMAGE_TILING_OPTIMAL,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
);
}
bool hasStencilComponent(VkFormat format){
return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT;
}
void Vulkan::createColorResources()
{
VkFormat colorFormat = swapChainImageFormat;
createImage(swapChainExtent.width, swapChainExtent.height, 1, msaaSamples, colorFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, colorImage, colorImageMemory);
colorImageView = createImageView(colorImage, colorFormat, VK_IMAGE_ASPECT_COLOR_BIT, 1);
}
void Vulkan::createDepthResources(){
VkFormat depthFormat = findDepthFormat();
createImage(swapChainExtent.width, swapChainExtent.height, 1, msaaSamples, depthFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, depthImage, depthImageMemory);
depthImageView = createImageView(depthImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT, 1);
}
VkCommandBuffer Vulkan::beginSingleTimeCommands(){
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
return commandBuffer;
}
void Vulkan::endSingleTimeCommands(VkCommandBuffer commandBuffer){
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
void Vulkan::copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size){
VkCommandBuffer commandBuffer = beginSingleTimeCommands();
VkBufferCopy copyRegion{};
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion);
endSingleTimeCommands(commandBuffer);
}
void Vulkan::transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels){
VkCommandBuffer commandBuffer = beginSingleTimeCommands();
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if(oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL){
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if(oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL){
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else{
throw std::invalid_argument("Func: transitionImageLayout\nError: Unsupported Layout Transition!\n");
}
vkCmdPipelineBarrier(commandBuffer, sourceStage, destinationStage, 0, 0, nullptr, 0, nullptr, 1, &barrier);
endSingleTimeCommands(commandBuffer);
}
void Vulkan::copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height){
VkCommandBuffer commandBuffer = beginSingleTimeCommands();
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = { width, height, 1 };
vkCmdCopyBufferToImage(commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
endSingleTimeCommands(commandBuffer);
}
void Vulkan::createImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage &image, VkDeviceMemory &imageMemory){
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D; // 3D is used to store voxel volumes
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling; // or LINEAR for direct memory access of texels, OPTIMAL provides efficient access from shader
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0; // something tells me this has another value when using voxels
if(vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS){
throw std::runtime_error("Func: createImage\nError: Failed to create Image!\n");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
if(vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS){
throw std::runtime_error("Func: createTextureImage\nError: Failed to allocate memory for Image!\n");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Vulkan::generateMipmaps(VkImage image, VkFormat imageFormat, int32_t texWidth, int32_t texHeight, uint32_t mipLevels){
// normally mipmaps are stored alongside base level of image
VkFormatProperties formatProperties;
vkGetPhysicalDeviceFormatProperties(physicalDevice, imageFormat, &formatProperties);
if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
{
throw std::runtime_error("Func: generateMipmaps\nError: Texture Image Format does not support linear blitting!\n");
}
VkCommandBuffer commandBuffer = beginSingleTimeCommands();
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.image = image;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
barrier.subresourceRange.levelCount = 1;
int32_t mipWidth = texWidth;
int32_t mipHeight = texHeight;
for (uint32_t i = 1; i < mipLevels; i++)
{
barrier.subresourceRange.baseMipLevel = i - 1;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
VkImageBlit blit{};
blit.srcOffsets[0] = { 0, 0, 0 };
blit.srcOffsets[1] = { mipWidth, mipHeight, 1 };
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.srcSubresource.mipLevel = i - 1;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = 1;
blit.dstOffsets[0] = { 0, 0, 0 };
blit.dstOffsets[1] = { mipWidth > 1 ? mipWidth / 2 : 1, mipHeight > 1 ? mipHeight / 2 : 1, 1 };
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.dstSubresource.mipLevel = i;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = 1;
vkCmdBlitImage(commandBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR);
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
if (mipWidth > 1) mipWidth /= 2;
if (mipHeight > 1) mipHeight /= 2;
}
barrier.subresourceRange.baseMipLevel = mipLevels - 1;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
endSingleTimeCommands(commandBuffer);
}
void Vulkan::createTextureImage(){
int texWidth, texHeight, texChannels;
if(MODEL_PATH == "" || TEXTURE_PATH == ""){
throw std::runtime_error("Func: createTextureImage\nError: No file was given in MODEL_PATH or TEXTURE_PATH!\n");
}
stbi_uc *pixels = stbi_load(TEXTURE_PATH.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
VkDeviceSize imageSize = texWidth * texHeight * 4; // 4 bytes per pixel
mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(texWidth, texHeight)))) + 1;
if(!pixels) throw std::runtime_error("Func: createTextureImage\nError: Failed to load Texture Image!\n");
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
createBuffer(imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
void *data;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &data);
memcpy(data, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
stbi_image_free(pixels);
createImage(texWidth, texHeight, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, textureImage, textureImageMemory);
transitionImageLayout(textureImage, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels);
copyBufferToImage(stagingBuffer, textureImage, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight));
// removed because of mipmapping
// transitionImageLayout(textureImage, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_LAYOUT_UNDEFINED /*TRANSFER_DST_OPTIMAL*/, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL /*SHADER_READ_ONLY_OPTIMAL*/, mipLevels);
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
generateMipmaps(textureImage, VK_FORMAT_R8G8B8A8_SRGB, texWidth, texHeight, mipLevels);
}
VkImageView Vulkan::createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels){
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
VkImageView imageView;
if(vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS){
throw std::runtime_error("Func: createTextureImageView\nError: Failed to create Texture Image View!\n");
}
return imageView;
}
void Vulkan::createTextureImageView(){
textureImageView = createImageView(textureImage, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
}
void Vulkan::createTextureSampler(){
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
// INFO: Here can preferences be used -> instead of REPEAT I use CLAMP_TO_EDGE to get this nice eye cancer
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
// INFO: filter user preferences here
samplerInfo.anisotropyEnable = VK_TRUE;
VkPhysicalDeviceProperties properties{};
vkGetPhysicalDeviceProperties(physicalDevice, &properties);
samplerInfo.maxAnisotropy = properties.limits.maxSamplerAnisotropy;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.minLod = /*static_cast<float>(mipLevels / 2);*/ 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
samplerInfo.mipLodBias = 0.0f;
if(vkCreateSampler(device, &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS){
throw std::runtime_error("Func: createTextureSampler\nError: Failed to create Texture Sampler!\n");
}
}
uint32_t Vulkan::findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties){ uint32_t Vulkan::findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties){
VkPhysicalDeviceMemoryProperties memProperties; VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
@@ -703,6 +1129,7 @@ namespace vapp{
allocInfo.allocationSize = memRequirements.size; allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties); allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
// TODO: switch vkAllocateMemory with own implementation or GPUOpen's VulkanMemoryAllocator
if(vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS){ if(vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS){
throw std::runtime_error("Func: createBuffer\nError: Failed to allocate memory for buffer!\n"); throw std::runtime_error("Func: createBuffer\nError: Failed to allocate memory for buffer!\n");
} }
@@ -710,7 +1137,7 @@ namespace vapp{
vkBindBufferMemory(device, buffer, bufferMemory, 0); vkBindBufferMemory(device, buffer, bufferMemory, 0);
} }
void Vulkan::copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size){ void Vulkan::copyBufferOld(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size){
VkCommandBufferAllocateInfo allocInfo{}; VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
@@ -744,6 +1171,47 @@ namespace vapp{
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
} }
void Vulkan::loadModel(){
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string warn, err;
if(!tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, MODEL_PATH.c_str())){
throw std::runtime_error("Func: loadModel\nError: " + warn + err + "\n");
}
std::unordered_map<Vertex, uint32_t> uniqueVertices{};
for(const auto &shape : shapes){
for(const auto &index : shape.mesh.indices){
Vertex vertex{};
vertex.pos = {
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2],
};
vertex.texCoord = {
attrib.texcoords[2 * index.texcoord_index + 0],
1.0f - attrib.texcoords[2 * index.texcoord_index + 1],
};
vertex.color = { 1.0f, 1.0f, 1.0f };
if(!uniqueVertices.contains(vertex)){
uniqueVertices[vertex] = static_cast<uint32_t>(vertices.size());
vertices.push_back(vertex);
}
indices.push_back(uniqueVertices[vertex]);
}
}
}
void Vulkan::createVertexBuffer(){ void Vulkan::createVertexBuffer(){
VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size();
@@ -765,6 +1233,105 @@ namespace vapp{
vkFreeMemory(device, stagingBufferMemory, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr);
} }
void Vulkan::createIndexBuffer(){
VkDeviceSize bufferSize = sizeof(indices[0]) * indices.size();
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
void *data;
vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, indices.data(), (size_t)bufferSize);
vkUnmapMemory(device, stagingBufferMemory);
createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory);
copyBuffer(stagingBuffer, indexBuffer, bufferSize);
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Vulkan::createUniformBuffers(){
VkDeviceSize bufferSize = sizeof(UniformBufferObject);
uniformBuffers.resize(MAX_FRAMES_IN_FLIGHT);
uniformBuffersMemory.resize(MAX_FRAMES_IN_FLIGHT);
uniformBuffersMapped.resize(MAX_FRAMES_IN_FLIGHT);
for(size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++){
createBuffer(bufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, uniformBuffers[i], uniformBuffersMemory[i]);
vkMapMemory(device, uniformBuffersMemory[i], 0, bufferSize, 0, &uniformBuffersMapped[i]);
}
}
void Vulkan::createDescriptorPool(){
std::array<VkDescriptorPoolSize, 2> poolSizes{};
poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSizes[0].descriptorCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSizes[1].descriptorCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
if(vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS){
throw std::runtime_error("Func: createDescriptorPool\nError: Failed to create Descriptor Pool!\n");
}
}
void Vulkan::createDescriptorSets(){
std::vector<VkDescriptorSetLayout> layouts(MAX_FRAMES_IN_FLIGHT, descriptorSetLayout);
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
allocInfo.pSetLayouts = layouts.data();
descriptorSets.resize(MAX_FRAMES_IN_FLIGHT);
if(vkAllocateDescriptorSets(device, &allocInfo, descriptorSets.data()) != VK_SUCCESS){
throw std::runtime_error("Func: createDescriptorSets\nError: Failed to allocate Descriptor Sets!\n");
}
for(size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++){
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffers[i];
bufferInfo.offset = 0;
bufferInfo.range = sizeof(UniformBufferObject);
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = textureImageView;
imageInfo.sampler = textureSampler;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSets[i];
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSets[i];
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
}
void Vulkan::createCommandBuffers(){ void Vulkan::createCommandBuffers(){
commandBuffers.resize(MAX_FRAMES_IN_FLIGHT); commandBuffers.resize(MAX_FRAMES_IN_FLIGHT);
@@ -794,9 +1361,12 @@ namespace vapp{
renderPassInfo.renderArea.offset = {0, 0}; renderPassInfo.renderArea.offset = {0, 0};
renderPassInfo.renderArea.extent = swapChainExtent; renderPassInfo.renderArea.extent = swapChainExtent;
VkClearValue clearColor = {{{0.01f, 0.01f, 0.01f, 1.0f}}}; // Background color after clear (Black 100%) std::array<VkClearValue, 2> clearValues{};
renderPassInfo.clearValueCount = 1; clearValues[0].color = {{0.01f, 0.01f, 0.01f, 1.0f}}; // Background color after clear (Black 100%)
renderPassInfo.pClearValues = &clearColor; clearValues[1].depthStencil = { 1.0f, 0 };
renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
renderPassInfo.pClearValues = clearValues.data();
vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);
@@ -805,6 +1375,8 @@ namespace vapp{
VkDeviceSize offsets[] = { 0 }; VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets); vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(commandBuffer, indexBuffer, 0, VK_INDEX_TYPE_UINT32);
VkViewport viewport{}; VkViewport viewport{};
viewport.x = 0.0f; viewport.x = 0.0f;
viewport.y = 0.0f; viewport.y = 0.0f;
@@ -819,7 +1391,11 @@ namespace vapp{
scissor.extent = swapChainExtent; scissor.extent = swapChainExtent;
vkCmdSetScissor(commandBuffer, 0, 1, &scissor); vkCmdSetScissor(commandBuffer, 0, 1, &scissor);
vkCmdDraw(commandBuffer, static_cast<uint32_t>(vertices.size()), 1, 0, 0); vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentFrame], 0, nullptr);
// vkCmdDraw(commandBuffer, static_cast<uint32_t>(vertices.size()), 1, 0, 0);
// -> goto indexed draw
vkCmdDrawIndexed(commandBuffer, static_cast<uint32_t>(indices.size()), 1, 0, 0, 0);
vkCmdEndRenderPass(commandBuffer); vkCmdEndRenderPass(commandBuffer);
if(vkEndCommandBuffer(commandBuffer) != VK_SUCCESS){ if(vkEndCommandBuffer(commandBuffer) != VK_SUCCESS){
@@ -848,6 +1424,27 @@ namespace vapp{
} }
} }
void Vulkan::updateUniformBuffer(uint32_t currentFrame){
static auto startTime = std::chrono::high_resolution_clock::now();
auto currentTime = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count();
// to not pass rotation over time instead by fps
// float time = (currentTime - startTime).count();
UniformBufferObject ubo{};
// INFO: Change here for other angles
ubo.model = glm::rotate(glm::mat4(1.0f), time * glm::radians(60.0f), glm::vec3(0.0f, 0.0f, 1.0f));
ubo.view = glm::lookAt(glm::vec3(2.0f, 2.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f));
ubo.proj = glm::perspective(glm::radians(45.0f), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f);
// removing this line results in the image rendering upside down
ubo.proj[1][1] *= -1;
memcpy(uniformBuffersMapped[currentFrame], &ubo, sizeof(ubo));
}
void Vulkan::drawFrame(){ void Vulkan::drawFrame(){
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]); vkResetFences(device, 1, &inFlightFences[currentFrame]);
@@ -861,6 +1458,8 @@ namespace vapp{
vkResetCommandBuffer(commandBuffers[currentFrame], 0); vkResetCommandBuffer(commandBuffers[currentFrame], 0);
recordCommandBuffer(commandBuffers[currentFrame], imageIndex); recordCommandBuffer(commandBuffers[currentFrame], imageIndex);
updateUniformBuffer(currentFrame);
VkSubmitInfo submitInfo{}; VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
@@ -905,6 +1504,14 @@ namespace vapp{
} }
void Vulkan::cleanupSwapChain(){ void Vulkan::cleanupSwapChain(){
vkDestroyImageView(device, colorImageView, nullptr);
vkDestroyImage(device, colorImage, nullptr);
vkFreeMemory(device, colorImageMemory, nullptr);
vkDestroyImageView(device, depthImageView, nullptr);
vkDestroyImage(device, depthImage, nullptr);
vkFreeMemory(device, depthImageMemory, nullptr);
for(const auto & swapChainFramebuffer : swapChainFramebuffers) for(const auto & swapChainFramebuffer : swapChainFramebuffers)
{ vkDestroyFramebuffer(device, swapChainFramebuffer, nullptr); } { vkDestroyFramebuffer(device, swapChainFramebuffer, nullptr); }
for(const auto & swapChainImageView : swapChainImageViews) for(const auto & swapChainImageView : swapChainImageViews)
@@ -915,7 +1522,6 @@ namespace vapp{
void Vulkan::recreateSwapChain(){ void Vulkan::recreateSwapChain(){
int width = 0, height = 0; int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
while(width == 0 || height == 0){ while(width == 0 || height == 0){
glfwGetFramebufferSize(window, &width, &height); glfwGetFramebufferSize(window, &width, &height);
glfwPollEvents(); glfwPollEvents();
@@ -927,7 +1533,9 @@ namespace vapp{
createSwapChain(); createSwapChain();
createImageViews(); createImageViews();
createFrameBuffers(); createColorResources();
createDepthResources();
createFramebuffers();
} }
static void framebufferResizeCallback(GLFWwindow *window, int width, int height){ static void framebufferResizeCallback(GLFWwindow *window, int width, int height){
@@ -938,7 +1546,7 @@ namespace vapp{
void Vulkan::initWindow(const char *windowName){ void Vulkan::initWindow(const char *windowName){
glfwInit(); glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // tell glfw to not use opengl glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // tell glfw to not use opengl
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // disable window resize glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); // disable window resize
this->window = glfwCreateWindow(static_cast<int>(_width), static_cast<int>(_height), windowName, nullptr, nullptr); this->window = glfwCreateWindow(static_cast<int>(_width), static_cast<int>(_height), windowName, nullptr, nullptr);
glfwSetWindowUserPointer(window, this); glfwSetWindowUserPointer(window, this);
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback); glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
@@ -953,10 +1561,21 @@ namespace vapp{
createSwapChain(); createSwapChain();
createImageViews(); createImageViews();
createRenderPass(); createRenderPass();
createDescriptorSetLayout();
createGraphicsPipeline(); createGraphicsPipeline();
createFrameBuffers();
createCommandPool(); createCommandPool();
createColorResources();
createDepthResources();
createFramebuffers();
createTextureImage();
createTextureImageView();
createTextureSampler();
loadModel();
createVertexBuffer(); createVertexBuffer();
createIndexBuffer();
createUniformBuffers();
createDescriptorPool();
createDescriptorSets();
createCommandBuffers(); createCommandBuffers();
createSyncObjects(); createSyncObjects();
} }
@@ -974,6 +1593,24 @@ namespace vapp{
// Vulkan // Vulkan
cleanupSwapChain(); cleanupSwapChain();
vkDestroySampler(device, textureSampler, nullptr);
vkDestroyImageView(device, textureImageView, nullptr);
vkDestroyImage(device, textureImage, nullptr);
vkFreeMemory(device, textureImageMemory, nullptr);
for(size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++){
vkDestroyBuffer(device, uniformBuffers[i], nullptr);
vkFreeMemory(device, uniformBuffersMemory[i], nullptr);
}
vkDestroyDescriptorPool(device, descriptorPool, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
vkDestroyBuffer(device, indexBuffer, nullptr);
vkFreeMemory(device, indexBufferMemory, nullptr);
vkDestroyBuffer(device, vertexBuffer, nullptr); vkDestroyBuffer(device, vertexBuffer, nullptr);
vkFreeMemory(device, vertexBufferMemory, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr);
+121 -17
View File
@@ -8,42 +8,50 @@
#define GLFW_INCLUDE_VULKAN #define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h> #include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/hash.hpp>
#include <iostream> #include <iostream>
#include <stdexcept>
#include <cstdlib>
#include <cstring> #include <cstring>
#include <cstdint> #include <cstdint>
#include <vector> #include <vector>
#include <optional> #include <optional>
#include <set> #include <set>
#include <limits>
#include <algorithm>
#include <fstream> #include <fstream>
#include <glm/glm.hpp>
#include <array> #include <array>
#include <chrono>
#include <unordered_map>
namespace vapp{ namespace vapp{
// Change here for other presentMode // Change here for other presentMode
const VkPresentModeKHR WISHED_PRESENT_MODE = VK_PRESENT_MODE_MAILBOX_KHR; const VkPresentModeKHR WISHED_PRESENT_MODE = VK_PRESENT_MODE_MAILBOX_KHR;
struct Vertex{ struct Vertex{
glm::vec2 pos; glm::vec3 pos;
glm::vec3 color; glm::vec3 color;
glm::vec2 texCoord;
static VkVertexInputBindingDescription getBindingDescription(){ static VkVertexInputBindingDescription getBindingDescription(){
VkVertexInputBindingDescription bindingDescription{}; VkVertexInputBindingDescription bindingDescription{};
bindingDescription.binding = 0; bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex); bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription; return bindingDescription;
} }
static std::array<VkVertexInputAttributeDescription, 2> getAttributeDescriptions(){ static std::array<VkVertexInputAttributeDescription, 3> getAttributeDescriptions(){
std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions{}; std::array<VkVertexInputAttributeDescription, 3> attributeDescriptions{};
attributeDescriptions[0].binding = 0; attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0; attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32_SFLOAT; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, pos); attributeDescriptions[0].offset = offsetof(Vertex, pos);
attributeDescriptions[1].binding = 0; attributeDescriptions[1].binding = 0;
@@ -51,15 +59,44 @@ namespace vapp{
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, color); attributeDescriptions[1].offset = offsetof(Vertex, color);
attributeDescriptions[2].binding = 0;
attributeDescriptions[2].location = 2;
attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
return attributeDescriptions; return attributeDescriptions;
} }
bool operator==(const Vertex &other) const{
return pos == other.pos && color == other.color && texCoord == other.texCoord;
}
}; };
// TODO: Remove /*
const std::vector<Vertex> vertices = { const std::vector<Vertex> vertices = {
{{0.0f, -0.5f}, {0.0f, 1.0f, 0.0f}}, {{-0.5f, -0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f}},
{{0.5f, 0.5f}, {0.0f, 1.0f, 0.0f}}, {{0.5f, -0.5f, 0.0f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
{{-0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}} {{0.5f, 0.5f, 0.0f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
{{-0.5f, 0.5f, 0.0f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}},
{{-0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f}},
{{0.5f, -0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 0.0f}},
{{0.5f, 0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 1.0f}},
{{-0.5f, 0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 1.0f}}
};
// uint16_t also possible -> change in vkCmdBindIndexBuffer also
const std::vector<uint32_t> indices = {
0, 1, 2, 2, 3, 0,
4, 5, 6, 6, 7, 4
};
*/
// END Remove
struct UniformBufferObject{
alignas(16) glm::mat4 model;
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
}; };
struct QueueFamilyIndices{ struct QueueFamilyIndices{
@@ -83,7 +120,7 @@ namespace vapp{
class Vulkan{ class Vulkan{
private: private:
#pragma region Fields #pragma region PrivateFields
GLFWwindow *window; GLFWwindow *window;
uint32_t _width, _height; uint32_t _width, _height;
@@ -106,6 +143,7 @@ namespace vapp{
std::vector<VkImageView> swapChainImageViews; std::vector<VkImageView> swapChainImageViews;
VkRenderPass renderPass; VkRenderPass renderPass;
VkDescriptorSetLayout descriptorSetLayout;
VkPipelineLayout pipelineLayout; VkPipelineLayout pipelineLayout;
VkPipeline graphicsPipeline; VkPipeline graphicsPipeline;
@@ -121,12 +159,39 @@ namespace vapp{
const int MAX_FRAMES_IN_FLIGHT = 2; const int MAX_FRAMES_IN_FLIGHT = 2;
uint32_t currentFrame = 0; uint32_t currentFrame = 0;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
VkBuffer vertexBuffer; VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory; VkDeviceMemory vertexBufferMemory;
#pragma endregion VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
std::vector<VkBuffer> uniformBuffers;
std::vector<VkDeviceMemory> uniformBuffersMemory;
std::vector<void*> uniformBuffersMapped;
VkDescriptorPool descriptorPool;
std::vector<VkDescriptorSet> descriptorSets;
int32_t mipLevels;
VkImage textureImage;
VkDeviceMemory textureImageMemory;
VkImageView textureImageView;
VkSampler textureSampler;
VkImage depthImage;
VkDeviceMemory depthImageMemory;
VkImageView depthImageView;
VkImage colorImage;
VkDeviceMemory colorImageMemory;
VkImageView colorImageView;
#pragma endregion
#pragma region PrivateFunctions
bool checkValidationLayerSupport(); bool checkValidationLayerSupport();
std::vector<const char*> getRequiredExtensions(); std::vector<const char*> getRequiredExtensions();
VkSampleCountFlagBits getMaxUsableSampleCount();
void createInstance(); void createInstance();
void setupDebugMessenger(); void setupDebugMessenger();
@@ -142,18 +207,40 @@ namespace vapp{
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities);
void createSwapChain(); void createSwapChain();
void createImageViews(); void createImageViews();
void createDescriptorSetLayout();
void createGraphicsPipeline(); void createGraphicsPipeline();
VkShaderModule createShaderModule(const std::vector<char>& code); VkShaderModule createShaderModule(const std::vector<char>& code);
void createRenderPass(); void createRenderPass();
void createFrameBuffers(); void createFramebuffers();
void createCommandPool(); void createCommandPool();
VkFormat findSupportedFormat(const std::vector<VkFormat> &candidates, VkImageTiling tiling, VkFormatFeatureFlags features);
VkFormat findDepthFormat();
void createColorResources();
void createDepthResources();
VkCommandBuffer beginSingleTimeCommands();
void endSingleTimeCommands(VkCommandBuffer commandBuffer);
void transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels);
void copyBufferToImage(VkBuffer buffer, VkImage image, uint32_t width, uint32_t height);
void createImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory &imageMemory);
void generateMipmaps(VkImage image, VkFormat imageFormat, int32_t texWidth, int32_t texHeight, uint32_t mipLevels);
void createTextureImage();
VkImageView createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void createTextureImageView();
void createTextureSampler();
uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties); uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties);
void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer &buffer, VkDeviceMemory &bufferMemory); void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer &buffer, VkDeviceMemory &bufferMemory);
void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
void copyBufferOld(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
void loadModel();
void createVertexBuffer(); void createVertexBuffer();
void createIndexBuffer();
void createUniformBuffers();
void createDescriptorPool();
void createDescriptorSets();
void createCommandBuffers(); void createCommandBuffers();
void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex); void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex);
void createSyncObjects(); void createSyncObjects();
void updateUniformBuffer(uint32_t currentFrame);
void drawFrame(); void drawFrame();
void cleanupSwapChain(); void cleanupSwapChain();
void recreateSwapChain(); void recreateSwapChain();
@@ -161,8 +248,9 @@ namespace vapp{
void initVulkan(); void initVulkan();
void mainLoop(); void mainLoop();
void cleanup(); void cleanup();
#pragma endregion
public: public:
#pragma region PublicFields
#ifdef DEBUG #ifdef DEBUG
const bool enableValidationLayers = true; const bool enableValidationLayers = true;
#else #else
@@ -170,9 +258,25 @@ namespace vapp{
#endif #endif
bool framebufferResized = false; bool framebufferResized = false;
std::string MODEL_PATH;
std::string TEXTURE_PATH;
VkSampleCountFlagBits msaaSamples = VK_SAMPLE_COUNT_1_BIT;
#pragma endregion
#pragma region PublicFunctions
void run(const char *windowName, const uint32_t width = 800, const uint32_t height = 600); void run(const char *windowName, const uint32_t width = 800, const uint32_t height = 600);
#pragma endregion
}; };
} // vapp } // vapp
namespace std{
template<> struct hash<vapp::Vertex>{
size_t operator()(vapp::Vertex const &vertex) const{
return ((hash<glm::vec3>()(vertex.pos) ^
(hash<glm::vec3>()(vertex.color) << 1)) >> 1) ^
(hash<glm::vec2>()(vertex.texCoord) << 1);
}
};
}
#endif //VULKAN_APP_H #endif //VULKAN_APP_H