From 6bc2ea165086419e7549c6a253218bb34105b743 Mon Sep 17 00:00:00 2001 From: Ano-sys Date: Fri, 4 Jul 2025 00:55:50 +0200 Subject: [PATCH] Added camera --- CMakeLists.txt | 4 + camera/camera.cpp | 2 + camera/camera.hpp | 71 +++++++++++ main.cpp | 5 +- vulkan/vulkan_app.cpp | 222 ++++++++++++++++++++-------------- vulkan/vulkan_app.hpp | 79 +++++------- vulkan/vulkan_glfw_events.cpp | 152 +++++++---------------- 7 files changed, 285 insertions(+), 250 deletions(-) create mode 100644 camera/camera.cpp create mode 100644 camera/camera.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c326c0..aa15972 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,10 @@ if(NOT GLSLC) message(FATAL_ERROR "glslc compiler not found. Please install the Vulkan SDK.") endif() +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/textures) +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/models) +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/shaders) + # Copy textures into cmake output file(GLOB TEXTURE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/textures/*" diff --git a/camera/camera.cpp b/camera/camera.cpp new file mode 100644 index 0000000..3003faa --- /dev/null +++ b/camera/camera.cpp @@ -0,0 +1,2 @@ +// Camera.cpp +#include "camera.hpp" diff --git a/camera/camera.hpp b/camera/camera.hpp new file mode 100644 index 0000000..5ca154e --- /dev/null +++ b/camera/camera.hpp @@ -0,0 +1,71 @@ +// Camera.hpp +#pragma once +#include +#include + +namespace vapp{ + enum Camera_Movement{ + FORWARD, + BACKWARD, + LEFT, + RIGHT, + UP, + DOWN, + }; + + class Camera{ + public: + float Yaw = -90.0f, Pitch = 0.0f; + float MovementSpeed = 2.5f; + float MouseSensitivity = 0.1f; + float Zoom = 45.0f; + + glm::vec3 Position, Front, Up, Right, WorldUp; + + Camera(glm::vec3 pos = {0, 0, 3}, glm::vec3 up = {0, 1, 0}) + : Position(pos), WorldUp(up), Front({0, 0, -1}){ updateCameraVectors(); } + + glm::mat4 GetViewMatrix(){ + return glm::lookAt(Position, Position + Front, Up); + } + + void ProcessKeyboard(Camera_Movement dir, float dt){ + float v = MovementSpeed * dt; + if(dir == FORWARD) Position += Front * v; + if(dir == BACKWARD) Position -= Front * v; + if(dir == LEFT) Position -= Right * v; + if(dir == RIGHT) Position += Right * v; + if(dir == UP) Position += Up * v; + if(dir == DOWN) Position -= Up * v; + } + + void ProcessMouseMovement(float xoff, float yoff, bool constrainPitch = true){ + xoff *= MouseSensitivity; + yoff *= MouseSensitivity; + Yaw += xoff; + Pitch += yoff; + if(constrainPitch){ + if(Pitch > 89.0f) Pitch = 89.0f; + if(Pitch < -89.0f) Pitch = -89.0f; + } + updateCameraVectors(); + } + + void ProcessMouseScroll(float yoff){ + Zoom -= yoff; + if(Zoom < 1.0f) Zoom = 1.0f; + if(Zoom > 45.0f) Zoom = 45.0f; + } + + private: + void updateCameraVectors(){ + glm::vec3 f; + f.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch)); + f.y = sin(glm::radians(Pitch)); + f.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch)); + Front = glm::normalize(f); + Right = glm::normalize(glm::cross(Front, WorldUp)); + Up = glm::normalize(glm::cross(Right, Front)); + } + }; +} diff --git a/main.cpp b/main.cpp index bd01b26..a7d3e32 100644 --- a/main.cpp +++ b/main.cpp @@ -16,6 +16,9 @@ int main(int argc, char **argv){ try{ vapp::Vulkan app; + // app.MODEL_PATH = "models/SMG_Observatory/objects/AstroBaseA.obj"; + // app.TEXTURE_PATH = "models/SMG_Observatory/objects/AstroBaseA.png"; + app.MODEL_PATH = "models/viking_room.obj"; app.TEXTURE_PATH = "textures/viking_room.png"; @@ -27,4 +30,4 @@ int main(int argc, char **argv){ } return EXIT_SUCCESS; -} \ No newline at end of file +} diff --git a/vulkan/vulkan_app.cpp b/vulkan/vulkan_app.cpp index dd6f295..1724f70 100644 --- a/vulkan/vulkan_app.cpp +++ b/vulkan/vulkan_app.cpp @@ -20,12 +20,17 @@ namespace vapp{ VK_KHR_SWAPCHAIN_EXTENSION_NAME, }; - static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, void *pUserData){ + static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, + void *pUserData){ std::cerr << "Validation Layer: " << pCallbackData->pMessage << std::endl; return VK_FALSE; } - VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pDebugMessenger){ + VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, + const VkAllocationCallbacks *pAllocator, + VkDebugUtilsMessengerEXT *pDebugMessenger){ auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr( instance, "vkCreateDebugUtilsMessengerEXT"); if(func == nullptr) return VK_ERROR_EXTENSION_NOT_PRESENT; @@ -33,7 +38,8 @@ namespace vapp{ return func(instance, pCreateInfo, pAllocator, pDebugMessenger); } - void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks *pAllocator){ + void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, + const VkAllocationCallbacks *pAllocator){ if(auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr( instance, "vkDestroyDebugUtilsMessengerEXT"); func != nullptr){ func(instance, debugMessenger, pAllocator); @@ -101,19 +107,18 @@ namespace vapp{ return extensions; } - VkSampleCountFlagBits Vulkan::getMaxUsableSampleCount() - { + 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; + 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; } @@ -367,7 +372,7 @@ namespace vapp{ actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width); actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, - capabilities.maxImageExtent.height); + capabilities.maxImageExtent.height); return actualExtent; } @@ -431,7 +436,8 @@ namespace vapp{ swapChainImageViews.resize(swapChainImages.size()); for(uint32_t i = 0; i < swapChainImages.size(); i++){ - swapChainImageViews[i] = createImageView(swapChainImages[i], swapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT, 1); + swapChainImageViews[i] = createImageView(swapChainImages[i], swapChainImageFormat, + VK_IMAGE_ASPECT_COLOR_BIT, 1); } } @@ -449,7 +455,7 @@ namespace vapp{ samplerLayoutBinding.pImmutableSamplers = nullptr; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; - std::array bindings = { uboLayoutBinding, samplerLayoutBinding }; + std::array bindings = {uboLayoutBinding, samplerLayoutBinding}; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; @@ -457,7 +463,8 @@ namespace vapp{ 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"); + throw std::runtime_error( + "Func: createDescriptorSetLayout\nError: Failed to create Descriptor Set Layout!\n"); } } @@ -468,7 +475,7 @@ namespace vapp{ vertShaderCode = readFile("shaders/shader.vert.spv"); fragShaderCode = readFile("shaders/shader.frag.spv"); } - catch(const std::exception &e){ + catch(const std::exception& e){ std::cout << "Failed to read ./shaders/...\nTrying fallback folders!\n"; vertShaderCode = readFile("../shaders/shader.vert.spv"); fragShaderCode = readFile("../shaders/shader.frag.spv"); @@ -697,12 +704,14 @@ namespace vapp{ VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; - dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; + dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT; dependency.srcAccessMask = 0; - dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_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 | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;; - std::array attachments = { colorAttachment, depthAttachment, colorAttachmentResolve }; + std::array attachments = {colorAttachment, depthAttachment, colorAttachmentResolve}; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; @@ -722,7 +731,7 @@ namespace vapp{ swapChainFramebuffers.resize(swapChainImageViews.size()); for(size_t i = 0; i < swapChainImageViews.size(); i++){ - std::array attachments = { colorImageView, depthImageView, swapChainImageViews[i] }; + std::array attachments = {colorImageView, depthImageView, swapChainImageViews[i]}; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; @@ -751,7 +760,8 @@ namespace vapp{ } } - VkFormat Vulkan::findSupportedFormat(const std::vector &candidates, VkImageTiling tiling, VkFormatFeatureFlags features){ + VkFormat Vulkan::findSupportedFormat(const std::vector& candidates, VkImageTiling tiling, + VkFormatFeatureFlags features){ for(VkFormat format : candidates){ VkFormatProperties props; vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &props); @@ -768,27 +778,30 @@ namespace vapp{ 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 - ); + {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() - { + 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); + 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); + 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); } @@ -834,7 +847,8 @@ namespace vapp{ endSingleTimeCommands(commandBuffer); } - void Vulkan::transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels){ + void Vulkan::transitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout, + uint32_t mipLevels){ VkCommandBuffer commandBuffer = beginSingleTimeCommands(); VkImageMemoryBarrier barrier{}; @@ -863,7 +877,8 @@ namespace vapp{ 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){ + 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; @@ -891,14 +906,16 @@ namespace vapp{ region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; - region.imageOffset = { 0, 0, 0 }; - region.imageExtent = { width, height, 1 }; + region.imageOffset = {0, 0, 0}; + region.imageExtent = {width, height, 1}; vkCmdCopyBufferToImage(commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); 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){ + 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 @@ -908,7 +925,8 @@ namespace vapp{ 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.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; @@ -934,14 +952,15 @@ namespace vapp{ vkBindImageMemory(device, image, imageMemory, 0); } - void Vulkan::generateMipmaps(VkImage image, VkFormat imageFormat, int32_t texWidth, int32_t texHeight, uint32_t mipLevels){ + 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"); + 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(); @@ -959,42 +978,44 @@ namespace vapp{ int32_t mipWidth = texWidth; int32_t mipHeight = texHeight; - for (uint32_t i = 1; i < mipLevels; i++) - { + 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); + 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.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.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); + 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); + 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; + if(mipWidth > 1) mipWidth /= 2; + if(mipHeight > 1) mipHeight /= 2; } barrier.subresourceRange.baseMipLevel = mipLevels - 1; @@ -1003,7 +1024,8 @@ namespace vapp{ 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); + vkCmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, + nullptr, 0, nullptr, 1, &barrier); endSingleTimeCommands(commandBuffer); } @@ -1012,7 +1034,8 @@ namespace vapp{ 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"); + 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); @@ -1025,7 +1048,9 @@ namespace vapp{ 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); + 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); @@ -1034,9 +1059,14 @@ namespace vapp{ 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(texWidth), static_cast(texHeight)); + 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(texWidth), + static_cast(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); @@ -1045,7 +1075,8 @@ namespace vapp{ generateMipmaps(textureImage, VK_FORMAT_R8G8B8A8_SRGB, texWidth, texHeight, mipLevels); } - VkImageView Vulkan::createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags, uint32_t 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; @@ -1106,13 +1137,15 @@ namespace vapp{ VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); for(uint32_t i = 0; i < memProperties.memoryTypeCount; i++){ - if(typeFilter & (1 << i) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) return i; + if(typeFilter & (1 << i) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) return + i; } throw std::runtime_error("Func: findMemoryType\nError: Failed to find suitable memory type!\n"); } - void Vulkan::createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer &buffer, VkDeviceMemory &bufferMemory){ + void Vulkan::createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, + VkBuffer& buffer, VkDeviceMemory& bufferMemory){ VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; @@ -1185,8 +1218,8 @@ namespace vapp{ std::unordered_map uniqueVertices{}; - for(const auto &shape : shapes){ - for(const auto &index : shape.mesh.indices){ + for(const auto& shape : shapes){ + for(const auto& index : shape.mesh.indices){ Vertex vertex{}; vertex.pos = { @@ -1200,7 +1233,7 @@ namespace vapp{ 1.0f - attrib.texcoords[2 * index.texcoord_index + 1], }; - vertex.color = { 1.0f, 1.0f, 1.0f }; + vertex.color = {1.0f, 1.0f, 1.0f}; if(!uniqueVertices.contains(vertex)){ @@ -1220,14 +1253,17 @@ namespace vapp{ 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); + createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, + stagingBufferMemory); void *data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); - createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); + createBuffer(bufferSize, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); copyBuffer(stagingBuffer, vertexBuffer, bufferSize); @@ -1241,14 +1277,17 @@ namespace vapp{ 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); + 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); + 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); @@ -1264,7 +1303,9 @@ namespace vapp{ 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]); + 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]); } } @@ -1330,7 +1371,8 @@ namespace vapp{ descriptorWrites[1].descriptorCount = 1; descriptorWrites[1].pImageInfo = &imageInfo; - vkUpdateDescriptorSets(device, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); + vkUpdateDescriptorSets(device, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, + nullptr); } } @@ -1365,7 +1407,7 @@ namespace vapp{ std::array clearValues{}; clearValues[0].color = {{0.01f, 0.01f, 0.01f, 1.0f}}; // Background color after clear (Black 100%) - clearValues[1].depthStencil = { 1.0f, 0 }; + clearValues[1].depthStencil = {1.0f, 0}; renderPassInfo.clearValueCount = static_cast(clearValues.size()); renderPassInfo.pClearValues = clearValues.data(); @@ -1373,8 +1415,8 @@ namespace vapp{ vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline); - VkBuffer vertexBuffers[] = { vertexBuffer }; - VkDeviceSize offsets[] = { 0 }; + VkBuffer vertexBuffers[] = {vertexBuffer}; + VkDeviceSize offsets[] = {0}; vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(commandBuffer, indexBuffer, 0, VK_INDEX_TYPE_UINT32); @@ -1393,7 +1435,8 @@ namespace vapp{ scissor.extent = swapChainExtent; vkCmdSetScissor(commandBuffer, 0, 1, &scissor); - vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSets[currentFrame], 0, nullptr); + vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, + &descriptorSets[currentFrame], 0, nullptr); // vkCmdDraw(commandBuffer, static_cast(vertices.size()), 1, 0, 0); // -> goto indexed draw @@ -1438,8 +1481,8 @@ namespace vapp{ UniformBufferObject ubo{}; // INFO: Change here for other angles ubo.model = glm::rotate(glm::mat4(1.0f), time * glm::radians(0.0f), glm::vec3(0.0f, 0.0f, 1.0f)); - ubo.view = glm::lookAt(cameraPos, cameraFront, cameraUp); - ubo.proj = glm::perspective(glm::radians(45.0f), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f); + ubo.view = camera.GetViewMatrix(); // glm::lookAt(cameraPos, cameraFront, cameraUp); + ubo.proj = glm::perspective(glm::radians(camera.Zoom), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f); // removing this line results in the image rendering upside down ubo.proj[1][1] *= -1; @@ -1452,7 +1495,8 @@ namespace vapp{ vkResetFences(device, 1, &inFlightFences[currentFrame]); uint32_t imageIndex; - VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); + VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], + VK_NULL_HANDLE, &imageIndex); // INFO: is this right here? // vkResetFences(device, 1, &inFlightFences[currentFrame]); @@ -1514,10 +1558,12 @@ namespace vapp{ vkDestroyImage(device, depthImage, nullptr); vkFreeMemory(device, depthImageMemory, nullptr); - for(const auto & swapChainFramebuffer : swapChainFramebuffers) - { vkDestroyFramebuffer(device, swapChainFramebuffer, nullptr); } - for(const auto & swapChainImageView : swapChainImageViews) - { vkDestroyImageView(device, swapChainImageView, nullptr); } + for(const auto& swapChainFramebuffer : swapChainFramebuffers){ + vkDestroyFramebuffer(device, swapChainFramebuffer, nullptr); + } + for(const auto& swapChainImageView : swapChainImageViews){ + vkDestroyImageView(device, swapChainImageView, nullptr); + } vkDestroySwapchainKHR(device, swapChain, nullptr); } @@ -1545,23 +1591,19 @@ namespace vapp{ app->framebufferResized = true; } - static void handleMouseInputCallback(GLFWwindow* window, double xpos, double ypos) { - Vulkan* vulkan = static_cast(glfwGetWindowUserPointer(window)); - if (vulkan) { - vulkan->handleMouseInput(window, xpos, ypos); - } - } - void Vulkan::initWindow(const char *windowName){ glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // tell glfw to not use opengl glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // disable window resize - this->window = glfwCreateWindow(static_cast(_width), static_cast(_height), windowName, nullptr, nullptr); + this->window = glfwCreateWindow(static_cast(_width), static_cast(_height), windowName, nullptr, + nullptr); glfwSetWindowUserPointer(window, this); glfwSetFramebufferSizeCallback(window, framebufferResizeCallback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); - glfwSetCursorPosCallback(window, handleMouseInputCallback); + glfwSetCursorPosCallback(window, mouseCallback); + glfwSetScrollCallback(window, scrollCallback); + glfwSetKeyCallback(window, keyCallback); } void Vulkan::initVulkan(){ @@ -1597,7 +1639,7 @@ namespace vapp{ // glfwSwapBuffers(window); glfwPollEvents(); - handleKeyboardInput(); + processInput(); drawFrame(); } @@ -1650,7 +1692,7 @@ namespace vapp{ vkDestroySurfaceKHR(instance, surface, nullptr); vkDestroyInstance(instance, nullptr); - + // GLFW glfwDestroyWindow(this->window); glfwTerminate(); diff --git a/vulkan/vulkan_app.hpp b/vulkan/vulkan_app.hpp index 40c4b35..8a411f6 100644 --- a/vulkan/vulkan_app.hpp +++ b/vulkan/vulkan_app.hpp @@ -27,35 +27,18 @@ #include #include -namespace vapp -{ - class Camera - { - private: - glm::mat4 projectionMatrix{1.f}; - glm::mat4 viewMatrix{1.f}; - - public: - void setOthographicProjection(float left, float right, float bottom, float top); - void setPerspectiveProjection(float fovy, float aspect, float zNear, float zFar); - void setViewDirection(glm::vec3 position, glm::vec3 direction, glm::vec3 up); - void setViewTarget(glm::vec3 position, glm::vec3 target, glm::vec3 up); - void setViewYXZ(glm::vec3 position, glm::vec3 rotation); - const glm::mat4& getProjectionMatrix(); - const glm::mat4& getViewMatrix(); - }; +#include "../camera/camera.hpp" +namespace vapp{ // Change here for other presentMode const VkPresentModeKHR WISHED_PRESENT_MODE = VK_PRESENT_MODE_MAILBOX_KHR; - struct Vertex - { + struct Vertex{ glm::vec3 pos; glm::vec3 color; glm::vec2 texCoord; - static VkVertexInputBindingDescription getBindingDescription() - { + static VkVertexInputBindingDescription getBindingDescription(){ VkVertexInputBindingDescription bindingDescription{}; bindingDescription.binding = 0; @@ -65,8 +48,7 @@ namespace vapp return bindingDescription; } - static std::array getAttributeDescriptions() - { + static std::array getAttributeDescriptions(){ std::array attributeDescriptions{}; attributeDescriptions[0].binding = 0; @@ -87,8 +69,7 @@ namespace vapp return attributeDescriptions; } - bool operator==(const Vertex& other) const - { + bool operator==(const Vertex& other) const{ return pos == other.pos && color == other.color && texCoord == other.texCoord; } }; @@ -114,26 +95,22 @@ namespace vapp */ // END Remove - struct UniformBufferObject - { + struct UniformBufferObject{ alignas(16) glm::mat4 model; alignas(16) glm::mat4 view; alignas(16) glm::mat4 proj; }; - struct QueueFamilyIndices - { + struct QueueFamilyIndices{ std::optional graphicsFamily; std::optional presentFamily; - bool isComplete() - { + bool isComplete(){ return graphicsFamily.has_value(); } }; - struct SwapChainSupportDetails - { + struct SwapChainSupportDetails{ VkSurfaceCapabilitiesKHR capabilities; std::vector formats; std::vector presentModes; @@ -143,11 +120,10 @@ namespace vapp static std::array getAttributeDescription(); - class Vulkan - { + class Vulkan{ private: #pragma region PrivateFields - GLFWwindow* window; + GLFWwindow *window; uint32_t _width, _height; VkInstance instance; @@ -213,6 +189,14 @@ namespace vapp VkImage colorImage; VkDeviceMemory colorImageMemory; VkImageView colorImageView; + +#pragma region GLFWFunctions + static void mouseCallback(GLFWwindow *win, double xpos, double ypos); + static void scrollCallback(GLFWwindow *win, double xoffset, double yoffset); + void processInput(); + static void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods); +#pragma endregion + #pragma endregion #pragma region PrivateFunctions bool checkValidationLayerSupport(); @@ -276,7 +260,7 @@ namespace vapp void drawFrame(); void cleanupSwapChain(); void recreateSwapChain(); - void initWindow(const char* windowName); + void initWindow(const char *windowName); void initVulkan(); void mainLoop(); void cleanup(); @@ -296,11 +280,12 @@ namespace vapp VkSampleCountFlagBits msaaSamples = VK_SAMPLE_COUNT_1_BIT; + Camera camera; float yaw = -90.0f; float pitch = 0.0f; - float lastX = 400.0f; - float lastY = 300.0f; + float lastX = 0.0f, lastY = 0.0f; bool firstMouse = true; + float deltaTime = 0.0f, lastFrame = 0.0f; glm::vec3 cameraPos = glm::vec3(2.0f, 2.0f, 2.0f); glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, 0.0f); @@ -308,23 +293,15 @@ namespace vapp #pragma endregion #pragma region PublicFunctions - void run(const char* windowName, const uint32_t width = 800, const uint32_t height = 600); -#pragma endregion - -#pragma region GLFWFunctions - void handleKeyboardInput(); - void handleMouseInput(GLFWwindow* window, double xpos, double ypos); + void run(const char *windowName, const uint32_t width = 800, const uint32_t height = 600); #pragma endregion }; } // vapp -namespace std -{ +namespace std{ template <> - struct hash - { - size_t operator()(vapp::Vertex const& vertex) const - { + struct hash{ + size_t operator()(vapp::Vertex const& vertex) const{ return ((hash()(vertex.pos) ^ (hash()(vertex.color) << 1)) >> 1) ^ (hash()(vertex.texCoord) << 1); diff --git a/vulkan/vulkan_glfw_events.cpp b/vulkan/vulkan_glfw_events.cpp index 95c92e9..3d8dc5b 100644 --- a/vulkan/vulkan_glfw_events.cpp +++ b/vulkan/vulkan_glfw_events.cpp @@ -1,115 +1,51 @@ #include "vulkan_app.hpp" namespace vapp{ + void Vulkan::processInput(){ + float currentFrame = static_cast(glfwGetTime()); + deltaTime = currentFrame - lastFrame; + lastFrame = currentFrame; - void Camera::setOthographicProjection(float left, float right, float bottom, float top){ - - } - - void Camera::setPerspectiveProjection(float fovy, float aspect, float zNear, float zFar){ - - } - - void Camera::setViewDirection(glm::vec3 position, glm::vec3 direction, glm::vec3 up) { - const glm::vec3 w{glm::normalize(direction)}; - const glm::vec3 u{glm::normalize(glm::cross(w, up))}; - const glm::vec3 v{glm::cross(w, u)}; - - viewMatrix = glm::mat4{1.f}; - viewMatrix[0][0] = u.x; - viewMatrix[1][0] = u.y; - viewMatrix[2][0] = u.z; - viewMatrix[0][1] = v.x; - viewMatrix[1][1] = v.y; - viewMatrix[2][1] = v.z; - viewMatrix[0][2] = w.x; - viewMatrix[1][2] = w.y; - viewMatrix[2][2] = w.z; - viewMatrix[3][0] = -glm::dot(u, position); - viewMatrix[3][1] = -glm::dot(v, position); - viewMatrix[3][2] = -glm::dot(w, position); - } - - void Camera::setViewTarget(glm::vec3 position, glm::vec3 target, glm::vec3 up) { - setViewDirection(position, target - position, up); - } - - void Camera::setViewYXZ(glm::vec3 position, glm::vec3 rotation) { - const float c3 = glm::cos(rotation.z); - const float s3 = glm::sin(rotation.z); - const float c2 = glm::cos(rotation.x); - const float s2 = glm::sin(rotation.x); - const float c1 = glm::cos(rotation.y); - const float s1 = glm::sin(rotation.y); - const glm::vec3 u{(c1 * c3 + s1 * s2 * s3), (c2 * s3), (c1 * s2 * s3 - c3 * s1)}; - const glm::vec3 v{(c3 * s1 * s2 - c1 * s3), (c2 * c3), (c1 * c3 * s2 + s1 * s3)}; - const glm::vec3 w{(c2 * s1), (-s2), (c1 * c2)}; - viewMatrix = glm::mat4{1.f}; - viewMatrix[0][0] = u.x; - viewMatrix[1][0] = u.y; - viewMatrix[2][0] = u.z; - viewMatrix[0][1] = v.x; - viewMatrix[1][1] = v.y; - viewMatrix[2][1] = v.z; - viewMatrix[0][2] = w.x; - viewMatrix[1][2] = w.y; - viewMatrix[2][2] = w.z; - viewMatrix[3][0] = -glm::dot(u, position); - viewMatrix[3][1] = -glm::dot(v, position); - viewMatrix[3][2] = -glm::dot(w, position); - } - - void Vulkan::handleKeyboardInput(){ - if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){ - cameraPos.x += 0.001f; - } - if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){ - cameraPos.x -= 0.001f; - } - if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){ - cameraPos.y -= 0.001f; - } - if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){ - cameraPos.y += 0.001f; - } - if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){ - cameraPos.x += 0.001f; - } - if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){ - cameraPos.x -= 0.001f; - } - if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS){ - cameraPos.z += 0.001f; - } - if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS){ - cameraPos.z -= 0.001f; - } + if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) + camera.ProcessKeyboard(FORWARD, deltaTime); + if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) + camera.ProcessKeyboard(BACKWARD, deltaTime); + if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) + camera.ProcessKeyboard(LEFT, deltaTime); + if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) + camera.ProcessKeyboard(RIGHT, deltaTime); + if(glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) + camera.ProcessKeyboard(UP, deltaTime); + if(glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) + camera.ProcessKeyboard(DOWN, deltaTime); } - void Vulkan::handleMouseInput(GLFWwindow* window, double xpos, double ypos){ - double xoffset = xpos - (_width / 2.0); - double yoffset = ypos - (_height / 2.0); - - glfwSetCursorPos(window, _width / 2.0, _height / 2.0); - - float sensitivity = 0.001f; - xoffset *= sensitivity; - yoffset *= sensitivity; - - yaw += xoffset; - pitch += yoffset; - - if(pitch > 89.0f) - pitch = 89.0f; - if(pitch < -89.0f) - pitch = -89.0f; - - glm::vec3 direction; - direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch)); - direction.y = sin(glm::radians(pitch)); - direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch)); - direction = glm::normalize(direction); - - cameraFront = cameraPos + direction; + void Vulkan::keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods){ + Vulkan *app = static_cast(glfwGetWindowUserPointer(window)); + if(key == GLFW_KEY_LEFT_SHIFT){ + if(action == GLFW_PRESS) + app->camera.MovementSpeed = 5.0f; + else if(action == GLFW_RELEASE) + app->camera.MovementSpeed = 2.5f; + } } -} \ No newline at end of file + + void Vulkan::mouseCallback(GLFWwindow *window, double xpos, double ypos){ + auto app = static_cast(glfwGetWindowUserPointer(window)); + if(app->firstMouse){ + app->lastX = xpos; + app->lastY = ypos; + app->firstMouse = false; + } + float xoff = xpos - app->lastX; + float yoff = app->lastY - ypos; + app->lastX = xpos; + app->lastY = ypos; + app->camera.ProcessMouseMovement(xoff, yoff); + } + + void Vulkan::scrollCallback(GLFWwindow *window, double /*x*/, double yoffset){ + Vulkan *app = static_cast(glfwGetWindowUserPointer(window)); + app->camera.ProcessMouseScroll(static_cast(yoffset)); + } +}