diff --git a/.gitignore b/.gitignore index d2bf98a016f588760241f9dc7f90f6197c458404..7ee4ff1903e902c4715c6e2b0c3e784ed5755aaf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,3 @@ -<<<<<<< HEAD -======= - ->>>>>>> develop # IDE specific files .project .cproject @@ -19,3 +15,6 @@ cmake-build-release/ *.exe *.ilk *.pdb + +# GUI configuration files +imgui.ini diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 318f3e931e557421a5e9275735174cdee7947453..33b70018e368ecc3ad019ea33e57485814eb233a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -14,7 +14,7 @@ build_ubuntu_gcc: - $RUN =~ /\bubuntu.*/i || $RUN =~ /\ball.*/i stage: build tags: - - ubuntu-gcc + - ubuntu-gcc-cached variables: GIT_SUBMODULE_STRATEGY: recursive timeout: 10m @@ -37,11 +37,11 @@ build_win10_msvc: - $RUN =~ /\bwin.*/i || $RUN =~ /\ball.*/i stage: build tags: - - win10-msvc + - win10-msvc-cached variables: GIT_SUBMODULE_STRATEGY: recursive timeout: 10m - retry: 1 + retry: 0 script: - cd 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\' - .\Launch-VsDevShell.ps1 diff --git a/.gitmodules b/.gitmodules index 983b753744e8767da0ec3c959c32a3766ee346f6..e0aaf2d17c340f98ae875f7e0f1238bfe04f7e5d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -15,4 +15,10 @@ url = https://github.com/nothings/stb.git [submodule "modules/camera/lib/glm"] path = modules/camera/lib/glm - url = https://github.com/g-truc/glm.git \ No newline at end of file + url = https://github.com/g-truc/glm.git +[submodule "modules/shader_compiler/lib/glslang"] + path = modules/shader_compiler/lib/glslang + url = https://github.com/KhronosGroup/glslang.git +[submodule "modules/gui/lib/imgui"] + path = modules/gui/lib/imgui + url = https://github.com/ocornut/imgui.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a7f978f81313ecc3a657dd670d2a16db3cd4e8d..bff486150f082c2e96e543436d977cf3112403ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,15 +41,15 @@ if (vkcv_build_debug) endif() endif() +# configure everything to use the required dependencies +include(${vkcv_config}/Libraries.cmake) + # add modules as targets add_subdirectory(modules) # add source files for compilation include(${vkcv_config}/Sources.cmake) -# configure everything to use the required dependencies -include(${vkcv_config}/Libraries.cmake) - message("-- Libraries: [ ${vkcv_libraries} ]") message("-- Flags: [ ${vkcv_flags} ]") diff --git a/config/Sources.cmake b/config/Sources.cmake index a5b2ddae5e0a194e4ee887da5f37097821e41d0f..4397e4978eb022d267571d185a1f122d053a5ea1 100644 --- a/config/Sources.cmake +++ b/config/Sources.cmake @@ -29,15 +29,18 @@ set(vkcv_sources ${vkcv_source}/vkcv/ImageManager.hpp ${vkcv_source}/vkcv/ImageManager.cpp + + ${vkcv_include}/vkcv/Logger.hpp - ${vkcv_include}/vkcv/SwapChain.hpp - ${vkcv_source}/vkcv/SwapChain.cpp - + ${vkcv_include}/vkcv/Swapchain.hpp + ${vkcv_source}/vkcv/Swapchain.cpp + + ${vkcv_include}/vkcv/ShaderStage.hpp + ${vkcv_include}/vkcv/ShaderProgram.hpp ${vkcv_source}/vkcv/ShaderProgram.cpp ${vkcv_include}/vkcv/PipelineConfig.hpp - ${vkcv_source}/vkcv/PipelineConfig.cpp ${vkcv_source}/vkcv/PipelineManager.hpp ${vkcv_source}/vkcv/PipelineManager.cpp diff --git a/config/lib/SPIRV_Cross.cmake b/config/lib/SPIRV_Cross.cmake index 751ee883c47e0eab081a13e5805ced6f2daa7e30..2e705d7d5a006e3851d14d22a57fd667c61c79f5 100644 --- a/config/lib/SPIRV_Cross.cmake +++ b/config/lib/SPIRV_Cross.cmake @@ -6,9 +6,20 @@ if (spirv-cross_FOUND) message(${vkcv_config_msg} " SPIRV Cross - " ${SPIRV_CROSS_VERSION}) else() if (EXISTS "${vkcv_lib_path}/SPIRV-Cross") + set(SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS OFF CACHE INTERNAL "") + set(SPIRV_CROSS_SHARED OFF CACHE INTERNAL "") + set(SPIRV_CROSS_STATIC ON CACHE INTERNAL "") set(SPIRV_CROSS_CLI OFF CACHE INTERNAL "") set(SPIRV_CROSS_ENABLE_TESTS OFF CACHE INTERNAL "") + + set(SPIRV_CROSS_ENABLE_GLSL ON CACHE INTERNAL "") + set(SPIRV_CROSS_ENABLE_HLSL OFF CACHE INTERNAL "") + set(SPIRV_CROSS_ENABLE_MSL OFF CACHE INTERNAL "") + set(SPIRV_CROSS_ENABLE_CPP ON CACHE INTERNAL "") + set(SPIRV_CROSS_ENABLE_REFLECT OFF CACHE INTERNAL "") set(SPIRV_CROSS_ENABLE_C_API OFF CACHE INTERNAL "") + set(SPIRV_CROSS_ENABLE_UTIL OFF CACHE INTERNAL "") + set(SPIRV_CROSS_SKIP_INSTALL ON CACHE INTERNAL "") add_subdirectory(${vkcv_lib}/SPIRV-Cross) diff --git a/include/vkcv/Core.hpp b/include/vkcv/Core.hpp index 8a165adf43561b1204490a12afa00d2a3fabdbf4..bf9514d5ba4c9d5dbf8d41be2a489dae826886a8 100644 --- a/include/vkcv/Core.hpp +++ b/include/vkcv/Core.hpp @@ -8,7 +8,7 @@ #include <vulkan/vulkan.hpp> #include "vkcv/Context.hpp" -#include "vkcv/SwapChain.hpp" +#include "vkcv/Swapchain.hpp" #include "vkcv/Window.hpp" #include "vkcv/PassConfig.hpp" #include "vkcv/Handles.hpp" @@ -41,6 +41,7 @@ namespace vkcv QueueType queueType; std::vector<vk::Semaphore> waitSemaphores; std::vector<vk::Semaphore> signalSemaphores; + vk::Fence fence; }; class Core final @@ -52,7 +53,7 @@ namespace vkcv * * @param context encapsulates various Vulkan objects */ - Core(Context &&context, Window &window, const SwapChain& swapChain, std::vector<vk::ImageView> imageViews, + Core(Context &&context, Window &window, const Swapchain& swapChain, std::vector<vk::ImageView> imageViews, const CommandResources& commandResources, const SyncResources& syncResources) noexcept; // explicit destruction of default constructor Core() = delete; @@ -61,11 +62,11 @@ namespace vkcv Context m_Context; - SwapChain m_swapchain; + Swapchain m_swapchain; std::vector<vk::ImageView> m_swapchainImageViews; std::vector<vk::Image> m_swapchainImages; std::vector<vk::ImageLayout> m_swapchainImageLayouts; - const Window& m_window; + Window& m_window; std::unique_ptr<PassManager> m_PassManager; std::unique_ptr<PipelineManager> m_PipelineManager; @@ -78,10 +79,10 @@ namespace vkcv CommandResources m_CommandResources; SyncResources m_SyncResources; uint32_t m_currentSwapchainImageIndex; + + event_handle<int,int> e_resizeHandle; - std::function<void(int, int)> e_resizeHandle; - - static std::vector<vk::ImageView> createImageViews( Context &context, SwapChain& swapChain); + static std::vector<vk::ImageView> createImageViews( Context &context, Swapchain& swapChain); void recordSwapchainImageLayoutTransition(vk::CommandBuffer cmdBuffer, vk::ImageLayout newLayout); @@ -123,6 +124,9 @@ namespace vkcv [[nodiscard]] const Context &getContext() const; + + [[nodiscard]] + const Swapchain& getSwapchain() const; /** * Creates a #Core with given @p applicationName and @p applicationVersion for your application. @@ -157,6 +161,19 @@ namespace vkcv [[nodiscard]] PipelineHandle createGraphicsPipeline(const PipelineConfig &config); + /** + * Creates a basic vulkan compute pipeline using @p shader program and returns it using the @p handle. + * Fixed Functions for pipeline are set with standard values. + * + * @param shader program that hold the compiles compute shader + * @param handle a handle to return the created vulkan handle + * @return True if pipeline creation was successful, False if not + */ + [[nodiscard]] + PipelineHandle createComputePipeline( + const ShaderProgram &config, + const std::vector<vk::DescriptorSetLayout> &descriptorSetLayouts); + /** * Creates a basic vulkan render pass using @p config from the render pass config class and returns it using the @p handle. * Fixed Functions for pipeline are set with standard values. @@ -211,7 +228,7 @@ namespace vkcv */ [[nodiscard]] DescriptorSetHandle createDescriptorSet(const std::vector<DescriptorBinding> &bindings); - void writeResourceDescription(DescriptorSetHandle handle, size_t setIndex, const DescriptorWrites& writes); + void writeDescriptorSet(DescriptorSetHandle handle, const DescriptorWrites& writes); DescriptorSet getDescriptorSet(const DescriptorSetHandle handle) const; @@ -228,13 +245,18 @@ namespace vkcv const std::vector<DrawcallInfo> &drawcalls, const std::vector<ImageHandle> &renderTargets); + void recordComputeDispatchToCmdStream( + CommandStreamHandle cmdStream, + PipelineHandle computePipeline, + const uint32_t dispatchCount[3], + const std::vector<DescriptorSetUsage> &descriptorSetUsages, + const PushConstantData& pushConstantData); + /** * @brief end recording and present image */ void endFrame(); - vk::Format getSwapchainImageFormat(); - /** * Submit a command buffer to any queue of selected type. The recording can be customized by a * custom record-command-function. If the command submission has finished, an optional finish-function @@ -259,5 +281,8 @@ namespace vkcv void submitCommandStream(const CommandStreamHandle handle); void prepareSwapchainImageForPresent(const CommandStreamHandle handle); void prepareImageForSampling(const CommandStreamHandle cmdStream, const ImageHandle image); + + const vk::ImageView& getSwapchainImageView() const; + }; } diff --git a/include/vkcv/DescriptorConfig.hpp b/include/vkcv/DescriptorConfig.hpp index 86c2e20eb37633e4519749bef507161133e57425..c6d0dfd1bc60988afb8b6a9326a8d50d8a4ea32e 100644 --- a/include/vkcv/DescriptorConfig.hpp +++ b/include/vkcv/DescriptorConfig.hpp @@ -1,8 +1,10 @@ #pragma once -#include <vkcv/ShaderProgram.hpp> -#include <vkcv/Handles.hpp> + #include <vulkan/vulkan.hpp> +#include "vkcv/Handles.hpp" +#include "vkcv/ShaderStage.hpp" + namespace vkcv { struct DescriptorSet @@ -33,11 +35,13 @@ namespace vkcv struct DescriptorBinding { DescriptorBinding( + uint32_t bindingID, DescriptorType descriptorType, uint32_t descriptorCount, ShaderStage shaderStage ) noexcept; - + + uint32_t bindingID; DescriptorType descriptorType; uint32_t descriptorCount; ShaderStage shaderStage; diff --git a/include/vkcv/Event.hpp b/include/vkcv/Event.hpp index 0836e836e84ff7dfc4931a7cedd65497bf9a89cf..e324917674cd2e1773ee23a9411ab28f6eb0d684 100644 --- a/include/vkcv/Event.hpp +++ b/include/vkcv/Event.hpp @@ -3,10 +3,18 @@ #include <functional> namespace vkcv { + + template<typename... T> + struct event_handle { + uint32_t id; + }; template<typename... T> struct event_function { typedef std::function<void(T...)> type; + + event_handle<T...> handle; + type callback; }; /** @@ -16,7 +24,8 @@ namespace vkcv { template<typename... T> struct event { private: - std::vector<typename event_function<T...>::type> m_handles; + std::vector< event_function<T...> > m_functions; + uint32_t m_id_counter; public: @@ -25,28 +34,34 @@ namespace vkcv { * @param arguments of the given function */ void operator()(T... arguments) { - for (auto &handle : this->m_handles) { - handle(arguments...); + for (auto &function : this->m_functions) { + function.callback(arguments...); } } /** * adds a function handle to the event to be called - * @param handle of the function + * @param callback of the function + * @return handle of the function */ - typename event_function<T...>::type add(typename event_function<T...>::type handle) { - this->m_handles.push_back(handle); - return handle; + event_handle<T...> add(typename event_function<T...>::type callback) { + event_function<T...> function; + function.handle = { m_id_counter++ }; + function.callback = callback; + this->m_functions.push_back(function); + return function.handle; } /** * removes a function handle of the event * @param handle of the function */ - void remove(typename event_function<T...>::type handle) { - this->m_handles.erase( - remove(this->m_handles.begin(), this->m_handles.end(), handle), - this->m_handles.end() + void remove(event_handle<T...> handle) { + this->m_functions.erase( + std::remove_if(this->m_functions.begin(), this->m_functions.end(), [&handle](auto function){ + return (handle.id == function.handle.id); + }), + this->m_functions.end() ); } diff --git a/include/vkcv/Image.hpp b/include/vkcv/Image.hpp index a1219ce4147ebbb8ae0650da8a87766f8967874b..840650a1d6288922eceff7ba10ee7e71bf88dc22 100644 --- a/include/vkcv/Image.hpp +++ b/include/vkcv/Image.hpp @@ -29,9 +29,6 @@ namespace vkcv { [[nodiscard]] uint32_t getDepth() const; - - [[nodiscard]] - vk::ImageLayout getLayout() const; [[nodiscard]] vkcv::ImageHandle getHandle() const; diff --git a/include/vkcv/Logger.hpp b/include/vkcv/Logger.hpp new file mode 100644 index 0000000000000000000000000000000000000000..251b6b528c45ea509dbfcd0cfb7135b77031f1ac --- /dev/null +++ b/include/vkcv/Logger.hpp @@ -0,0 +1,68 @@ +#pragma once + +#include <iostream> + +namespace vkcv { + + enum class LogLevel { + INFO, + WARNING, + ERROR + }; + + constexpr auto getLogOutput(LogLevel level) { + switch (level) { + case LogLevel::INFO: + return stdout; + default: + return stderr; + } + } + + constexpr const char* getLogName(LogLevel level) { + switch (level) { + case LogLevel::INFO: + return "INFO"; + case LogLevel::WARNING: + return "WARNING"; + case LogLevel::ERROR: + return "ERROR"; + default: + return "UNKNOWN"; + } + } + +#ifndef NDEBUG +#ifndef VKCV_DEBUG_MESSAGE_LEN +#define VKCV_DEBUG_MESSAGE_LEN 1024 +#endif + +#ifdef _MSC_VER +#define __PRETTY_FUNCTION__ __FUNCSIG__ +#endif + +#define vkcv_log(level, ...) { \ + char output_message [ \ + VKCV_DEBUG_MESSAGE_LEN \ + ]; \ + std::snprintf( \ + output_message, \ + VKCV_DEBUG_MESSAGE_LEN, \ + __VA_ARGS__ \ + ); \ + std::fprintf( \ + getLogOutput(level), \ + "[%s]: %s [%s, line %d: %s]\n", \ + vkcv::getLogName(level), \ + output_message, \ + __FILE__, \ + __LINE__, \ + __PRETTY_FUNCTION__ \ + ); \ +} + +#else +#define vkcv_log(level, ...) {} +#endif + +} diff --git a/include/vkcv/PipelineConfig.hpp b/include/vkcv/PipelineConfig.hpp index 7dc6f2200db7efc1abdddab81145daec27540c49..93523128a67d7b9667c342fb7c10203f4b9a43dd 100644 --- a/include/vkcv/PipelineConfig.hpp +++ b/include/vkcv/PipelineConfig.hpp @@ -7,38 +7,20 @@ #include <vector> #include <cstdint> -#include "vkcv/Handles.hpp" +#include "Handles.hpp" #include "ShaderProgram.hpp" -#include <vkcv/VertexLayout.hpp> +#include "VertexLayout.hpp" namespace vkcv { struct PipelineConfig { - /** - * Constructor for the pipeline. Creates a pipeline using @p vertexCode, @p fragmentCode as well as the - * dimensions of the application window @p width and @p height. A handle for the Render Pass is also needed, @p passHandle. - * - * @param shaderProgram shaders of the pipeline - * @param height height of the application window - * @param width width of the application window - * @param passHandle handle for Render Pass - */ - PipelineConfig( - const ShaderProgram& shaderProgram, - uint32_t width, - uint32_t height, - const PassHandle &passHandle, - const std::vector<VertexAttribute> &vertexAttributes, - const std::vector<vk::DescriptorSetLayout> &descriptorLayouts, - bool useDynamicViewport); - - ShaderProgram m_ShaderProgram; - uint32_t m_Height; - uint32_t m_Width; - PassHandle m_PassHandle; - std::vector<VertexAttribute> m_VertexAttributes; - std::vector<vk::DescriptorSetLayout> m_DescriptorLayouts; - bool m_UseDynamicViewport; + ShaderProgram m_ShaderProgram; + uint32_t m_Width; + uint32_t m_Height; + PassHandle m_PassHandle; + VertexLayout m_VertexLayout; + std::vector<vk::DescriptorSetLayout> m_DescriptorLayouts; + bool m_UseDynamicViewport; }; diff --git a/include/vkcv/ShaderProgram.hpp b/include/vkcv/ShaderProgram.hpp index 896f84d3f6cf854e364498643050d2c0db5085e4..78b1f02169fe630427b9f66150e32078d42b7b3f 100644 --- a/include/vkcv/ShaderProgram.hpp +++ b/include/vkcv/ShaderProgram.hpp @@ -8,24 +8,16 @@ #include <unordered_map> #include <fstream> #include <iostream> +#include <algorithm> #include <filesystem> #include <vulkan/vulkan.hpp> #include <spirv_cross.hpp> -#include "vkcv/VertexLayout.hpp" +#include "VertexLayout.hpp" +#include "ShaderStage.hpp" +#include "DescriptorConfig.hpp" namespace vkcv { - enum class ShaderStage - { - VERTEX, - TESS_CONTROL, - TESS_EVAL, - GEOMETRY, - FRAGMENT, - COMPUTE, - ALL - }; - struct Shader { std::vector<char> shaderCode; @@ -56,15 +48,24 @@ namespace vkcv { bool existsShader(ShaderStage shaderStage) const; - void reflectShader(ShaderStage shaderStage); - - const VertexLayout &getVertexLayout() const; + const std::vector<VertexAttachment> &getVertexAttachments() const; size_t getPushConstantSize() const; + const std::vector<std::vector<DescriptorBinding>>& getReflectedDescriptors() const; + private: + /** + * Called after successfully adding a shader to the program. + * Fills vertex input attachments and descriptor sets (if present). + * @param shaderStage the stage to reflect data from + */ + void reflectShader(ShaderStage shaderStage); + std::unordered_map<ShaderStage, Shader> m_Shaders; - VertexLayout m_VertexLayout; + // contains all vertex input attachments used in the vertex buffer + std::vector<VertexAttachment> m_VertexAttachments; + std::vector<std::vector<DescriptorBinding>> m_DescriptorSets; size_t m_pushConstantSize = 0; }; } diff --git a/include/vkcv/ShaderStage.hpp b/include/vkcv/ShaderStage.hpp new file mode 100644 index 0000000000000000000000000000000000000000..dca395bdba82a2f1cb38bb0a25196cfd3dab8019 --- /dev/null +++ b/include/vkcv/ShaderStage.hpp @@ -0,0 +1,15 @@ +#pragma once + +namespace vkcv { + + enum class ShaderStage + { + VERTEX, + TESS_CONTROL, + TESS_EVAL, + GEOMETRY, + FRAGMENT, + COMPUTE + }; + +} diff --git a/include/vkcv/SwapChain.hpp b/include/vkcv/Swapchain.hpp similarity index 83% rename from include/vkcv/SwapChain.hpp rename to include/vkcv/Swapchain.hpp index 089205d1633551b4ad9f11d0bdd5540b2bb61bbb..b75fc5a87156ea56061e41b4b0974928c83ffa28 100644 --- a/include/vkcv/SwapChain.hpp +++ b/include/vkcv/Swapchain.hpp @@ -7,8 +7,9 @@ namespace vkcv { - class SwapChain final { + class Swapchain final { private: + friend class Core; struct Surface { @@ -21,10 +22,10 @@ namespace vkcv Surface m_Surface; vk::SwapchainKHR m_Swapchain; - vk::Format m_SwapchainFormat; - vk::ColorSpaceKHR m_SwapchainColorSpace; - vk::PresentModeKHR m_SwapchainPresentMode; - uint32_t m_SwapchainImageCount; + vk::Format m_Format; + vk::ColorSpaceKHR m_ColorSpace; + vk::PresentModeKHR m_PresentMode; + uint32_t m_ImageCount; vk::Extent2D m_Extent; @@ -39,16 +40,36 @@ namespace vkcv * @param format */ // TODO: - SwapChain(const Surface &surface, + Swapchain(const Surface &surface, vk::SwapchainKHR swapchain, vk::Format format, vk::ColorSpaceKHR colorSpace, vk::PresentModeKHR presentMode, uint32_t imageCount, vk::Extent2D extent) noexcept; + + /** + * TODO + * + * @return + */ + bool shouldUpdateSwapchain() const; + + /** + * TODO + * + * context + * window + */ + void updateSwapchain(const Context &context, const Window &window); + + /** + * + */ + void signalSwapchainRecreation(); public: - SwapChain(const SwapChain& other); + Swapchain(const Swapchain& other); /** * @return The swapchain linked with the #SwapChain class @@ -69,7 +90,7 @@ namespace vkcv * @return gets the chosen swapchain format */ [[nodiscard]] - vk::Format getSwapchainFormat() const; + vk::Format getFormat() const; /** * creates a swap chain object out of the given window and the given context @@ -77,37 +98,17 @@ namespace vkcv * @param context of the application * @return returns an object of swapChain */ - static SwapChain create(const Window &window, const Context &context); + static Swapchain create(const Window &window, const Context &context); /** * Destructor of SwapChain */ - virtual ~SwapChain(); + virtual ~Swapchain(); /** * @return number of images in swapchain */ - uint32_t getImageCount(); - - /** - * TODO - * - * @return - */ - bool shouldUpdateSwapchain() const; - - /** - * TODO - * - * context - * window - */ - void updateSwapchain(const Context &context, const Window &window); - - /** - * - */ - void signalSwapchainRecreation(); + uint32_t getImageCount() const; /** * TODO diff --git a/include/vkcv/VertexLayout.hpp b/include/vkcv/VertexLayout.hpp index ee0ad8ef56d5284af2be4c81b7ea2f0d052d5a6f..0600b99a24a327605e89b2e8ec304c20dbf7ad2e 100644 --- a/include/vkcv/VertexLayout.hpp +++ b/include/vkcv/VertexLayout.hpp @@ -1,29 +1,11 @@ #pragma once -#include <unordered_map> #include <vector> #include <iostream> +#include <string> namespace vkcv{ - - /* With these enums, 0 is reserved to signal uninitialized or invalid data. */ - enum class PrimitiveType : uint32_t { - UNDEFINED = 0, - POSITION = 1, - NORMAL = 2, - TEXCOORD_0 = 3 - }; - /* This struct describes one vertex attribute of a vertex buffer. */ - typedef struct { - PrimitiveType type; // POSITION, NORMAL, ... - uint32_t offset; // offset in bytes - uint32_t length; // length of ... in bytes - uint32_t stride; // stride in bytes - uint16_t componentType; // eg. 5126 for float - uint8_t componentCount; // eg. 3 for vec3 - } VertexAttribute; - - enum class VertexFormat{ + enum class VertexAttachmentFormat{ FLOAT, FLOAT2, FLOAT3, @@ -34,22 +16,51 @@ namespace vkcv{ INT4 }; - uint32_t getFormatSize(VertexFormat format); + uint32_t getFormatSize(VertexAttachmentFormat format); - struct VertexInputAttachment{ - VertexInputAttachment() = delete; - VertexInputAttachment(uint32_t location, uint32_t binding, VertexFormat format, uint32_t offset) noexcept; + struct VertexAttachment{ + friend struct VertexBinding; + /** + * Describes an individual vertex input attribute/attachment. + * @param inputLocation its location in the vertex shader. + * @param name the name referred to in the shader. + * @param format the format (and therefore, the size) this attachment is in. + * The offset is calculated when a collection of attachments forms a binding, hence the friend declaration. + */ + VertexAttachment(uint32_t inputLocation, const std::string &name, VertexAttachmentFormat format) noexcept; + VertexAttachment() = delete; - uint32_t location; - uint32_t binding; - VertexFormat format; - uint32_t offset; + uint32_t inputLocation; + std::string name; + VertexAttachmentFormat format; + uint32_t offset; + }; + + struct VertexBinding{ + /** + * Describes all vertex input attachments _one_ buffer contains to create a vertex buffer binding. + * NOTE: multiple vertex layouts may contain various (mutually exclusive) vertex input attachments + * to form one complete vertex buffer binding! + * @param bindingLocation its entry in the buffers that make up the whole vertex buffer. + * @param attachments the vertex input attachments this specific buffer layout contains. + */ + VertexBinding(uint32_t bindingLocation, const std::vector<VertexAttachment> &attachments) noexcept; + VertexBinding() = delete; + + uint32_t bindingLocation; + uint32_t stride; + std::vector<VertexAttachment> vertexAttachments; }; struct VertexLayout{ + /** + * Describes the complete layout of one vertex, e.g. all of the vertex input attachments used, + * and all of the buffer bindings that refer to the attachments (for when multiple buffers are used). + * @param bindings bindings the complete vertex buffer is comprised of. + */ VertexLayout() noexcept; - VertexLayout(const std::vector<VertexInputAttachment> &inputs) noexcept; - std::unordered_map<uint32_t, VertexInputAttachment> attachmentMap; - uint32_t stride; + VertexLayout(const std::vector<VertexBinding> &bindings) noexcept; + + std::vector<VertexBinding> vertexBindings; }; -} \ No newline at end of file +} diff --git a/include/vkcv/Window.hpp b/include/vkcv/Window.hpp index f71671c935a0a5e17bb517c726d75ffff2973532..51d6e2245a8b588334b38254c05276ee0eb10150 100644 --- a/include/vkcv/Window.hpp +++ b/include/vkcv/Window.hpp @@ -13,16 +13,19 @@ struct GLFWwindow; namespace vkcv { - class Window final { - private: - GLFWwindow *m_window; - - /** + class Window { + protected: + GLFWwindow *m_window; + + /** * * @param GLFWwindow of the class */ - explicit Window(GLFWwindow *window); - + explicit Window(GLFWwindow *window); + + static GLFWwindow* createGLFWWindow(const char *windowTitle, int width, int height, bool resizable); + + private: /** * mouse callback for moving the mouse on the screen * @param[in] window The window that received the event. @@ -58,6 +61,13 @@ namespace vkcv { * @param[in] mods Bit field describing which [modifier keys](@ref mods) were held down. */ static void onKeyEvent(GLFWwindow *callbackWindow, int key, int scancode, int action, int mods); + + /** + * char callback for any typed character + * @param[in] window The window that received the event + * @param[in] c The character that got typed + */ + static void onCharEvent(GLFWwindow *callbackWindow, unsigned int c); public: /** @@ -95,6 +105,7 @@ namespace vkcv { event< double, double > e_mouseScroll; event< int, int > e_resize; event< int, int, int, int > e_key; + event< unsigned int > e_char; /** * returns the current window diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 7647eb04fbcd45180b3b644f32433f384b0af4c3..5edb802b3adf16878c2dec4050d8444278739026 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -2,5 +2,6 @@ # Add new modules here: add_subdirectory(asset_loader) add_subdirectory(camera) -add_subdirectory(material) +add_subdirectory(gui) +add_subdirectory(shader_compiler) add_subdirectory(testing) diff --git a/modules/asset_loader/include/vkcv/asset/asset_loader.hpp b/modules/asset_loader/include/vkcv/asset/asset_loader.hpp index 24687e846ff9eae3275de357331a825f0b4ed2c3..4107d57ee97a6efe0475c6d9dbd80d2603e0afe8 100644 --- a/modules/asset_loader/include/vkcv/asset/asset_loader.hpp +++ b/modules/asset_loader/include/vkcv/asset/asset_loader.hpp @@ -1,16 +1,16 @@ #pragma once /** - * @authors Trevor Hollmann + * @authors Trevor Hollmann, Mara Vogt, Susanne Dötsch * @file include/vkcv/asset/asset_loader.h * @brief Interface of the asset loader module for the vkcv framework. */ #include <string> #include <vector> +#include <array> #include <cstdint> -#include <vkcv/VertexLayout.hpp> -/* These macros define limits of the following structs. Implementations can +/** These macros define limits of the following structs. Implementations can * test against these limits when performing sanity checks. The main constraint * expressed is that of the data type: Material indices are identified by a * uint8_t in the VertexGroup struct, so there can't be more than UINT8_MAX @@ -20,17 +20,18 @@ #define MAX_MATERIALS_PER_MESH UINT8_MAX #define MAX_VERTICES_PER_VERTEX_GROUP UINT32_MAX -/* LOADING MESHES +/** LOADING MESHES * The description of meshes is a hierarchy of structures with the Mesh at the * top. * * Each Mesh has an array of one or more vertex groups (called "primitives" in - * glTF parlance) and an array of zero or more Materials. + * glTF parlance). Specifically, it has an array of indices into an array of + * vertex groups defined by the Scene struct. * * Each vertex group describes a part of the meshes vertices by defining how * they should be rendered (as points, lines, triangles), how many indices and * vertices there are, how the content of the vertex buffer is to be - * interpreted and which material from the Meshes materials array should be + * interpreted and which material from the Scenes materials array should be * used for the surface of the vertices. * As a bonus there is also the axis aligned bounding box of the vertices. * @@ -44,20 +45,99 @@ namespace vkcv::asset { -/* This enum matches modes in fx-gltf, the library returns a standard mode +/** This enum matches modes in fx-gltf, the library returns a standard mode * (TRIANGLES) if no mode is given in the file. */ -enum PrimitiveMode { +enum class PrimitiveMode : uint8_t { POINTS=0, LINES, LINELOOP, LINESTRIP, TRIANGLES, TRIANGLESTRIP, TRIANGLEFAN }; -/* The indices in the index buffer can be of different bit width. */ -enum IndexType { UINT32=0, UINT16=1, UINT8=2 }; +/** The indices in the index buffer can be of different bit width. */ +enum class IndexType : uint8_t { UNDEFINED=0, UINT8=1, UINT16=2, UINT32=3 }; + +typedef struct { + // TODO define struct for samplers (low priority) + // NOTE: glTF defines samplers based on OpenGL, which can not be + // directly translated to Vulkan. Specifically, OpenGL (and glTF) + // define a different set of Min/Mag-filters than Vulkan. +} Sampler; + +/** struct for defining the loaded texture */ typedef struct { - // TODO not yet needed for the first (unlit) triangle + int sampler; // index into the sampler array of the Scene + uint8_t channels; // number of channels + uint16_t w, h; // width and height of the texture + std::vector<uint8_t> data; // binary data of the decoded texture +} Texture; + +/** The asset loader module only supports the PBR-MetallicRoughness model for + * materials.*/ +typedef struct { + uint16_t textureMask; // bit mask with active texture targets + // Indices into the Array.textures array + int baseColor, metalRough, normal, occlusion, emissive; + // Scaling factors for each texture target + struct { float r, g, b, a; } baseColorFactor; + float metallicFactor, roughnessFactor; + float normalScale; + float occlusionStrength; + struct { float r, g, b; } emissiveFactor; } Material; -/* This struct represents one (possibly the only) part of a mesh. There is +/** Flags for the bit-mask in the Material struct. To check if a material has a + * certain texture target, you can use the hasTexture() function below, passing + * the material struct and the enum. */ +enum class PBRTextureTarget { + baseColor=1, metalRough=2, normal=4, occlusion=8, emissive=16 +}; + +/** This macro translates the index of an enum in the defined order to an + * integer with a single bit set in the corresponding place. It is used for + * working with the bitmask of texture targets ("textureMask") in the Material + * struct: + * Material mat = ...; + * if (mat.textureMask & bitflag(PBRTextureTarget::baseColor)) {...} + * However, this logic is also encapsulated in the convenience-function + * materialHasTexture() so users of the asset loader module can avoid direct + * contact with bit-level operations. */ +#define bitflag(ENUM) (0x1u << ((unsigned)(ENUM))) + +/** To signal that a certain texture target is active in a Material struct, its + * bit is set in the textureMask. You can use this function to check that: + * Material mat = ...; + * if (materialHasTexture(&mat, baseColor)) {...} */ +bool materialHasTexture(const Material *const m, const PBRTextureTarget t); + +/** With these enums, 0 is reserved to signal uninitialized or invalid data. */ +enum class PrimitiveType : uint32_t { + UNDEFINED = 0, + POSITION = 1, + NORMAL = 2, + TEXCOORD_0 = 3, + TEXCOORD_1 = 4 +}; + +/** These integer values are used the same way in OpenGL, Vulkan and glTF. This + * enum is not needed for translation, it's only for the programmers + * convenience (easier to read in if/switch statements etc). While this enum + * exists in (almost) the same definition in the fx-gltf library, we want to + * avoid exposing that dependency, thus it is re-defined here. */ +enum class ComponentType : uint16_t { + NONE = 0, INT8 = 5120, UINT8 = 5121, INT16 = 5122, UINT16 = 5123, + UINT32 = 5125, FLOAT32 = 5126 +}; + +/** This struct describes one vertex attribute of a vertex buffer. */ +typedef struct { + PrimitiveType type; // POSITION, NORMAL, ... + uint32_t offset; // offset in bytes + uint32_t length; // length of ... in bytes + uint32_t stride; // stride in bytes + ComponentType componentType; // eg. 5126 for float + uint8_t componentCount; // eg. 3 for vec3 +} VertexAttribute; + +/** This struct represents one (possibly the only) part of a mesh. There is * always one vertexBuffer and zero or one indexBuffer (indexed rendering is * common but not always used). If there is no index buffer, this is indicated * by indexBuffer.data being empty. Each vertex buffer can have one or more @@ -71,38 +151,43 @@ typedef struct { } indexBuffer; struct { std::vector<uint8_t> data; // binary data of the vertex buffer - std::vector<VertexAttribute> attributes; + std::vector<VertexAttribute> attributes; // description of one } vertexBuffer; struct { float x, y, z; } min; // bounding box lower left struct { float x, y, z; } max; // bounding box upper right - uint8_t materialIndex; // index to one of the meshes materials + int materialIndex; // index to one of the materials } VertexGroup; -/* This struct represents a single mesh loaded from a glTF file. It consists of - * at least one VertexVroup and any number of Materials. */ +/** This struct represents a single mesh as it was loaded from a glTF file. It + * consists of at least one VertexGroup, which then references other resources + * such as Materials. */ typedef struct { std::string name; - std::vector<VertexGroup> vertexGroups; - std::vector<Material> materials; - // FIXME Dirty hack to get one(!) texture for our cube demo - // hardcoded to always have RGBA channel layout - struct { - int w, h, ch; // width, height and channels of image - uint8_t *img; // raw bytes, free after use (deal with it) - } texture_hack; + std::array<float, 16> modelMatrix; + std::vector<int> vertexGroups; } Mesh; +/** The scene struct is simply a collection of objects in the scene as well as + * the resources used by those objects. + * For now the only type of object are the meshes and they are represented in a + * flat array. + * Note that parent-child relations are not yet possible. */ +typedef struct { + std::vector<Mesh> meshes; + std::vector<VertexGroup> vertexGroups; + std::vector<Material> materials; + std::vector<Texture> textures; + std::vector<Sampler> samplers; +} Scene; /** - * In its first iteration the asset loader module will only allow loading - * single meshes, one per glTF file. - * It will later be extended to allow loading entire scenes from glTF files. + * Load every mesh from the glTF file, as well as materials and textures. * - * @param path must be the path to a glTF file containing a single mesh. - * @param mesh is a reference to a Mesh struct that will be filled with the + * @param path must be the path to a glTF or glb file. + * @param scene is a reference to a Scene struct that will be filled with the * content of the glTF file being loaded. * */ -int loadMesh(const std::string &path, Mesh &mesh); +int loadScene(const std::string &path, Scene &scene); } diff --git a/modules/asset_loader/src/vkcv/asset/asset_loader.cpp b/modules/asset_loader/src/vkcv/asset/asset_loader.cpp index e660b442d0b9a0208f95c9d753ef19e926bcac44..97fd39515290ac9235b3936d44d3e40a584ef84f 100644 --- a/modules/asset_loader/src/vkcv/asset/asset_loader.cpp +++ b/modules/asset_loader/src/vkcv/asset/asset_loader.cpp @@ -5,7 +5,10 @@ #include <fx/gltf.h> #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_JPEG +#define STBI_ONLY_PNG #include <stb_image.h> +#include <vkcv/Logger.hpp> +#include <algorithm> namespace vkcv::asset { @@ -39,170 +42,328 @@ uint8_t convertTypeToInt(const fx::gltf::Accessor::Type type) { * @param path path to file that is responsible for error */ void print_what (const std::exception& e, const std::string &path) { - fprintf(stderr, "ERROR loading file %s: %s\n", path.c_str(), e.what()); + vkcv_log(LogLevel::ERROR, "Loading file %s: %s", + path.c_str(), e.what()); + try { std::rethrow_if_nested(e); } catch (const std::exception& nested) { - std::cerr << "nested: "; print_what(nested, path); } } -int loadMesh(const std::string &path, Mesh &mesh) { - fx::gltf::Document object; - - try { - if (path.rfind(".glb", (path.length()-4)) != std::string::npos) { - object = fx::gltf::LoadFromBinary(path); - } else { - object = fx::gltf::LoadFromText(path); - } - } catch (const std::system_error &err) { - print_what(err, path); - return 0; - } catch (const std::exception &e) { - print_what(e, path); - return 0; - } - - // TODO Temporary restriction: Only one mesh per glTF file allowed - // currently. Later, we want to support whole scenes with more than - // just meshes. - if (object.meshes.size() != 1) return 0; - - fx::gltf::Mesh const &objectMesh = object.meshes[0]; - // TODO We want to support more than one vertex group per mesh - // eventually... right now this is hard-coded to use only the first one - // because we only care about the example triangle and cube - fx::gltf::Primitive const &objectPrimitive = objectMesh.primitives[0]; - fx::gltf::Accessor posAccessor; - - std::vector<VertexAttribute> vertexAttributes; - vertexAttributes.reserve(objectPrimitive.attributes.size()); - - for (auto const & attrib : objectPrimitive.attributes) { - fx::gltf::Accessor accessor = object.accessors[attrib.second]; - VertexAttribute attribute; - - if (attrib.first == "POSITION") { - attribute.type = PrimitiveType::POSITION; - posAccessor = accessor; - } else if (attrib.first == "NORMAL") { - attribute.type = PrimitiveType::NORMAL; - } else if (attrib.first == "TEXCOORD_0") { - attribute.type = PrimitiveType::TEXCOORD_0; - } else { - return 0; - } - - attribute.offset = object.bufferViews[accessor.bufferView].byteOffset; - attribute.length = object.bufferViews[accessor.bufferView].byteLength; - attribute.stride = object.bufferViews[accessor.bufferView].byteStride; - attribute.componentType = static_cast<uint16_t>(accessor.componentType); - - if (convertTypeToInt(accessor.type) != 10) { - attribute.componentCount = convertTypeToInt(accessor.type); - } else { - return 0; - } - - vertexAttributes.push_back(attribute); - } - - // TODO consider the case where there is no index buffer (not all - // meshes have to use indexed rendering) - const fx::gltf::Accessor &indexAccessor = object.accessors[objectPrimitive.indices]; - const fx::gltf::BufferView &indexBufferView = object.bufferViews[indexAccessor.bufferView]; - const fx::gltf::Buffer &indexBuffer = object.buffers[indexBufferView.buffer]; - - std::vector<uint8_t> indexBufferData; - indexBufferData.resize(indexBufferView.byteLength); - { - const size_t off = indexBufferView.byteOffset; - const void *const ptr = ((char*)indexBuffer.data.data()) + off; - if (!memcpy(indexBufferData.data(), ptr, indexBufferView.byteLength)) { - std::cerr << "ERROR copying index buffer data.\n"; - return 0; - } - } - - const fx::gltf::BufferView& vertexBufferView = object.bufferViews[posAccessor.bufferView]; - const fx::gltf::Buffer& vertexBuffer = object.buffers[vertexBufferView.buffer]; - - // FIXME: This only works when all vertex attributes are in one buffer - std::vector<uint8_t> vertexBufferData; - vertexBufferData.resize(vertexBuffer.byteLength); - { - const size_t off = 0; - const void *const ptr = ((char*)vertexBuffer.data.data()) + off; - if (!memcpy(vertexBufferData.data(), ptr, vertexBuffer.byteLength)) { - std::cerr << "ERROR copying vertex buffer data.\n"; - return 0; - } - } - - IndexType indexType; - switch(indexAccessor.componentType) { +/** Translate the component type used in the index accessor of fx-gltf to our + * enum for index type. The reason we have defined an incompatible enum that + * needs translation is that only a subset of component types is valid for + * indices and we want to catch these incompatibilities here. */ +enum IndexType getIndexType(const enum fx::gltf::Accessor::ComponentType &t) +{ + switch (t) { case fx::gltf::Accessor::ComponentType::UnsignedByte: - indexType = UINT8; break; + return IndexType::UINT8; case fx::gltf::Accessor::ComponentType::UnsignedShort: - indexType = UINT16; break; + return IndexType::UINT16; case fx::gltf::Accessor::ComponentType::UnsignedInt: - indexType = UINT32; break; + return IndexType::UINT32; default: - std::cerr << "ERROR: Index type not supported: " << - static_cast<uint16_t>(indexAccessor.componentType) << - std::endl; - return 0; + std::cerr << "ERROR: Index type not supported: " << + static_cast<uint16_t>(t) << std::endl; + return IndexType::UNDEFINED; } +} - const size_t numVertexGroups = objectMesh.primitives.size(); - - std::vector<VertexGroup> vertexGroups; - vertexGroups.reserve(numVertexGroups); - - vertexGroups.push_back({ - static_cast<PrimitiveMode>(objectPrimitive.mode), - object.accessors[objectPrimitive.indices].count, - posAccessor.count, - {indexType, indexBufferData}, - {vertexBufferData, vertexAttributes}, - {posAccessor.min[0], posAccessor.min[1], posAccessor.min[2]}, - {posAccessor.max[0], posAccessor.max[1], posAccessor.max[2]}, - static_cast<uint8_t>(objectPrimitive.material) - }); - - std::vector<Material> materials; - - mesh = { - object.meshes[0].name, - vertexGroups, - materials, - 0, 0, 0, NULL - }; - - // FIXME HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK - // fail quietly if there is no texture - if (object.textures.size()) { - const std::string mime_type("image/jpeg"); - const fx::gltf::Texture &tex = object.textures[0]; - const fx::gltf::Image &img = object.images[tex.source]; -#ifndef NDEBUG - printf("texture name=%s sampler=%u source=%u\n", - tex.name.c_str(), tex.sampler, tex.source); - printf("image name=%s uri=%s mime=%s\n", img.name.c_str(), - img.uri.c_str(), img.mimeType.c_str()); -#endif - - size_t pos = path.find_last_of("/"); - auto dir = path.substr(0, pos); - - mesh.texture_hack.img = stbi_load((dir + "/" + img.uri).c_str(), - &mesh.texture_hack.w, &mesh.texture_hack.h, - &mesh.texture_hack.ch, 4); - } - // FIXME HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK HACK - return 1; +/** + * This function computes the modelMatrix out of the data given in the gltf file. It also checks, whether a modelMatrix was given. + * @param translation possible translation vector (default 0,0,0) + * @param scale possible scale vector (default 1,1,1) + * @param rotation possible rotation, given in quaternion (default 0,0,0,1) + * @param matrix possible modelmatrix (default identity) + * @return model Matrix as an array of floats + */ +std::array<float, 16> computeModelMatrix(std::array<float, 3> translation, std::array<float, 3> scale, std::array<float, 4> rotation, std::array<float, 16> matrix){ + std::array<float, 16> modelMatrix = {1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1}; + if (matrix != modelMatrix){ + return matrix; + } else { + // translation + modelMatrix[3] = translation[0]; + modelMatrix[7] = translation[1]; + modelMatrix[11] = translation[2]; + // rotation and scale + auto a = rotation[0]; + auto q1 = rotation[1]; + auto q2 = rotation[2]; + auto q3 = rotation[3]; + + modelMatrix[0] = (2 * (a * a + q1 * q1) - 1) * scale[0]; + modelMatrix[1] = (2 * (q1 * q2 - a * q3)) * scale[1]; + modelMatrix[2] = (2 * (q1 * q3 + a * q2)) * scale[2]; + + modelMatrix[4] = (2 * (q1 * q2 + a * q3)) * scale[0]; + modelMatrix[5] = (2 * (a * a + q2 * q2) - 1) * scale[1]; + modelMatrix[6] = (2 * (q2 * q3 - a * q1)) * scale[2]; + + modelMatrix[8] = (2 * (q1 * q3 - a * q2)) * scale[0]; + modelMatrix[9] = (2 * (q2 * q3 + a * q1)) * scale[1]; + modelMatrix[10] = (2 * (a * a + q3 * q3) - 1) * scale[2]; + + // flip y, because GLTF uses y up, but vulkan -y up + modelMatrix[5] *= -1; + + return modelMatrix; + } + +} + +bool materialHasTexture(const Material *const m, const PBRTextureTarget t) +{ + return m->textureMask & bitflag(t); +} + +int loadScene(const std::string &path, Scene &scene){ + fx::gltf::Document sceneObjects; + + try { + if (path.rfind(".glb", (path.length()-4)) != std::string::npos) { + sceneObjects = fx::gltf::LoadFromBinary(path); + } else { + sceneObjects = fx::gltf::LoadFromText(path); + } + } catch (const std::system_error &err) { + print_what(err, path); + return 0; + } catch (const std::exception &e) { + print_what(e, path); + return 0; + } + size_t pos = path.find_last_of("/"); + auto dir = path.substr(0, pos); + + // file has to contain at least one mesh + if (sceneObjects.meshes.size() == 0) return 0; + + fx::gltf::Accessor posAccessor; + std::vector<VertexAttribute> vertexAttributes; + std::vector<Material> materials; + std::vector<Texture> textures; + std::vector<Sampler> samplers; + std::vector<Mesh> meshes; + std::vector<VertexGroup> vertexGroups; + int groupCount = 0; + + Mesh mesh = {}; + + for(int i = 0; i < sceneObjects.meshes.size(); i++){ + std::vector<int> vertexGroupsIndices; + fx::gltf::Mesh const &objectMesh = sceneObjects.meshes[i]; + + for(int j = 0; j < objectMesh.primitives.size(); j++){ + fx::gltf::Primitive const &objectPrimitive = objectMesh.primitives[j]; + vertexAttributes.clear(); + vertexAttributes.reserve(objectPrimitive.attributes.size()); + + for (auto const & attrib : objectPrimitive.attributes) { + + fx::gltf::Accessor accessor = sceneObjects.accessors[attrib.second]; + VertexAttribute attribute; + + if (attrib.first == "POSITION") { + attribute.type = PrimitiveType::POSITION; + posAccessor = accessor; + } else if (attrib.first == "NORMAL") { + attribute.type = PrimitiveType::NORMAL; + } else if (attrib.first == "TEXCOORD_0") { + attribute.type = PrimitiveType::TEXCOORD_0; + } else if (attrib.first == "TEXCOORD_1") { + attribute.type = PrimitiveType::TEXCOORD_1; + } else { + return 0; + } + + attribute.offset = sceneObjects.bufferViews[accessor.bufferView].byteOffset; + attribute.length = sceneObjects.bufferViews[accessor.bufferView].byteLength; + attribute.stride = sceneObjects.bufferViews[accessor.bufferView].byteStride; + attribute.componentType = static_cast<ComponentType>(accessor.componentType); + + if (convertTypeToInt(accessor.type) != 10) { + attribute.componentCount = convertTypeToInt(accessor.type); + } else { + return 0; + } + + vertexAttributes.push_back(attribute); + } + + IndexType indexType; + std::vector<uint8_t> indexBufferData = {}; + if (objectPrimitive.indices >= 0){ // if there is no index buffer, -1 is returned from fx-gltf + const fx::gltf::Accessor &indexAccessor = sceneObjects.accessors[objectPrimitive.indices]; + const fx::gltf::BufferView &indexBufferView = sceneObjects.bufferViews[indexAccessor.bufferView]; + const fx::gltf::Buffer &indexBuffer = sceneObjects.buffers[indexBufferView.buffer]; + + indexBufferData.resize(indexBufferView.byteLength); + { + const size_t off = indexBufferView.byteOffset; + const void *const ptr = ((char*)indexBuffer.data.data()) + off; + if (!memcpy(indexBufferData.data(), ptr, indexBufferView.byteLength)) { + vkcv_log(LogLevel::ERROR, "Copying index buffer data"); + return 0; + } + } + + indexType = getIndexType(indexAccessor.componentType); + if (indexType == IndexType::UNDEFINED){ + vkcv_log(LogLevel::ERROR, "Index Type undefined."); + return 0; + } + } + + const fx::gltf::BufferView& vertexBufferView = sceneObjects.bufferViews[posAccessor.bufferView]; + const fx::gltf::Buffer& vertexBuffer = sceneObjects.buffers[vertexBufferView.buffer]; + + // only copy relevant part of vertex data + uint32_t relevantBufferOffset = std::numeric_limits<uint32_t>::max(); + uint32_t relevantBufferEnd = 0; + for (const auto &attribute : vertexAttributes) { + relevantBufferOffset = std::min(attribute.offset, relevantBufferOffset); + const uint32_t attributeEnd = attribute.offset + attribute.length; + relevantBufferEnd = std::max(relevantBufferEnd, attributeEnd); // TODO: need to incorporate stride? + } + const uint32_t relevantBufferSize = relevantBufferEnd - relevantBufferOffset; + + // FIXME: This only works when all vertex attributes are in one buffer + std::vector<uint8_t> vertexBufferData; + vertexBufferData.resize(relevantBufferSize); + { + const void *const ptr = ((char*)vertexBuffer.data.data()) + relevantBufferOffset; + if (!memcpy(vertexBufferData.data(), ptr, relevantBufferSize)) { + vkcv_log(LogLevel::ERROR, "Copying vertex buffer data"); + return 0; + } + } + + // make vertex attributes relative to copied section + for (auto &attribute : vertexAttributes) { + attribute.offset -= relevantBufferOffset; + } + + const size_t numVertexGroups = objectMesh.primitives.size(); + vertexGroups.reserve(numVertexGroups); + + vertexGroups.push_back({ + static_cast<PrimitiveMode>(objectPrimitive.mode), + sceneObjects.accessors[objectPrimitive.indices].count, + posAccessor.count, + {indexType, indexBufferData}, + {vertexBufferData, vertexAttributes}, + {posAccessor.min[0], posAccessor.min[1], posAccessor.min[2]}, + {posAccessor.max[0], posAccessor.max[1], posAccessor.max[2]}, + static_cast<uint8_t>(objectPrimitive.material) + }); + + vertexGroupsIndices.push_back(groupCount); + groupCount++; + } + + mesh.name = sceneObjects.meshes[i].name; + mesh.vertexGroups = vertexGroupsIndices; + + meshes.push_back(mesh); + } + + for(int m = 0; m < sceneObjects.nodes.size(); m++) { + meshes[sceneObjects.nodes[m].mesh].modelMatrix = computeModelMatrix(sceneObjects.nodes[m].translation, + sceneObjects.nodes[m].scale, + sceneObjects.nodes[m].rotation, + sceneObjects.nodes[m].matrix); + } + + if (sceneObjects.textures.size() > 0){ + textures.reserve(sceneObjects.textures.size()); + + for(int k = 0; k < sceneObjects.textures.size(); k++){ + const fx::gltf::Texture &tex = sceneObjects.textures[k]; + const fx::gltf::Image &img = sceneObjects.images[tex.source]; + std::string img_uri = dir + "/" + img.uri; + int w, h, c; + uint8_t *data = stbi_load(img_uri.c_str(), &w, &h, &c, 4); + c = 4; // FIXME hardcoded to always have RGBA channel layout + if (!data) { + vkcv_log(LogLevel::ERROR, "Loading texture image data.") + return 0; + } + const size_t byteLen = w * h * c; + + std::vector<uint8_t> imgdata; + imgdata.resize(byteLen); + if (!memcpy(imgdata.data(), data, byteLen)) { + vkcv_log(LogLevel::ERROR, "Copying texture image data") + free(data); + return 0; + } + free(data); + + textures.push_back({ + 0, + static_cast<uint8_t>(c), + static_cast<uint16_t>(w), + static_cast<uint16_t>(h), + imgdata + }); + + } + } + + if (sceneObjects.materials.size() > 0){ + materials.reserve(sceneObjects.materials.size()); + + for (int l = 0; l < sceneObjects.materials.size(); l++){ + fx::gltf::Material material = sceneObjects.materials[l]; + // TODO I think we shouldn't set the index for a texture target if + // it isn't defined. So we need to test first if there is a normal + // texture before assigning material.normalTexture.index. + // About the bitmask: If a normal texture is there, modify the + // materials textureMask like this: + // mat.textureMask |= bitflag(asset::normal); + materials.push_back({ + 0, + material.pbrMetallicRoughness.baseColorTexture.index, + material.pbrMetallicRoughness.metallicRoughnessTexture.index, + material.normalTexture.index, + material.occlusionTexture.index, + material.emissiveTexture.index, + { + material.pbrMetallicRoughness.baseColorFactor[0], + material.pbrMetallicRoughness.baseColorFactor[1], + material.pbrMetallicRoughness.baseColorFactor[2], + material.pbrMetallicRoughness.baseColorFactor[3] + }, + material.pbrMetallicRoughness.metallicFactor, + material.pbrMetallicRoughness.roughnessFactor, + material.normalTexture.scale, + material.occlusionTexture.strength, + { + material.emissiveFactor[0], + material.emissiveFactor[1], + material.emissiveFactor[2] + } + + }); + } + } + + scene = { + meshes, + vertexGroups, + materials, + textures, + samplers + }; + + return 1; } } diff --git a/modules/camera/CMakeLists.txt b/modules/camera/CMakeLists.txt index 28080bf2b1cd3bbc88d6c13d7ef26a43d7c3e19a..73f2dd1c81be9c6cadf563f7936bfaba8c1d0025 100644 --- a/modules/camera/CMakeLists.txt +++ b/modules/camera/CMakeLists.txt @@ -11,10 +11,13 @@ set(vkcv_camera_include ${PROJECT_SOURCE_DIR}/include) set(vkcv_camera_sources ${vkcv_camera_include}/vkcv/camera/Camera.hpp ${vkcv_camera_source}/vkcv/camera/Camera.cpp - ${vkcv_camera_include}/vkcv/camera/TrackballCamera.hpp - ${vkcv_camera_source}/vkcv/camera/TrackballCamera.cpp ${vkcv_camera_include}/vkcv/camera/CameraManager.hpp ${vkcv_camera_source}/vkcv/camera/CameraManager.cpp + ${vkcv_camera_include}/vkcv/camera/CameraController.hpp + ${vkcv_camera_include}/vkcv/camera/PilotCameraController.hpp + ${vkcv_camera_source}/vkcv/camera/PilotCameraController.cpp + ${vkcv_camera_include}/vkcv/camera/TrackballCameraController.hpp + ${vkcv_camera_source}/vkcv/camera/TrackballCameraController.cpp ) # adding source files to the project diff --git a/modules/camera/include/vkcv/camera/Camera.hpp b/modules/camera/include/vkcv/camera/Camera.hpp index ff8fda811eaad7a99dbb940601f9e5904025255e..dc9f2dcb3038655f51fb2404abc21f98a2120399 100644 --- a/modules/camera/include/vkcv/camera/Camera.hpp +++ b/modules/camera/include/vkcv/camera/Camera.hpp @@ -1,101 +1,199 @@ #pragma once +#define GLM_DEPTH_ZERO_TO_ONE +#define GLM_FORCE_LEFT_HANDED #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_access.hpp> -namespace vkcv { +namespace vkcv::camera { - class Camera { + /** + * @brief Used to create a camera which governs the view and projection matrices. + */ + class Camera final { protected: glm::mat4 m_view; glm::mat4 m_projection; - int m_width; - int m_height; - float m_near; float m_far; - float m_fov; - float m_ratio; - glm::vec3 m_up; + glm::vec3 m_up; glm::vec3 m_position; - float m_cameraSpeed; + glm::vec3 m_center; + float m_pitch; float m_yaw; - - int m_fov_nsteps; - float m_fov_min; - float m_fov_max; - - bool m_forward; - bool m_backward; - bool m_left; - bool m_right; + + /** + * @brief Sets the view matrix of the camera to @p view + * @param[in] view The view matrix + */ + void setView(const glm::mat4& view); + + /** + * @brief Sets the projection matrix of the camera to @p projection + * @param[in] projection The projection matrix + */ + void setProjection(const glm::mat4& projection); public: - Camera(); - virtual ~Camera(); + /** + * @brief The default constructor of the camera + */ + Camera(); + /** + * @brief The destructor of the camera (default behavior) + */ + ~Camera(); + + /** + * @brief Sets the perspective object according to @p fov, @p ratio, @p near and @p far. This leads to changes in the projection matrix of the camera + * @param[in] fov The desired field of view in radians + * @param[in] ratio The aspect ratio + * @param[in] near Distance to near clipping plane + * @param[in] far Distance to far clipping plane + */ void setPerspective(float fov, float ratio, float near, float far); - const glm::mat4 getView() const; - - void getView(glm::vec3 &x, glm::vec3 &y, glm::vec3 &z, glm::vec3 &pos); - - glm::mat4 updateView(double deltatime); - - void lookAt(glm::vec3 position, glm::vec3 center, glm::vec3 up); - + /** + * @brief Gets the view matrix of the camera + * @return The view matrix of the camera + */ + const glm::mat4& getView() const; + + /** + * @brief Sets the view matrix of the camera according to @p position, @p center and @p up + * @param[in] position The position of the camera + * @param[in] center The target position the camera is looking at + * @param[in] up The vector that defines which direction is 'up' depending on the camera's orientation + */ + void lookAt(const glm::vec3& position, const glm::vec3& center, const glm::vec3& up); + + /** + * @brief Gets the current projection of the camera + * @return The current projection matrix + */ const glm::mat4& getProjection() const; - void setProjection(const glm::mat4 projection); - + /** + * @brief Gets the model-view-projection matrix of the camera with y-axis-correction applied + * @return The model-view-projection matrix + */ + glm::mat4 getMVP() const; + + /** + * @brief Gets the near and far bounds of the view frustum of the camera. + * @param[out] near The near bound of the view frustum + * @param[out] far The far bound of the view frustum + */ void getNearFar(float &near, float &far) const; - void setUp(const glm::vec3 &Up); - + /** + * @brief Gets the current field of view of the camera in radians + * @return[in] The current field of view in radians + */ float getFov() const; + /** + * @brief Sets the field of view of the camera to @p fov in radians + * @param[in] fov The new field of view in radians + */ void setFov(float fov); - - void changeFov(double fov); - - void updateRatio(int width, int height); + /** + * @brief Gets the current aspect ratio of the camera + * @return The current aspect ratio of the camera + */ float getRatio() const; + /** + * @brief Updates the aspect ratio of the camera with @p ratio and, thus, changes the projection matrix + * @param[in] ratio The new aspect ratio of the camera + */ + void setRatio(float ratio); + + /** + * @brief Sets @p near and @p far as new values for the view frustum of the camera. This leads to changes in the projection matrix according to these two values. + * @param[in] near The new near bound of the view frustum + * @param[in] far The new far bound of the view frustum + */ void setNearFar(float near, float far); + /** + * @brief Gets the current front vector of the camera in world space + * @return The current front vector of the camera + */ glm::vec3 getFront() const; - - glm::vec3 getPosition() const; - - void setPosition( glm::vec3 position ); - + + /** + * @brief Sets the front vector of the camera in world space to @p front + * @param[in] front The new front vector of the camera + */ + void setFront(const glm::vec3& front); + + /** + * @brief Gets the current position of the camera in world space + * @return The current position of the camera in world space + */ + const glm::vec3& getPosition() const; + + /** + * @brief Sets the position of the camera to @p position + * @param[in] position The new position of the camera + */ + void setPosition( const glm::vec3& position ); + + /** + * @brief Gets the center point. + * @return The center point. + */ + const glm::vec3& getCenter() const; + + /** + * @brief Sets @p center as the new center point. + * @param[in] center The new center point. + */ + void setCenter(const glm::vec3& center); + + /** + * @brief Gets the pitch value of the camera in degrees. + * @return The pitch value in degrees. + */ float getPitch() const; + /** + * @brief Sets the pitch value of the camera to @p pitch in degrees. + * @param[in] pitch The new pitch value in degrees. + */ void setPitch(float pitch); + /** + * @brief Gets the yaw value of the camera in degrees. + * @return The yaw value in degrees. + */ float getYaw() const; + /** + * @brief Sets the yaw value of the camera to @p yaw. + * @param[in] yaw The new yaw value in degrees. + */ void setYaw(float yaw); - void panView( double xOffset, double yOffset ); - - void updatePosition(double deltatime); - - void moveForward(int action); - - void moveBackward(int action); - - void moveLeft(int action); - - void moveRight(int action); - - + /** + * @brief Gets the up vector. + * @return The up vector. + */ + const glm::vec3& getUp() const; + + /** + * @brief Sets @p up as the new up vector. + * @param[in] up The new up vector. + */ + void setUp(const glm::vec3 &up); }; } diff --git a/modules/camera/include/vkcv/camera/CameraController.hpp b/modules/camera/include/vkcv/camera/CameraController.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5fe7aba586068beff15525617d8e4817662746b7 --- /dev/null +++ b/modules/camera/include/vkcv/camera/CameraController.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include "Camera.hpp" +#include "vkcv/Window.hpp" + +namespace vkcv::camera { + + /** + * @brief Used as a base class for defining camera controller classes with different behaviors, e.g. the + * #PilotCameraController. + */ + class CameraController { + + public: + + /** + * @brief The constructor of the #CameraController (default behavior). + */ + CameraController() = default; + + /** + * @brief Updates @p camera in respect to @p deltaTime. + * @param[in] deltaTime The time that has passed since last update. + * @param[in] camera The camera object. + */ + virtual void updateCamera(double deltaTime, Camera &camera) = 0; + + /** + * @brief A callback function for key events. + * @param[in] key The keyboard key. + * @param[in] scancode The platform-specific scancode. + * @param[in] action The key action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + virtual void keyCallback(int key, int scancode, int action, int mods, Camera &camera) = 0; + + /** + * @brief A callback function for mouse scrolling events. + * @param[in] offsetX The offset in horizontal direction. + * @param[in] offsetY The offset in vertical direction. + * @param[in] camera The camera object. + */ + virtual void scrollCallback( double offsetX, double offsetY, Camera &camera) = 0; + + /** + * @brief A callback function for mouse movement events. + * @param[in] x The horizontal mouse position. + * @param[in] y The vertical mouse position. + * @param[in] camera The camera object. + */ + virtual void mouseMoveCallback(double offsetX, double offsetY, Camera &camera) = 0; + + /** + * @brief A callback function for mouse button events. + * @param[in] button The mouse button. + * @param[in] action The button action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + virtual void mouseButtonCallback(int button, int action, int mods, Camera &camera) = 0; + }; + +} \ No newline at end of file diff --git a/modules/camera/include/vkcv/camera/CameraManager.hpp b/modules/camera/include/vkcv/camera/CameraManager.hpp index 4e52eccea25e8544a9a5cc89d0dc74ddd0e023c6..5755d6cdc20f0321197b7755e459725eb363fc90 100644 --- a/modules/camera/include/vkcv/camera/CameraManager.hpp +++ b/modules/camera/include/vkcv/camera/CameraManager.hpp @@ -1,40 +1,184 @@ #pragma once -#include "TrackballCamera.hpp" +#include "PilotCameraController.hpp" +#include "TrackballCameraController.hpp" +#include "CameraController.hpp" #include "vkcv/Window.hpp" #include <GLFW/glfw3.h> #include <functional> -namespace vkcv{ +namespace vkcv::camera { + /** + * @brief Used for specifying existing types of camera controllers when adding a new controller object to the + * #CameraManager. + */ + enum class ControllerType { + NONE, + PILOT, + TRACKBALL, + TRACE + }; + + /** + * @brief Used for managing an arbitrary amount of camera controllers. + */ class CameraManager{ private: - std::function<void(int, int, int, int)> e_keyHandle; - std::function<void(double, double)> e_mouseMoveHandle; - std::function<void(double, double)> e_mouseScrollHandle; - std::function<void(int, int, int)> e_mouseButtonHandle; - std::function<void(int, int)> e_resizeHandle; - - Window &m_window; - Camera m_camera; - float m_width; - float m_height; -// std::shared_ptr<vkcv::TrackballCamera> m_trackball; - - bool m_roationActive = false; - double m_lastX ; - double m_lastY ; - - void bindCamera(); + event_handle<int, int, int, int> m_keyHandle; + event_handle<double, double> m_mouseMoveHandle; + event_handle<double, double> m_mouseScrollHandle; + event_handle<int, int, int> m_mouseButtonHandle; + event_handle<int, int> m_resizeHandle; + + Window& m_window; + std::vector<Camera> m_cameras; + std::vector<ControllerType> m_cameraControllerTypes; + uint32_t m_activeCameraIndex; + + PilotCameraController m_pilotController; + TrackballCameraController m_trackController; + + double m_lastX; + double m_lastY; + + /** + * @brief Binds the camera object to the window event handles. + */ + void bindCameraToEvents(); + + /** + * @brief A callback function for key events. Currently, cycling between all existing camera controllers via Tab, + * window closure via Esc and polling key events from the active camera controller are supported. + * @param[in] key The keyboard key. + * @param[in] scancode The platform-specific scancode. + * @param[in] action The key action. + * @param[in] mods The modifier bits. + */ void keyCallback(int key, int scancode, int action, int mods); - void scrollCallback( double offsetX, double offsetY); - void mouseMoveCallback( double offsetX, double offsetY); + + /** + * @brief A callback function for mouse scrolling events. + * @param[in] offsetX The offset in horizontal direction. + * @param[in] offsetY The offset in vertical direction. + */ + void scrollCallback(double offsetX, double offsetY); + + /** + * @brief A callback function for mouse movement events. + * @param[in] x The horizontal mouse position. + * @param[in] y The vertical mouse position. + */ + void mouseMoveCallback(double x, double y); + + /** + * @brief A callback function for mouse button events. + * @param[in] button The mouse button. + * @param[in] action The button action. + * @param[in] mods The modifier bits. + */ void mouseButtonCallback(int button, int action, int mods); + + /** + * @brief A callback function for handling the window resizing event. Each existing camera is resized in respect + * of the window size. + * @param[in] width The new width of the window. + * @param[in] height The new height of the window. + */ void resizeCallback(int width, int height); + + /** + * @brief Gets a camera controller object of specified @p controllerType. + * @param[in] controllerType The type of the camera controller. + * @return The specified camera controller object. + */ + CameraController& getControllerByType(ControllerType controllerType); + + /** + * @briof A method to get the currently active controller for the active camera. + * @return Reference to the active #CameraController + */ + CameraController& getActiveController(); public: - CameraManager(Window &window, float width, float height, glm::vec3 up = glm::vec3(0.0f,-1.0f,0.0f), glm::vec3 position = glm::vec3(0.0f,0.0f,0.0f)); - Camera &getCamera(); + /** + * @brief The constructor of the #CameraManager. + * @param[in] window The window. + */ + CameraManager(Window &window); + + /** + * @brief The destructor of the #CameraManager. Destroying the #CameraManager leads to deletion of all stored + * camera objects and camera controller objects. + */ + ~CameraManager(); + + /** + * @brief Adds a new camera object to the #CameraManager and binds it to a camera controller object of specified + * @p controllerType. + * @param[in] controllerType The type of the camera controller. + * @return The index of the newly created camera object. + */ + uint32_t addCamera(ControllerType controllerType = ControllerType::NONE); + + /** + * @brief Adds a new camera object to the #CameraManager and binds it to a camera controller object of specified + * @p controllerType. + * @param[in] controllerType The type of the camera controller. + * @param[in] camera The new camera object. + * @return The index of the newly bound camera object. + */ + uint32_t addCamera(ControllerType controllerType, const Camera& camera); + + /** + * @brief Gets the stored camera object located at @p cameraIndex. + * @param[in] cameraIndex The camera index. + * @return The camera object at @p cameraIndex. + * @throws std::runtime_error If @p cameraIndex is not a valid camera index. + */ + Camera& getCamera(uint32_t cameraIndex); + + /** + * @brief Gets the stored camera object set as the active camera. + * @return The active camera. + */ + Camera& getActiveCamera(); + + /** + * @brief Sets the stored camera object located at @p cameraIndex as the active camera. + * @param[in] cameraIndex The camera index. + * @throws std::runtime_error If @p cameraIndex is not a valid camera index. + */ + void setActiveCamera(uint32_t cameraIndex); + + /** + * @brief Gets the index of the stored active camera object. + * @return The active camera index. + */ + uint32_t getActiveCameraIndex() const; + + /** + * @brief Binds a stored camera object located at @p cameraIndex to a camera controller of specified + * @p controllerType. + * @param[in] cameraIndex The camera index. + * @param[in] controllerType The type of the camera controller. + * @throws std::runtime_error If @p cameraIndex is not a valid camera index. + */ + void setControllerType(uint32_t cameraIndex, ControllerType controllerType); + + /** + * @brief Gets the currently bound camera controller type of the stored camera object located at @p cameraIndex. + * @param[in] cameraIndex The camera index. + * @return The type of the camera controller of the specified camera object. + * @throws std::runtime_error If @p cameraIndex is not a valid camera index. + */ + ControllerType getControllerType(uint32_t cameraIndex); + + /** + * @brief Updates all stored camera controllers in respect to @p deltaTime. + * @param[in] deltaTime The time that has passed since last update. + */ + void update(double deltaTime); }; } diff --git a/modules/camera/include/vkcv/camera/PilotCameraController.hpp b/modules/camera/include/vkcv/camera/PilotCameraController.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c6a9f7c7ffa9a3be77f12c29e456291fb8f6b845 --- /dev/null +++ b/modules/camera/include/vkcv/camera/PilotCameraController.hpp @@ -0,0 +1,138 @@ +#pragma once + +#include <vkcv/camera/CameraController.hpp> + +namespace vkcv::camera { + + /** + * @brief Used to move around a camera object in world space. + */ + class PilotCameraController final : public CameraController { + private: + // camera movement indicators + bool m_forward; + bool m_backward; + bool m_upward; + bool m_downward; + bool m_left; + bool m_right; + + bool m_rotationActive; + + float m_cameraSpeed; + + int m_fov_nsteps; + float m_fov_min; + float m_fov_max; + + /** + * @brief Indicates forward movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveForward(int action); + + /** + * @brief Indicates backward movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveBackward(int action); + + /** + * @brief Indicates left movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveLeft(int action); + + /** + * @brief Indicates right movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveRight(int action); + + /** + * @brief Indicates upward movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveUpward(int action); + + /** + * @brief Indicates downward movement of the camera depending on the performed @p action. + * @param[in] action The performed action. + */ + void moveDownward(int action); + + public: + + /** + * @brief The default constructor of the #PilotCameraController. + */ + PilotCameraController(); + + /** + * @brief The destructor of the #PilotCameraController (default behavior). + */ + ~PilotCameraController() = default; + + /** + * @brief Changes the field of view of @p camera with an @p offset in degrees. + * @param[in] offset The offset in degrees. + * @param[in] camera The camera object. + */ + void changeFov(double offset, Camera &camera); + + /** + * @brief Pans the view of @p camera according to the pitch and yaw values and additional offsets @p xOffset + * and @p yOffset. + * @param[in] xOffset The offset added to the yaw value. + * @param[in] yOffset The offset added to the pitch value. + * @param[in] camera The camera object. + */ + void panView(double xOffset, double yOffset, Camera &camera); + + /** + * @brief Updates @p camera in respect to @p deltaTime. + * @param[in] deltaTime The time that has passed since last update. + * @param[in] camera The camera object. + */ + void updateCamera(double deltaTime, Camera &camera); + + /** + * @brief A callback function for key events. Currently, 3D camera movement via W, A, S, D, E, Q are supported. + * @param[in] key The keyboard key. + * @param[in] scancode The platform-specific scancode. + * @param[in] action The key action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + void keyCallback(int key, int scancode, int action, int mods, Camera &camera); + + /** + * @brief A callback function for mouse scrolling events. Currently, this leads to changes in the field of view + * of @p camera. + * @param[in] offsetX The offset in horizontal direction. + * @param[in] offsetY The offset in vertical direction. + * @param[in] camera The camera object. + */ + void scrollCallback(double offsetX, double offsetY, Camera &camera); + + /** + * @brief A callback function for mouse movement events. Currently, this leads to panning the view of the camera, + * if #mouseButtonCallback(int button, int action, int mods) enabled panning. + * @param[in] x The horizontal mouse position + * @param[in] y The vertical mouse position + * @param[in] camera The camera object. + */ + void mouseMoveCallback(double x, double y, Camera &camera); + + /** + * @brief A callback function for mouse button events. Currently, the right mouse button enables panning the + * view of the camera as long as it is pressed. + * @param[in] button The mouse button + * @param[in] action The button action + * @param[in] mods The modifier bits + * @param[in] camera The camera object. + */ + void mouseButtonCallback(int button, int action, int mods, Camera &camera); + }; + +} \ No newline at end of file diff --git a/modules/camera/include/vkcv/camera/TrackballCamera.hpp b/modules/camera/include/vkcv/camera/TrackballCamera.hpp deleted file mode 100644 index c9e269e9f7ad708c68158d5b358efbf37c5bb7a9..0000000000000000000000000000000000000000 --- a/modules/camera/include/vkcv/camera/TrackballCamera.hpp +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include "Camera.hpp" - -namespace vkcv { - - class TrackballCamera : public vkcv::Camera { - public: - - TrackballCamera( int width, int height, glm::mat4 projection); - - TrackballCamera(int width, int height); - - ~TrackballCamera(); - - float getSensitivity() const; - - void setSensitivity(float sensitivity); - - float getStepSize() const; - - void setStepSize(float stepSize); - - float getTheta() const; - - void setTheta(float theta); - - float getPhi() const; - - void setPhi(float phi); - - float getRadius() const; - - void setRadius(float radius); - - const glm::vec3& getCenter() const; - - void setCenter(const glm::vec3 ¢er); - - private: - float m_sensitivity; - float m_stepSize, m_theta, m_phi, m_radius; - glm::vec3 m_center; - - float m_oldX; - float m_oldY; - }; - -} \ No newline at end of file diff --git a/modules/camera/include/vkcv/camera/TrackballCameraController.hpp b/modules/camera/include/vkcv/camera/TrackballCameraController.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0211043a9c6b862df8e500af190ad1f75a3c78aa --- /dev/null +++ b/modules/camera/include/vkcv/camera/TrackballCameraController.hpp @@ -0,0 +1,100 @@ +#pragma once + +#include "CameraController.hpp" + +namespace vkcv::camera { + + /** + * @brief Used to orbit a camera around its center point. + */ + class TrackballCameraController final : public CameraController { + private: + bool m_rotationActive; + + float m_cameraSpeed; + float m_scrollSensitivity; + float m_radius; + + /** + * @brief Updates the current radius of @p camera in respect to the @p offset. + * @param[in] offset The offset between the old and new radius. + * @param[in] camera The camera object. + */ + void updateRadius(double offset, Camera &camera); + + public: + + /** + * @brief The default constructor of the #TrackballCameraController. + */ + TrackballCameraController(); + + /** + * @brief The destructor of the #TrackballCameraController (default behavior). + */ + ~TrackballCameraController() = default; + + /** + * @brief Sets @p radius as the new radius for orbiting around the camera's center point. + * @param[in] radius The new radius. + */ + void setRadius(const float radius); + + /** + * @brief Pans the view of @p camera according to the pitch and yaw values and additional offsets @p xOffset + * and @p yOffset. + * @param[in] xOffset The offset added to the yaw value. + * @param[in] yOffset The offset added to the pitch value. + * @param[in] camera The camera object. + */ + void panView(double xOffset, double yOffset, Camera &camera); + + /** + * @brief Updates @p camera in respect to @p deltaTime. + * @param[in] deltaTime The time that has passed since last update. + * @param[in] camera The camera object + */ + void updateCamera(double deltaTime, Camera &camera); + + /** + * @brief A callback function for key events. Currently, the trackball camera does not support camera movement. + * It can only orbit around its center point. + * @param[in] key The keyboard key. + * @param[in] scancode The platform-specific scancode. + * @param[in] action The key action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + void keyCallback(int key, int scancode, int action, int mods, Camera &camera); + + /** + * @brief A callback function for mouse scrolling events. Currently, this leads to changes in the field of view + * of the camera object. + * @param[in] offsetX The offset in horizontal direction. + * @param[in] offsetY The offset in vertical direction. + * @param[in] camera The camera object. + */ + void scrollCallback(double offsetX, double offsetY, Camera &camera); + + /** + * @brief A callback function for mouse movement events. Currently, this leads to panning the view of the + * camera, if #mouseButtonCallback(int button, int action, int mods) enabled panning. + * @param[in] xoffset The horizontal mouse position. + * @param[in] yoffset The vertical mouse position. + * @param[in] camera The camera object. + */ + void mouseMoveCallback(double xoffset, double yoffset, Camera &camera); + + /** + * @brief A callback function for mouse button events. Currently, the right mouse button enables panning the + * view of the camera as long as it is pressed. + * @param[in] button The mouse button. + * @param[in] action The button action. + * @param[in] mods The modifier bits. + * @param[in] camera The camera object. + */ + void mouseButtonCallback(int button, int action, int mods, Camera &camera); + + }; + +} \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/Camera.cpp b/modules/camera/src/vkcv/camera/Camera.cpp index af89ed86881acc8b754a041d32599a78caac57b4..eb1857968b2284287691c6ed41ba168db30d3f84 100644 --- a/modules/camera/src/vkcv/camera/Camera.cpp +++ b/modules/camera/src/vkcv/camera/Camera.cpp @@ -1,44 +1,28 @@ #include "vkcv/camera/Camera.hpp" -#include <iostream> -namespace vkcv { +#define _USE_MATH_DEFINES +#include <math.h> - Camera::Camera(){ - m_up = glm::vec3(0.0f, -1.0f, 0.0f); - m_position = glm::vec3(0.0f, 0.0f, 0.0f); - m_cameraSpeed = 2.f; - // front - m_pitch = 0.0; - m_yaw = 180.0; +namespace vkcv::camera { - m_fov_nsteps = 100; - m_fov_min = 10; - m_fov_max = 120; - - m_forward = false; - m_backward = false; - m_left = false; - m_right = false; + Camera::Camera() { + lookAt( + glm::vec3(0.0f, 0.0f, -1.0f), + glm::vec3(0.0f, 0.0f, 0.0f), + glm::vec3(0.0f, 1.0f, 0.0f) + ); + + setFront(glm::normalize(m_center - m_position)); } Camera::~Camera() = default; - void Camera::lookAt(glm::vec3 position, glm::vec3 center, glm::vec3 up){ - m_view = glm::lookAt(position, center, up); - } - - glm::mat4 Camera::updateView(double deltatime){ - updatePosition(deltatime); - return m_view = glm::lookAt(m_position, m_position + getFront() , m_up); - } - - void Camera::getView(glm::vec3 &x, glm::vec3 &y, glm::vec3 &z, glm::vec3 &pos){ - x = glm::vec3( glm::row(m_view, 0)); - y = glm::vec3( glm::row(m_view, 1)); - z = glm::vec3( glm::row(m_view, 2)); - pos = glm::vec3( glm::column(m_view, 3)); - glm::mat3 mat_inv = glm::inverse( glm::mat3(m_view)); - pos = -mat_inv * pos; + void Camera::lookAt(const glm::vec3& position, const glm::vec3& center, const glm::vec3& up) { + m_position = position; + m_center = center; + m_up = up; + + setView(glm::lookAt(position, center, up)); } void Camera::getNearFar( float &near, float &far) const { @@ -46,98 +30,111 @@ namespace vkcv { far = m_far; } - - const glm::mat4 Camera::getView() const { + const glm::mat4& Camera::getView() const { return m_view; } + + void Camera::setView(const glm::mat4 &view) { + m_view = view; + } const glm::mat4& Camera::getProjection() const { return m_projection; } - void Camera::setProjection(const glm::mat4 projection){ - m_projection = projection; + void Camera::setProjection(const glm::mat4& projection) { + m_projection = projection; } - float Camera::getFov() const { - return m_fov; + glm::mat4 Camera::getMVP() const { + const glm::mat4 y_correction ( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + return y_correction * m_projection * m_view; } - void Camera::setFov( float fov){ - m_fov = fov; - setPerspective( m_fov, m_ratio, m_near, m_far); + float Camera::getFov() const { + const float tanHalfFovy = 1.0f / m_projection[1][1]; + float halfFovy = std::atan(tanHalfFovy); + + if (halfFovy < 0) { + halfFovy += static_cast<float>(M_PI); + } + + return halfFovy * 2.0f; } - void Camera::changeFov(double offset){ - float fov = m_fov; - float fov_range = m_fov_max - m_fov_min; - float fov_stepsize = glm::radians(fov_range)/m_fov_nsteps; - fov -= (float) offset*fov_stepsize; - if (fov < glm::radians(m_fov_min)) { - fov = glm::radians(m_fov_min); - } - if (fov > glm::radians(m_fov_max)) { - fov = glm::radians(m_fov_max); - } - setFov(fov); + void Camera::setFov( float fov){ + setPerspective(fov, getRatio(), m_near, m_far); } - void Camera::updateRatio( int width, int height){ - m_width = width; - m_height = height; - m_ratio = static_cast<float>(width)/glm::max(height, 1); - setPerspective( m_fov, m_ratio, m_near, m_far); + float Camera::getRatio() const { + const float aspectProduct = 1.0f / m_projection[0][0]; + const float tanHalfFovy = 1.0f / m_projection[1][1]; + + return aspectProduct / tanHalfFovy; } - float Camera::getRatio() const { - return m_ratio; + void Camera::setRatio(float ratio){ + setPerspective( getFov(), ratio, m_near, m_far); } - void Camera::setNearFar( float near, float far){ - m_near = near; - m_far = far; - setPerspective(m_fov, m_ratio, m_near, m_far); + void Camera::setNearFar(float near, float far){ + setPerspective(getFov(), getRatio(), near, far); } - void Camera::setPerspective(float fov, float ratio, float near, float far){ - m_fov = fov; - m_ratio = ratio; - m_near = near; - m_far = far; - m_projection = glm::perspective( m_fov, ratio, m_near, m_far); + void Camera::setPerspective(float fov, float ratio, float near, float far) { + m_near = near; + m_far = far; + setProjection(glm::perspective(fov, ratio, near, far)); } glm::vec3 Camera::getFront() const { glm::vec3 direction; - direction.x = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); - direction.y = sin(glm::radians(m_pitch)); - direction.z = cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch)); + direction.x = std::sin(glm::radians(m_yaw)) * std::cos(glm::radians(m_pitch)); + direction.y = std::sin(glm::radians(m_pitch)); + direction.z = std::cos(glm::radians(m_yaw)) * std::cos(glm::radians(m_pitch)); return glm::normalize(direction); } + + void Camera::setFront(const glm::vec3 &front) { + m_pitch = std::atan2(front.y, std::sqrt(front.x * front.x + front.z * front.z)); + m_yaw = std::atan2(front.x, front.z); + } - glm::vec3 Camera::getPosition() const { + const glm::vec3& Camera::getPosition() const { return m_position; } - void Camera::setPosition( glm::vec3 position ){ - m_position = position; + void Camera::setPosition( const glm::vec3& position ){ + lookAt(position, m_center, m_up); } - void Camera::setUp(const glm::vec3 &up) { - m_up = up; + const glm::vec3& Camera::getCenter() const { + return m_center; } + void Camera::setCenter(const glm::vec3& center) { + lookAt(m_position, center, m_up); + } + + const glm::vec3& Camera::getUp() const { + return m_up; + } + + void Camera::setUp(const glm::vec3 &up) { + lookAt(m_position, m_center, up); + } + float Camera::getPitch() const { return m_pitch; } void Camera::setPitch(float pitch) { - if (pitch > 89.0f) { - pitch = 89.0f; - } - if (pitch < -89.0f) { - pitch = -89.0f; - } m_pitch = pitch; } @@ -149,31 +146,4 @@ namespace vkcv { m_yaw = yaw; } - void Camera::panView(double xOffset, double yOffset) { - m_yaw += xOffset; - m_pitch += yOffset; - } - - void Camera::updatePosition(double deltatime ){ - m_position += (m_cameraSpeed * getFront() * static_cast<float> (m_forward) * static_cast<float>(deltatime)); - m_position -= (m_cameraSpeed * getFront() * static_cast<float> (m_backward) * static_cast<float>(deltatime)); - m_position -= (glm::normalize(glm::cross(getFront(), m_up)) * m_cameraSpeed * static_cast<float> (m_left) * static_cast<float>(deltatime)); - m_position += (glm::normalize(glm::cross(getFront(), m_up)) * m_cameraSpeed * static_cast<float> (m_right) * static_cast<float>(deltatime)); - } - - void Camera::moveForward(int action){ - m_forward = static_cast<bool>(action); - } - - void Camera::moveBackward(int action){ - m_backward = static_cast<bool>(action); - } - - void Camera::moveLeft(int action){ - m_left = static_cast<bool>(action); - } - - void Camera::moveRight(int action){ - m_right = static_cast<bool>(action); - } } \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/CameraManager.cpp b/modules/camera/src/vkcv/camera/CameraManager.cpp index 2631890d646fbf27a4fbb14cfeef706678d8918c..84a0d7ca3049846c4fbb234bab02b5f4d3c7ffd5 100644 --- a/modules/camera/src/vkcv/camera/CameraManager.cpp +++ b/modules/camera/src/vkcv/camera/CameraManager.cpp @@ -1,88 +1,164 @@ -#include <iostream> + #include "vkcv/camera/CameraManager.hpp" -namespace vkcv{ +#include <vkcv/Logger.hpp> + +namespace vkcv::camera { - CameraManager::CameraManager(Window &window, float width, float height, glm::vec3 up, glm::vec3 position): - m_window(window), m_width(width), m_height(height) + CameraManager::CameraManager(Window& window) + : m_window(window) { - m_camera.setUp(up); - m_camera.setPosition(position); - m_camera.setPerspective( glm::radians(60.0f), m_width / m_height, 0.1f, 10.f); - m_lastX = width/2.0; - m_lastY = height/2.0; - bindCamera(); + bindCameraToEvents(); + m_activeCameraIndex = 0; + m_lastX = static_cast<float>(window.getWidth()) / 2.0f; + m_lastY = static_cast<float>(window.getHeight()) / 2.0f; } - void CameraManager::bindCamera(){ - e_keyHandle = m_window.e_key.add( [&](int key, int scancode, int action, int mods) { this->keyCallback(key, scancode, action, mods); }); - e_mouseMoveHandle = m_window.e_mouseMove.add( [&]( double offsetX, double offsetY) {this->mouseMoveCallback( offsetX, offsetY);} ); - e_mouseScrollHandle = m_window.e_mouseScroll.add([&](double offsetX, double offsetY) {this->scrollCallback( offsetX, offsetY);} ); - e_mouseButtonHandle = m_window.e_mouseButton.add([&] (int button, int action, int mods) {this->mouseButtonCallback( button, action, mods);}); - e_resizeHandle = m_window.e_resize.add([&] (int width, int height) {this->resizeCallback( width, height);}); + CameraManager::~CameraManager() { + m_window.e_key.remove(m_keyHandle); + m_window.e_mouseMove.remove(m_mouseMoveHandle); + m_window.e_mouseScroll.remove(m_mouseScrollHandle); + m_window.e_mouseButton.remove(m_mouseButtonHandle); + m_window.e_resize.remove(m_resizeHandle); + } + + void CameraManager::bindCameraToEvents() { + m_keyHandle = m_window.e_key.add( [&](int key, int scancode, int action, int mods) { this->keyCallback(key, scancode, action, mods); }); + m_mouseMoveHandle = m_window.e_mouseMove.add( [&]( double offsetX, double offsetY) {this->mouseMoveCallback( offsetX, offsetY);} ); + m_mouseScrollHandle = m_window.e_mouseScroll.add([&](double offsetX, double offsetY) {this->scrollCallback( offsetX, offsetY);} ); + m_mouseButtonHandle = m_window.e_mouseButton.add([&] (int button, int action, int mods) {this->mouseButtonCallback( button, action, mods);}); + m_resizeHandle = m_window.e_resize.add([&](int width, int height) {this->resizeCallback(width, height);}); + } + + void CameraManager::resizeCallback(int width, int height) { + for (size_t i = 0; i < m_cameras.size(); i++) { + getCamera(i).setRatio(static_cast<float>(width) / static_cast<float>(height));; + } } void CameraManager::mouseButtonCallback(int button, int action, int mods){ - if(button == GLFW_MOUSE_BUTTON_2 && m_roationActive == false && action == GLFW_PRESS){ + if(button == GLFW_MOUSE_BUTTON_2 && action == GLFW_PRESS){ glfwSetInputMode(m_window.getWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED); - m_roationActive = true; - }else if(button == GLFW_MOUSE_BUTTON_2 && m_roationActive == true && action == GLFW_RELEASE){ + } + else if(button == GLFW_MOUSE_BUTTON_2 && action == GLFW_RELEASE){ glfwSetInputMode(m_window.getWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL); - m_roationActive = false; } + getActiveController().mouseButtonCallback(button, action, mods, getActiveCamera()); } void CameraManager::mouseMoveCallback(double x, double y){ - - float xoffset = x - m_lastX; - float yoffset = m_lastY - y; + auto xoffset = static_cast<float>(x - m_lastX); + auto yoffset = static_cast<float>(y - m_lastY); m_lastX = x; m_lastY = y; + getActiveController().mouseMoveCallback(xoffset, yoffset, getActiveCamera()); + } + + void CameraManager::scrollCallback(double offsetX, double offsetY) { + getActiveController().scrollCallback(offsetX, offsetY, getActiveCamera()); + } - if(!m_roationActive){ - return; + void CameraManager::keyCallback(int key, int scancode, int action, int mods) { + switch (action) { + case GLFW_RELEASE: + switch (key) { + case GLFW_KEY_TAB: + if (m_activeCameraIndex + 1 == m_cameras.size()) { + m_activeCameraIndex = 0; + } + else { + m_activeCameraIndex++; + } + return; + case GLFW_KEY_ESCAPE: + glfwSetWindowShouldClose(m_window.getWindow(), 1); + return; + default: + break; + } + default: + getActiveController().keyCallback(key, scancode, action, mods, getActiveCamera()); + break; } + } + + CameraController& CameraManager::getActiveController() { + const ControllerType type = getControllerType(getActiveCameraIndex()); + return getControllerByType(type); + } + + uint32_t CameraManager::addCamera(ControllerType controllerType) { + const float ratio = static_cast<float>(m_window.getWidth()) / static_cast<float>(m_window.getHeight()); + + Camera camera; + camera.setPerspective(glm::radians(60.0f), ratio, 0.1f, 10.0f); + return addCamera(controllerType, camera); + } + + uint32_t CameraManager::addCamera(ControllerType controllerType, const Camera &camera) { + const uint32_t index = static_cast<uint32_t>(m_cameras.size()); + m_cameras.push_back(camera); + m_cameraControllerTypes.push_back(controllerType); + return index; + } - float sensitivity = 0.05f; - xoffset *= sensitivity; - yoffset *= sensitivity; + Camera& CameraManager::getCamera(uint32_t cameraIndex) { + if (cameraIndex < 0 || cameraIndex > m_cameras.size() - 1) { + vkcv_log(LogLevel::ERROR, "Invalid camera index: The index must range from 0 to %lu", m_cameras.size()); + return getActiveCamera(); + } + + return m_cameras[cameraIndex]; + } - m_camera.panView( xoffset , yoffset ); + Camera& CameraManager::getActiveCamera() { + return m_cameras[getActiveCameraIndex()]; } - void CameraManager::scrollCallback(double offsetX, double offsetY) { - m_camera.changeFov(offsetY); + void CameraManager::setActiveCamera(uint32_t cameraIndex) { + if (cameraIndex < 0 || cameraIndex > m_cameras.size() - 1) { + vkcv_log(LogLevel::ERROR, "Invalid camera index: The index must range from 0 to %lu", m_cameras.size()); + return; + } + + m_activeCameraIndex = cameraIndex; } - void CameraManager::keyCallback(int key, int scancode, int action, int mods) { + uint32_t CameraManager::getActiveCameraIndex() const { + return m_activeCameraIndex; + } - switch (key) { - case GLFW_KEY_W: - m_camera.moveForward(action); - break; - case GLFW_KEY_S: - m_camera.moveBackward(action); - break; - case GLFW_KEY_A: - m_camera.moveLeft(action); - break; - case GLFW_KEY_D: - m_camera.moveRight(action); - break; - case GLFW_KEY_ESCAPE: - glfwSetWindowShouldClose(m_window.getWindow(), 1); - break; - default: - break; + void CameraManager::setControllerType(uint32_t cameraIndex, ControllerType controllerType) { + if (cameraIndex < 0 || cameraIndex > m_cameras.size() - 1) { + vkcv_log(LogLevel::ERROR, "Invalid camera index: The index must range from 0 to %lu", m_cameras.size()); + return; } + + m_cameraControllerTypes[cameraIndex] = controllerType; } - void CameraManager::resizeCallback(int width, int height){ - m_camera.updateRatio(width, height); + ControllerType CameraManager::getControllerType(uint32_t cameraIndex) { + if (cameraIndex < 0 || cameraIndex > m_cameras.size() - 1) { + vkcv_log(LogLevel::ERROR, "Invalid camera index: The index must range from 0 to %lu", m_cameras.size()); + return ControllerType::NONE; + } + + return m_cameraControllerTypes[cameraIndex]; } - Camera &CameraManager::getCamera(){ - return m_camera; + CameraController& CameraManager::getControllerByType(ControllerType controllerType) { + switch(controllerType) { + case ControllerType::PILOT: + return m_pilotController; + case ControllerType::TRACKBALL: + return m_trackController; + default: + return m_pilotController; + } } + void CameraManager::update(double deltaTime) { + getActiveController().updateCamera(deltaTime, getActiveCamera()); + } + } \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/PilotCameraController.cpp b/modules/camera/src/vkcv/camera/PilotCameraController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1a50a0efa4b4e75adb81ce869d6b927bd0046758 --- /dev/null +++ b/modules/camera/src/vkcv/camera/PilotCameraController.cpp @@ -0,0 +1,155 @@ +#include "vkcv/camera/PilotCameraController.hpp" + +#include <GLFW/glfw3.h> + +namespace vkcv::camera { + + PilotCameraController::PilotCameraController() { + m_forward = false; + m_backward = false; + m_upward = false; + m_downward = false; + m_left = false; + m_right = false; + + m_rotationActive = false; + + m_cameraSpeed = 2.0f; + + m_fov_nsteps = 100; + m_fov_min = 10; + m_fov_max = 120; + } + + void PilotCameraController::changeFov(double offset, Camera &camera){ + float fov = camera.getFov(); + float fov_range = m_fov_max - m_fov_min; + float fov_stepsize = glm::radians(fov_range) / static_cast<float>(m_fov_nsteps); + fov -= (float) offset*fov_stepsize; + if (fov < glm::radians(m_fov_min)) { + fov = glm::radians(m_fov_min); + } + if (fov > glm::radians(m_fov_max)) { + fov = glm::radians(m_fov_max); + } + camera.setFov(fov); + } + + void PilotCameraController::panView(double xOffset, double yOffset, Camera &camera) { + // handle yaw rotation + float yaw = camera.getYaw() + xOffset; + if (yaw < -180.0f) { + yaw += 360.0f; + } + else if (yaw > 180.0f) { + yaw -= 360.0f; + } + camera.setYaw(yaw); + + // handle pitch rotation + float pitch = camera.getPitch() - yOffset; + if (pitch > 89.0f) { + pitch = 89.0f; + } + if (pitch < -89.0f) { + pitch = -89.0f; + } + camera.setPitch(pitch); + } + + constexpr float getDirectionFactor(bool positive, bool negative) { + return static_cast<float>(positive) - static_cast<float>(negative); + } + + void PilotCameraController::updateCamera(double deltaTime, Camera &camera) { + glm::vec3 position = camera.getPosition(); + + const glm::vec3 front = camera.getFront(); + const glm::vec3 up = camera.getUp(); + const glm::vec3 left = glm::normalize(glm::cross(front, up)); + + const float distance = m_cameraSpeed * static_cast<float>(deltaTime); + + position += distance * getDirectionFactor(m_forward, m_backward) * front; + position += distance * getDirectionFactor(m_left, m_right) * left; + position += distance * getDirectionFactor(m_upward, m_downward) * up; + + camera.lookAt(position, position + front, up); + } + + void PilotCameraController::keyCallback(int key, int scancode, int action, int mods, Camera &camera) { + switch (key) { + case GLFW_KEY_W: + moveForward(action); + break; + case GLFW_KEY_S: + moveBackward(action); + break; + case GLFW_KEY_A: + moveLeft(action); + break; + case GLFW_KEY_D: + moveRight(action); + break; + case GLFW_KEY_E: + moveUpward(action); + break; + case GLFW_KEY_Q: + moveDownward(action); + break; + default: + break; + } + } + + void PilotCameraController::scrollCallback(double offsetX, double offsetY, Camera &camera) { + changeFov(offsetY, camera); + } + + void PilotCameraController::mouseMoveCallback(double xoffset, double yoffset, Camera &camera) { + if(!m_rotationActive){ + return; + } + + float sensitivity = 0.05f; + xoffset *= sensitivity; + yoffset *= sensitivity; + + panView(xoffset , yoffset, camera); + } + + void PilotCameraController::mouseButtonCallback(int button, int action, int mods, Camera &camera) { + if(button == GLFW_MOUSE_BUTTON_2 && m_rotationActive == false && action == GLFW_PRESS){ + m_rotationActive = true; + } + else if(button == GLFW_MOUSE_BUTTON_2 && m_rotationActive == true && action == GLFW_RELEASE){ + m_rotationActive = false; + } + } + + + void PilotCameraController::moveForward(int action){ + m_forward = static_cast<bool>(action); + } + + void PilotCameraController::moveBackward(int action){ + m_backward = static_cast<bool>(action); + } + + void PilotCameraController::moveLeft(int action){ + m_left = static_cast<bool>(action); + } + + void PilotCameraController::moveRight(int action){ + m_right = static_cast<bool>(action); + } + + void PilotCameraController::moveUpward(int action){ + m_upward = static_cast<bool>(action); + } + + void PilotCameraController::moveDownward(int action){ + m_downward = static_cast<bool>(action); + } + +} \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/TrackballCamera.cpp b/modules/camera/src/vkcv/camera/TrackballCamera.cpp deleted file mode 100644 index 3bbb8611dd234499fb9ba08ba87009c8c76660f6..0000000000000000000000000000000000000000 --- a/modules/camera/src/vkcv/camera/TrackballCamera.cpp +++ /dev/null @@ -1,146 +0,0 @@ -#include "vkcv/camera/TrackballCamera.hpp" - -namespace vkcv{ - - TrackballCamera::TrackballCamera( int width, int height, glm::mat4 projection) - { - setPosition( glm::vec3(0.0f, 0.0f, 5.0) ); - m_center = glm::vec3( 0.0f, 0.0f, 0.0f); - m_up = glm::vec3(0.0f, 1.0f, 0.0f); - - m_width = width; - m_height = height; - - m_sensitivity = 0.010f; - m_stepSize = 0.1f; - m_theta = glm::pi<float>() / 2.0f; - m_phi = 0.f; - m_radius = 1.5; - - m_view = glm::lookAt( m_center + getPosition(), m_center, m_up); - - m_oldX = width/2.f; - m_oldY = height/2.f; - - setProjection(projection); - } - - - TrackballCamera::TrackballCamera(int width, int height) - { - setPosition( glm::vec3(0.0f, 0.0f, 5.0)); - m_center = glm::vec3( 0.0f, 0.0f, 0.0f); - m_up = glm::vec3(0.0f, 1.0f, 0.0f); - - m_width = width; - m_height = height; - - m_sensitivity = 0.010f; - m_stepSize = 0.1f; - m_theta = glm::pi<float>() / 2.0f; - m_phi = 0.f; - m_radius = 1.5; - - m_view = glm::lookAt( m_center + getPosition(), m_center, m_up); - - m_oldX = width/2.f; - m_oldY = height/2.f; - - m_fov = glm::radians(60.f); - m_ratio = m_width / (float) m_height; - m_near = 0.001f; - m_far = 10.f; - glm::mat4 projection = glm::perspective(m_fov, m_ratio, m_near, m_far); - - setProjection(projection); - } - - TrackballCamera::~TrackballCamera() - { - } - - // TODO: Can be done as events... (mouseMove, mouseDown, mouseUp) - /*void TrackballCamera::update( GLFWwindow* window) { - - double x, y; - - glfwGetCursorPos( window, &x, &y); - if (glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) - { - float changeX = ((float) x - m_oldX) * m_sensitivity; - float changeY = ((float) y - m_oldY) * m_sensitivity; - - m_theta -= changeY; - if (m_theta < 0.01f) m_theta = 0.01f; - else if (m_theta > glm::pi<float>() - 0.01f) m_theta = glm::pi<float>() - 0.01f; - - m_phi -= changeX; - if (m_phi < 0) m_phi += 2*glm::pi<float>(); - else if (m_phi > 2*glm::pi<float>()) m_phi -= 2*glm::pi<float>(); - } - - m_oldX = (float) x; - m_oldY = (float) y; - - if (glfwGetKey( window, GLFW_KEY_UP) == GLFW_PRESS) - m_radius -= m_stepSize; - if (glfwGetKey( window, GLFW_KEY_DOWN) == GLFW_PRESS) - m_radius += m_stepSize; - if (m_radius < 0.1f) m_radius = 0.1f; - - m_position.x = m_center.x + m_radius * sin(m_theta) * sin(m_phi); - m_position.y = m_center.y + m_radius * cos(m_theta); - m_position.z = m_center.z + m_radius * sin(m_theta) * cos(m_phi); - - m_view = glm::lookAt( m_position, m_center, m_up); - - }*/ - - float TrackballCamera::getSensitivity() const { - return m_sensitivity; - } - - void TrackballCamera::setSensitivity(float sensitivity) { - m_sensitivity = sensitivity; - } - - float TrackballCamera::getStepSize() const { - return m_stepSize; - } - - void TrackballCamera::setStepSize(float stepSize) { - m_stepSize = stepSize; - } - - float TrackballCamera::getTheta() const { - return m_theta; - } - - void TrackballCamera::setTheta(float theta) { - m_theta = theta; - } - - float TrackballCamera::getPhi() const { - return m_phi; - } - - void TrackballCamera::setPhi(float phi) { - m_phi = phi; - } - - float TrackballCamera::getRadius() const { - return m_radius; - } - - void TrackballCamera::setRadius(float radius) { - m_radius = radius; - } - - const glm::vec3& TrackballCamera::getCenter() const { - return m_center; - } - - void TrackballCamera::setCenter(const glm::vec3 ¢er) { - m_center = center; - } -} \ No newline at end of file diff --git a/modules/camera/src/vkcv/camera/TrackballCameraController.cpp b/modules/camera/src/vkcv/camera/TrackballCameraController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..201c6ecdc1c703dbcd53b7dc4b179c86576f2312 --- /dev/null +++ b/modules/camera/src/vkcv/camera/TrackballCameraController.cpp @@ -0,0 +1,100 @@ +#include "vkcv/camera/TrackballCameraController.hpp" + +#include <GLFW/glfw3.h> + +namespace vkcv::camera { + + TrackballCameraController::TrackballCameraController() { + m_rotationActive = false; + m_radius = 3.0f; + m_cameraSpeed = 2.5f; + m_scrollSensitivity = 0.2f; + } + + void TrackballCameraController::setRadius(const float radius) { + if (radius < 0.1f) { + m_radius = 0.1f; + } + else { + m_radius = radius; + } + } + + void TrackballCameraController::panView(double xOffset, double yOffset, Camera &camera) { + // handle yaw rotation + float yaw = camera.getYaw() + xOffset * m_cameraSpeed; + if (yaw < 0.0f) { + yaw += 360.0f; + } + else if (yaw > 360.0f) { + yaw -= 360.0f; + } + camera.setYaw(yaw); + + // handle pitch rotation + float pitch = camera.getPitch() + yOffset * m_cameraSpeed; + if (pitch < 0.0f) { + pitch += 360.0f; + } + else if (pitch > 360.0f) { + pitch -= 360.0f; + } + camera.setPitch(pitch); + } + + void TrackballCameraController::updateRadius(double offset, Camera &camera) { + glm::vec3 cameraPosition = camera.getPosition(); + glm::vec3 cameraCenter = camera.getCenter(); + float radius = glm::length(cameraCenter - cameraPosition); // get current camera radius + setRadius(radius - offset * m_scrollSensitivity); + } + + void TrackballCameraController::updateCamera(double deltaTime, Camera &camera) { + float yaw = camera.getYaw(); + float pitch = camera.getPitch(); + + const glm::vec3 yAxis = glm::vec3(0.0f, 1.0f, 0.0f); + const glm::vec3 xAxis = glm::vec3(1.0f, 0.0f, 0.0f); + + const glm::mat4 rotationY = glm::rotate(glm::mat4(1.0f), glm::radians(yaw), yAxis); + const glm::mat4 rotationX = glm::rotate(rotationY, -glm::radians(pitch), xAxis); + const glm::vec3 translation = glm::vec3( + rotationX * glm::vec4(0.0f, 0.0f, m_radius, 0.0f) + ); + + const glm::vec3 center = camera.getCenter(); + const glm::vec3 position = center + translation; + const glm::vec3 up = glm::vec3( + rotationX * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f) + ); + + camera.lookAt(position, center, up); + } + + void TrackballCameraController::keyCallback(int key, int scancode, int action, int mods, Camera &camera) {} + + void TrackballCameraController::scrollCallback(double offsetX, double offsetY, Camera &camera) { + updateRadius(offsetY, camera); + } + + void TrackballCameraController::mouseMoveCallback(double xoffset, double yoffset, Camera &camera) { + if(!m_rotationActive){ + return; + } + + float sensitivity = 0.05f; + xoffset *= sensitivity; + yoffset *= sensitivity; + + panView(xoffset , yoffset, camera); + } + + void TrackballCameraController::mouseButtonCallback(int button, int action, int mods, Camera &camera) { + if(button == GLFW_MOUSE_BUTTON_2 && m_rotationActive == false && action == GLFW_PRESS){ + m_rotationActive = true; + } + else if(button == GLFW_MOUSE_BUTTON_2 && m_rotationActive == true && action == GLFW_RELEASE){ + m_rotationActive = false; + } + } +} \ No newline at end of file diff --git a/modules/gui/CMakeLists.txt b/modules/gui/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ce03f16e1f8d421f5b8e6c2fe913c0da04d34598 --- /dev/null +++ b/modules/gui/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.16) +project(vkcv_gui) + +# setting c++ standard for the module +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(vkcv_gui_source ${PROJECT_SOURCE_DIR}/src) +set(vkcv_gui_include ${PROJECT_SOURCE_DIR}/include) + +# Add source and header files to the module +set(vkcv_gui_sources + ${vkcv_gui_include}/vkcv/gui/GUI.hpp + ${vkcv_gui_source}/vkcv/gui/GUI.cpp + ) + +# Setup some path variables to load libraries +set(vkcv_gui_lib lib) +set(vkcv_gui_lib_path ${PROJECT_SOURCE_DIR}/${vkcv_gui_lib}) + +# Check and load IMGUI +include(config/ImGui.cmake) + +# adding source files to the module +add_library(vkcv_gui STATIC ${vkcv_gui_sources} ${vkcv_imgui_sources}) + +# link the required libraries to the module +target_link_libraries(vkcv_gui ${vkcv_gui_libraries} vkcv ${vkcv_libraries}) + +# including headers of dependencies and the VkCV framework +target_include_directories(vkcv_gui SYSTEM BEFORE PRIVATE ${vkcv_gui_includes} ${vkcv_include} ${vkcv_includes}) + +# add the own include directory for public headers +target_include_directories(vkcv_gui BEFORE PUBLIC ${vkcv_gui_include} ${vkcv_imgui_includes}) diff --git a/modules/gui/config/ImGui.cmake b/modules/gui/config/ImGui.cmake new file mode 100644 index 0000000000000000000000000000000000000000..3f55ad05c34783ba0e82c41d2cbc4e5b204d60e7 --- /dev/null +++ b/modules/gui/config/ImGui.cmake @@ -0,0 +1,17 @@ + +if (EXISTS "${vkcv_gui_lib_path}/imgui") + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/backends/imgui_impl_glfw.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/backends/imgui_impl_vulkan.cpp ) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui_draw.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui_demo.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui_tables.cpp) + list(APPEND vkcv_imgui_sources ${vkcv_gui_lib_path}/imgui/imgui_widgets.cpp) + + list(APPEND vkcv_imgui_includes ${vkcv_gui_lib}/imgui) + list(APPEND vkcv_imgui_includes ${vkcv_gui_lib}/imgui/backend) + + list(APPEND vkcv_gui_include ${vkcv_gui_lib}) +else() + message(WARNING "IMGUI is required..! Update the submodules!") +endif () diff --git a/modules/gui/include/vkcv/gui/GUI.hpp b/modules/gui/include/vkcv/gui/GUI.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d1a9986c5f69bfd9d4392bd5ae50f0b1f8b60642 --- /dev/null +++ b/modules/gui/include/vkcv/gui/GUI.hpp @@ -0,0 +1,62 @@ +#pragma once + +#include "imgui/imgui.h" +#include "imgui/backends/imgui_impl_glfw.h" +#include "imgui/backends/imgui_impl_vulkan.h" + +#include <vkcv/Core.hpp> +#include <vkcv/Window.hpp> + +namespace vkcv::gui { + + class GUI final { + private: + Window& m_window; + Core& m_core; + + const Context& m_context; + + ImGuiContext* m_gui_context; + + vk::DescriptorPool m_descriptor_pool; + vk::RenderPass m_render_pass; + + event_handle<int,int,int> f_mouseButton; + event_handle<double,double> f_mouseScroll; + event_handle<int,int,int,int> f_key; + event_handle<unsigned int> f_char; + + public: + /** + * Constructor of a new instance of ImGui management + * + * @param core Valid #Core instance of the framework + * @param window Valid #Window instance of the framework + */ + GUI(Core& core, Window& window); + + GUI(const GUI& other) = delete; + GUI(GUI&& other) = delete; + + GUI& operator=(const GUI& other) = delete; + GUI& operator=(GUI&& other) = delete; + + /** + * Destructor of a #GUI instance + */ + virtual ~GUI(); + + /** + * Sets up a new frame for ImGui to draw + */ + void beginGUI(); + + /** + * Ends a frame for ImGui, renders it and draws it onto + * the currently active swapchain image of the core (ready to present). + */ + void endGUI(); + + }; + +} diff --git a/modules/gui/lib/imgui b/modules/gui/lib/imgui new file mode 160000 index 0000000000000000000000000000000000000000..d5828cd988db525f27128edeadb1a689cd2d7461 --- /dev/null +++ b/modules/gui/lib/imgui @@ -0,0 +1 @@ +Subproject commit d5828cd988db525f27128edeadb1a689cd2d7461 diff --git a/modules/gui/src/vkcv/gui/GUI.cpp b/modules/gui/src/vkcv/gui/GUI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..096a857a13f01840d8a3a7e2bf74ba571bd2c249 --- /dev/null +++ b/modules/gui/src/vkcv/gui/GUI.cpp @@ -0,0 +1,239 @@ + +#include "vkcv/gui/GUI.hpp" + +#include <GLFW/glfw3.h> +#include <vkcv/Logger.hpp> + +namespace vkcv::gui { + + static void checkVulkanResult(VkResult resultCode) { + if (resultCode == 0) + return; + + const auto result = vk::Result(resultCode); + + vkcv_log(LogLevel::ERROR, "ImGui has a problem with Vulkan! (%s)", vk::to_string(result).c_str()); + } + + GUI::GUI(Core& core, Window& window) : + m_window(window), + m_core(core), + m_context(m_core.getContext()), + m_gui_context(nullptr) { + IMGUI_CHECKVERSION(); + + m_gui_context = ImGui::CreateContext(); + + ImGui_ImplGlfw_InitForVulkan(m_window.getWindow(), false); + + f_mouseButton = m_window.e_mouseButton.add([&](int button, int action, int mods) { + ImGui_ImplGlfw_MouseButtonCallback(m_window.getWindow(), button, action, mods); + }); + + f_mouseScroll = m_window.e_mouseScroll.add([&](double xoffset, double yoffset) { + ImGui_ImplGlfw_ScrollCallback(m_window.getWindow(), xoffset, yoffset); + }); + + f_key = m_window.e_key.add([&](int key, int scancode, int action, int mods) { + ImGui_ImplGlfw_KeyCallback(m_window.getWindow(), key, scancode, action, mods); + }); + + f_char = m_window.e_char.add([&](unsigned int c) { + ImGui_ImplGlfw_CharCallback(m_window.getWindow(), c); + }); + + vk::DescriptorPoolSize pool_sizes[] = { + vk::DescriptorPoolSize(vk::DescriptorType::eSampler, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eCombinedImageSampler, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eSampledImage, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eStorageImage, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eUniformTexelBuffer, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eStorageTexelBuffer, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eUniformBuffer, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eStorageBuffer, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eUniformBufferDynamic, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eStorageBufferDynamic, 1000), + vk::DescriptorPoolSize(vk::DescriptorType::eInputAttachment, 1000) + }; + + const vk::DescriptorPoolCreateInfo descriptorPoolCreateInfo ( + vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, + static_cast<uint32_t>(1000 * IM_ARRAYSIZE(pool_sizes)), + static_cast<uint32_t>(IM_ARRAYSIZE(pool_sizes)), + pool_sizes + ); + + m_descriptor_pool = m_context.getDevice().createDescriptorPool(descriptorPoolCreateInfo); + + const vk::PhysicalDevice& physicalDevice = m_context.getPhysicalDevice(); + const Swapchain& swapchain = m_core.getSwapchain(); + + const uint32_t graphicsQueueFamilyIndex = ( + m_context.getQueueManager().getGraphicsQueues()[0].familyIndex + ); + + ImGui_ImplVulkan_InitInfo init_info = {}; + init_info.Instance = m_context.getInstance(); + init_info.PhysicalDevice = m_context.getPhysicalDevice(); + init_info.Device = m_context.getDevice(); + init_info.QueueFamily = graphicsQueueFamilyIndex; + init_info.Queue = m_context.getQueueManager().getGraphicsQueues()[0].handle; + init_info.PipelineCache = nullptr; + init_info.DescriptorPool = m_descriptor_pool; + init_info.Allocator = nullptr; + init_info.MinImageCount = swapchain.getImageCount(); + init_info.ImageCount = swapchain.getImageCount(); + init_info.CheckVkResultFn = checkVulkanResult; + + const vk::AttachmentDescription attachment ( + vk::AttachmentDescriptionFlags(), + swapchain.getFormat(), + vk::SampleCountFlagBits::e1, + vk::AttachmentLoadOp::eLoad, + vk::AttachmentStoreOp::eStore, + vk::AttachmentLoadOp::eDontCare, + vk::AttachmentStoreOp::eDontCare, + vk::ImageLayout::eUndefined, + vk::ImageLayout::ePresentSrcKHR + ); + + const vk::AttachmentReference attachmentReference ( + 0, + vk::ImageLayout::eColorAttachmentOptimal + ); + + const vk::SubpassDescription subpass ( + vk::SubpassDescriptionFlags(), + vk::PipelineBindPoint::eGraphics, + 0, + nullptr, + 1, + &attachmentReference, + nullptr, + nullptr, + 0, + nullptr + ); + + const vk::SubpassDependency dependency ( + VK_SUBPASS_EXTERNAL, + 0, + vk::PipelineStageFlagBits::eColorAttachmentOutput, + vk::PipelineStageFlagBits::eColorAttachmentOutput, + vk::AccessFlags(), + vk::AccessFlagBits::eColorAttachmentWrite, + vk::DependencyFlags() + ); + + const vk::RenderPassCreateInfo passCreateInfo ( + vk::RenderPassCreateFlags(), + 1, + &attachment, + 1, + &subpass, + 1, + &dependency + ); + + m_render_pass = m_context.getDevice().createRenderPass(passCreateInfo); + + ImGui_ImplVulkan_Init(&init_info, m_render_pass); + + const SubmitInfo submitInfo { QueueType::Graphics, {}, {} }; + + m_core.recordAndSubmitCommands(submitInfo, [](const vk::CommandBuffer& commandBuffer) { + ImGui_ImplVulkan_CreateFontsTexture(commandBuffer); + }, []() { + ImGui_ImplVulkan_DestroyFontUploadObjects(); + }); + + m_context.getDevice().waitIdle(); + } + + GUI::~GUI() { + m_context.getDevice().waitIdle(); + + ImGui_ImplVulkan_Shutdown(); + + m_context.getDevice().destroyRenderPass(m_render_pass); + m_context.getDevice().destroyDescriptorPool(m_descriptor_pool); + + ImGui_ImplGlfw_Shutdown(); + + m_window.e_mouseButton.remove(f_mouseButton); + m_window.e_mouseScroll.remove(f_mouseScroll); + m_window.e_key.remove(f_key); + m_window.e_char.remove(f_char); + + if (m_gui_context) { + ImGui::DestroyContext(m_gui_context); + } + } + + void GUI::beginGUI() { + const Swapchain& swapchain = m_core.getSwapchain(); + const auto extent = swapchain.getExtent(); + + if ((extent.width > 0) && (extent.height > 0)) { + ImGui_ImplVulkan_SetMinImageCount(swapchain.getImageCount()); + } + + ImGui_ImplVulkan_NewFrame(); + ImGui_ImplGlfw_NewFrame(); + ImGui::NewFrame(); + } + + void GUI::endGUI() { + ImGui::Render(); + + ImDrawData* drawData = ImGui::GetDrawData(); + + if ((!drawData) || + (drawData->DisplaySize.x <= 0.0f) || + (drawData->DisplaySize.y <= 0.0f)) { + return; + } + + const Swapchain& swapchain = m_core.getSwapchain(); + const auto extent = swapchain.getExtent(); + + const vk::FramebufferCreateInfo framebufferCreateInfo ( + vk::FramebufferCreateFlags(), + m_render_pass, + 1, + &m_core.getSwapchainImageView(), + extent.width, + extent.height, + 1 + ); + + const vk::Framebuffer framebuffer = m_context.getDevice().createFramebuffer(framebufferCreateInfo); + + SubmitInfo submitInfo; + submitInfo.queueType = QueueType::Graphics; + + m_core.recordAndSubmitCommands(submitInfo, [&](const vk::CommandBuffer& commandBuffer) { + const vk::Rect2D renderArea ( + vk::Offset2D(0, 0), + extent + ); + + const vk::RenderPassBeginInfo beginInfo ( + m_render_pass, + framebuffer, + renderArea, + 0, + nullptr + ); + + commandBuffer.beginRenderPass(beginInfo, vk::SubpassContents::eInline); + + ImGui_ImplVulkan_RenderDrawData(drawData, commandBuffer); + + commandBuffer.endRenderPass(); + }, [&]() { + m_context.getDevice().destroyFramebuffer(framebuffer); + }); + } + +} diff --git a/modules/shader_compiler/CMakeLists.txt b/modules/shader_compiler/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4b674ec41ed4ea5f42dc73187c212e6a69952cec --- /dev/null +++ b/modules/shader_compiler/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.16) +project(vkcv_shader_compiler) + +# setting c++ standard for the module +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(vkcv_shader_compiler_source ${PROJECT_SOURCE_DIR}/src) +set(vkcv_shader_compiler_include ${PROJECT_SOURCE_DIR}/include) + +# Add source and header files to the module +set(vkcv_shader_compiler_sources + ${vkcv_shader_compiler_include}/vkcv/shader/GLSLCompiler.hpp + ${vkcv_shader_compiler_source}/vkcv/shader/GLSLCompiler.cpp +) + +# adding source files to the module +add_library(vkcv_shader_compiler STATIC ${vkcv_shader_compiler_sources}) + +# Setup some path variables to load libraries +set(vkcv_shader_compiler_lib lib) +set(vkcv_shader_compiler_lib_path ${PROJECT_SOURCE_DIR}/${vkcv_shader_compiler_lib}) + +# Check and load GLSLANG +include(config/GLSLANG.cmake) + +# link the required libraries to the module +target_link_libraries(vkcv_shader_compiler ${vkcv_shader_compiler_libraries} vkcv) + +# including headers of dependencies and the VkCV framework +target_include_directories(vkcv_shader_compiler SYSTEM BEFORE PRIVATE ${vkcv_shader_compiler_includes} ${vkcv_include}) + +# add the own include directory for public headers +target_include_directories(vkcv_shader_compiler BEFORE PUBLIC ${vkcv_shader_compiler_include}) diff --git a/modules/shader_compiler/config/GLSLANG.cmake b/modules/shader_compiler/config/GLSLANG.cmake new file mode 100644 index 0000000000000000000000000000000000000000..50b9fd46bd0db9421c632aa0b80fb8df7e3f2123 --- /dev/null +++ b/modules/shader_compiler/config/GLSLANG.cmake @@ -0,0 +1,28 @@ + +if (EXISTS "${vkcv_shader_compiler_lib_path}/glslang") + set(SKIP_GLSLANG_INSTALL ON CACHE INTERNAL "") + set(ENABLE_SPVREMAPPER OFF CACHE INTERNAL "") + set(ENABLE_GLSLANG_BINARIES OFF CACHE INTERNAL "") + set(ENABLE_GLSLANG_JS OFF CACHE INTERNAL "") + set(ENABLE_GLSLANG_WEBMIN OFF CACHE INTERNAL "") + set(ENABLE_GLSLANG_WEBMIN_DEVEL OFF CACHE INTERNAL "") + set(ENABLE_EMSCRIPTEN_SINGLE_FILE OFF CACHE INTERNAL "") + set(ENABLE_EMSCRIPTEN_ENVIRONMENT_NODE OFF CACHE INTERNAL "") + set(ENABLE_HLSL OFF CACHE INTERNAL "") + set(ENABLE_RTTI OFF CACHE INTERNAL "") + set(ENABLE_EXCEPTIONS OFF CACHE INTERNAL "") + set(ENABLE_OPT OFF CACHE INTERNAL "") + set(ENABLE_PCH OFF CACHE INTERNAL "") + set(ENABLE_CTEST OFF CACHE INTERNAL "") + set(USE_CCACHE OFF CACHE INTERNAL "") + + set(BUILD_SHARED_LIBS OFF CACHE INTERNAL "") + set(BUILD_EXTERNAL OFF CACHE INTERNAL "") + + add_subdirectory(${vkcv_shader_compiler_lib}/glslang) + + list(APPEND vkcv_shader_compiler_libraries glslang SPIRV) + list(APPEND vkcv_shader_compiler_includes ${vkcv_shader_compiler_lib}) +else() + message(WARNING "GLSLANG is required..! Update the submodules!") +endif () diff --git a/modules/shader_compiler/include/vkcv/shader/Compiler.hpp b/modules/shader_compiler/include/vkcv/shader/Compiler.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d7b7af7178531aea358cecbc8b86a29527173014 --- /dev/null +++ b/modules/shader_compiler/include/vkcv/shader/Compiler.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include <vkcv/Event.hpp> + +namespace vkcv::shader { + + typedef typename event_function<ShaderStage, const std::filesystem::path&>::type ShaderCompiledFunction; + + class Compiler { + private: + public: + virtual void compile(ShaderStage shaderStage, const std::filesystem::path& shaderPath, + const ShaderCompiledFunction& compiled, bool update = false) = 0; + + }; + +} diff --git a/modules/shader_compiler/include/vkcv/shader/GLSLCompiler.hpp b/modules/shader_compiler/include/vkcv/shader/GLSLCompiler.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7105d93a0c3e153bf3abe1d624d0c13c6f09ac6d --- /dev/null +++ b/modules/shader_compiler/include/vkcv/shader/GLSLCompiler.hpp @@ -0,0 +1,28 @@ +#pragma once + +#include <filesystem> + +#include <vkcv/ShaderStage.hpp> +#include "Compiler.hpp" + +namespace vkcv::shader { + + class GLSLCompiler { + private: + public: + GLSLCompiler(); + + GLSLCompiler(const GLSLCompiler& other); + GLSLCompiler(GLSLCompiler&& other) = default; + + ~GLSLCompiler(); + + GLSLCompiler& operator=(const GLSLCompiler& other); + GLSLCompiler& operator=(GLSLCompiler&& other) = default; + + void compile(ShaderStage shaderStage, const std::filesystem::path& shaderPath, + const ShaderCompiledFunction& compiled, bool update = false); + + }; + +} diff --git a/modules/shader_compiler/lib/glslang b/modules/shader_compiler/lib/glslang new file mode 160000 index 0000000000000000000000000000000000000000..fe15158676657bf965e41c32e15ae5db7ea2ab6a --- /dev/null +++ b/modules/shader_compiler/lib/glslang @@ -0,0 +1 @@ +Subproject commit fe15158676657bf965e41c32e15ae5db7ea2ab6a diff --git a/modules/shader_compiler/src/vkcv/shader/GLSLCompiler.cpp b/modules/shader_compiler/src/vkcv/shader/GLSLCompiler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e07dec255d283b4b8a8d4fcc769083498c10264 --- /dev/null +++ b/modules/shader_compiler/src/vkcv/shader/GLSLCompiler.cpp @@ -0,0 +1,268 @@ + +#include "vkcv/shader/GLSLCompiler.hpp" + +#include <fstream> +#include <glslang/SPIRV/GlslangToSpv.h> + +#include <vkcv/Logger.hpp> + +namespace vkcv::shader { + + static uint32_t s_CompilerCount = 0; + + GLSLCompiler::GLSLCompiler() { + if (s_CompilerCount == 0) { + glslang::InitializeProcess(); + } + + s_CompilerCount++; + } + + GLSLCompiler::GLSLCompiler(const GLSLCompiler &other) { + s_CompilerCount++; + } + + GLSLCompiler::~GLSLCompiler() { + s_CompilerCount--; + + if (s_CompilerCount == 0) { + glslang::FinalizeProcess(); + } + } + + GLSLCompiler &GLSLCompiler::operator=(const GLSLCompiler &other) { + s_CompilerCount++; + return *this; + } + + constexpr EShLanguage findShaderLanguage(ShaderStage shaderStage) { + switch (shaderStage) { + case ShaderStage::VERTEX: + return EShLangVertex; + case ShaderStage::TESS_CONTROL: + return EShLangTessControl; + case ShaderStage::TESS_EVAL: + return EShLangTessEvaluation; + case ShaderStage::GEOMETRY: + return EShLangGeometry; + case ShaderStage::FRAGMENT: + return EShLangFragment; + case ShaderStage::COMPUTE: + return EShLangCompute; + default: + return EShLangCount; + } + } + + static void initResources(TBuiltInResource& resources) { + resources.maxLights = 32; + resources.maxClipPlanes = 6; + resources.maxTextureUnits = 32; + resources.maxTextureCoords = 32; + resources.maxVertexAttribs = 64; + resources.maxVertexUniformComponents = 4096; + resources.maxVaryingFloats = 64; + resources.maxVertexTextureImageUnits = 32; + resources.maxCombinedTextureImageUnits = 80; + resources.maxTextureImageUnits = 32; + resources.maxFragmentUniformComponents = 4096; + resources.maxDrawBuffers = 32; + resources.maxVertexUniformVectors = 128; + resources.maxVaryingVectors = 8; + resources.maxFragmentUniformVectors = 16; + resources.maxVertexOutputVectors = 16; + resources.maxFragmentInputVectors = 15; + resources.minProgramTexelOffset = -8; + resources.maxProgramTexelOffset = 7; + resources.maxClipDistances = 8; + resources.maxComputeWorkGroupCountX = 65535; + resources.maxComputeWorkGroupCountY = 65535; + resources.maxComputeWorkGroupCountZ = 65535; + resources.maxComputeWorkGroupSizeX = 1024; + resources.maxComputeWorkGroupSizeY = 1024; + resources.maxComputeWorkGroupSizeZ = 64; + resources.maxComputeUniformComponents = 1024; + resources.maxComputeTextureImageUnits = 16; + resources.maxComputeImageUniforms = 8; + resources.maxComputeAtomicCounters = 8; + resources.maxComputeAtomicCounterBuffers = 1; + resources.maxVaryingComponents = 60; + resources.maxVertexOutputComponents = 64; + resources.maxGeometryInputComponents = 64; + resources.maxGeometryOutputComponents = 128; + resources.maxFragmentInputComponents = 128; + resources.maxImageUnits = 8; + resources.maxCombinedImageUnitsAndFragmentOutputs = 8; + resources.maxCombinedShaderOutputResources = 8; + resources.maxImageSamples = 0; + resources.maxVertexImageUniforms = 0; + resources.maxTessControlImageUniforms = 0; + resources.maxTessEvaluationImageUniforms = 0; + resources.maxGeometryImageUniforms = 0; + resources.maxFragmentImageUniforms = 8; + resources.maxCombinedImageUniforms = 8; + resources.maxGeometryTextureImageUnits = 16; + resources.maxGeometryOutputVertices = 256; + resources.maxGeometryTotalOutputComponents = 1024; + resources.maxGeometryUniformComponents = 1024; + resources.maxGeometryVaryingComponents = 64; + resources.maxTessControlInputComponents = 128; + resources.maxTessControlOutputComponents = 128; + resources.maxTessControlTextureImageUnits = 16; + resources.maxTessControlUniformComponents = 1024; + resources.maxTessControlTotalOutputComponents = 4096; + resources.maxTessEvaluationInputComponents = 128; + resources.maxTessEvaluationOutputComponents = 128; + resources.maxTessEvaluationTextureImageUnits = 16; + resources.maxTessEvaluationUniformComponents = 1024; + resources.maxTessPatchComponents = 120; + resources.maxPatchVertices = 32; + resources.maxTessGenLevel = 64; + resources.maxViewports = 16; + resources.maxVertexAtomicCounters = 0; + resources.maxTessControlAtomicCounters = 0; + resources.maxTessEvaluationAtomicCounters = 0; + resources.maxGeometryAtomicCounters = 0; + resources.maxFragmentAtomicCounters = 8; + resources.maxCombinedAtomicCounters = 8; + resources.maxAtomicCounterBindings = 1; + resources.maxVertexAtomicCounterBuffers = 0; + resources.maxTessControlAtomicCounterBuffers = 0; + resources.maxTessEvaluationAtomicCounterBuffers = 0; + resources.maxGeometryAtomicCounterBuffers = 0; + resources.maxFragmentAtomicCounterBuffers = 1; + resources.maxCombinedAtomicCounterBuffers = 1; + resources.maxAtomicCounterBufferSize = 16384; + resources.maxTransformFeedbackBuffers = 4; + resources.maxTransformFeedbackInterleavedComponents = 64; + resources.maxCullDistances = 8; + resources.maxCombinedClipAndCullDistances = 8; + resources.maxSamples = 4; + resources.maxMeshOutputVerticesNV = 256; + resources.maxMeshOutputPrimitivesNV = 512; + resources.maxMeshWorkGroupSizeX_NV = 32; + resources.maxMeshWorkGroupSizeY_NV = 1; + resources.maxMeshWorkGroupSizeZ_NV = 1; + resources.maxTaskWorkGroupSizeX_NV = 32; + resources.maxTaskWorkGroupSizeY_NV = 1; + resources.maxTaskWorkGroupSizeZ_NV = 1; + resources.maxMeshViewCountNV = 4; + resources.limits.nonInductiveForLoops = 1; + resources.limits.whileLoops = 1; + resources.limits.doWhileLoops = 1; + resources.limits.generalUniformIndexing = 1; + resources.limits.generalAttributeMatrixVectorIndexing = 1; + resources.limits.generalVaryingIndexing = 1; + resources.limits.generalSamplerIndexing = 1; + resources.limits.generalVariableIndexing = 1; + resources.limits.generalConstantMatrixVectorIndexing = 1; + } + + static std::vector<char> readShaderCode(const std::filesystem::path &shaderPath) { + std::ifstream file (shaderPath.string(), std::ios::ate); + + if (!file.is_open()) { + vkcv_log(LogLevel::ERROR, "The file could not be opened (%s)", shaderPath.string().c_str()); + return std::vector<char>{}; + } + + std::streamsize fileSize = file.tellg(); + std::vector<char> buffer (fileSize + 1); + + file.seekg(0); + file.read(buffer.data(), fileSize); + file.close(); + + buffer[fileSize] = '\0'; + return buffer; + } + + static bool writeSpirvCode(const std::filesystem::path &shaderPath, const std::vector<uint32_t>& spirv) { + std::ofstream file (shaderPath.string(), std::ios::out | std::ios::binary); + + if (!file.is_open()) { + vkcv_log(LogLevel::ERROR, "The file could not be opened (%s)", shaderPath.string().c_str()); + return false; + } + + const auto fileSize = static_cast<std::streamsize>( + sizeof(uint32_t) * spirv.size() + ); + + file.seekp(0); + file.write(reinterpret_cast<const char*>(spirv.data()), fileSize); + file.close(); + + return true; + } + + void GLSLCompiler::compile(ShaderStage shaderStage, const std::filesystem::path &shaderPath, + const ShaderCompiledFunction& compiled, bool update) { + const EShLanguage language = findShaderLanguage(shaderStage); + + if (language == EShLangCount) { + vkcv_log(LogLevel::ERROR, "Shader stage not supported (%s)", shaderPath.string().c_str()); + return; + } + + const std::vector<char> code = readShaderCode(shaderPath); + + glslang::TShader shader (language); + glslang::TProgram program; + + const char *shaderStrings [1]; + shaderStrings[0] = code.data(); + + shader.setStrings(shaderStrings, 1); + + TBuiltInResource resources = {}; + initResources(resources); + + const auto messages = (EShMessages) ( + EShMsgSpvRules | + EShMsgVulkanRules + ); + + if (!shader.parse(&resources, 100, false, messages)) { + vkcv_log(LogLevel::ERROR, "Shader parsing failed {\n%s\n%s\n} (%s)", + shader.getInfoLog(), shader.getInfoDebugLog(), shaderPath.string().c_str()); + return; + } + + program.addShader(&shader); + + if (!program.link(messages)) { + vkcv_log(LogLevel::ERROR, "Shader linking failed {\n%s\n%s\n} (%s)", + shader.getInfoLog(), shader.getInfoDebugLog(), shaderPath.string().c_str()); + return; + } + + const glslang::TIntermediate* intermediate = program.getIntermediate(language); + + if (!intermediate) { + vkcv_log(LogLevel::ERROR, "No valid intermediate representation (%s)", shaderPath.string().c_str()); + return; + } + + std::vector<uint32_t> spirv; + glslang::GlslangToSpv(*intermediate, spirv); + + const std::filesystem::path tmp_path (std::tmpnam(nullptr)); + + if (!writeSpirvCode(tmp_path, spirv)) { + vkcv_log(LogLevel::ERROR, "Spir-V could not be written to disk (%s)", shaderPath.string().c_str()); + return; + } + + if (compiled) { + compiled(shaderStage, tmp_path); + } + + std::filesystem::remove(tmp_path); + + if (update) { + // TODO: Shader hot compilation during runtime + } + } + +} diff --git a/projects/CMakeLists.txt b/projects/CMakeLists.txt index ccbdaf4101c5dabb3e9d43788e255eab85ad5776..474c9764bd29053c95ca2c4511d1287359350d02 100644 --- a/projects/CMakeLists.txt +++ b/projects/CMakeLists.txt @@ -2,4 +2,5 @@ # Add new projects/examples here: add_subdirectory(first_triangle) add_subdirectory(first_mesh) +add_subdirectory(first_scene) add_subdirectory(cmd_sync_test) \ No newline at end of file diff --git a/projects/cmd_sync_test/src/main.cpp b/projects/cmd_sync_test/src/main.cpp index a0fb29fafe24a4ae1279161dc8814c0d8f52765f..7ec54582aac6b16a484b74183036539e91cfe731 100644 --- a/projects/cmd_sync_test/src/main.cpp +++ b/projects/cmd_sync_test/src/main.cpp @@ -18,9 +18,15 @@ int main(int argc, const char** argv) { true ); - vkcv::CameraManager cameraManager(window, windowWidth, windowHeight); - cameraManager.getCamera().setPosition(glm::vec3(0.f, 0.f, 3.f)); - cameraManager.getCamera().setNearFar(0.1, 30); + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex2 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex).setPosition(glm::vec3(0.f, 0.f, 3.f)); + cameraManager.getCamera(camIndex).setNearFar(0.1f, 30.0f); + cameraManager.getCamera(camIndex).setYaw(180.0f); + + cameraManager.getCamera(camIndex2).setNearFar(0.1f, 30.0f); window.initEvents(); @@ -33,10 +39,10 @@ int main(int argc, const char** argv) { { "VK_KHR_swapchain" } ); - vkcv::asset::Mesh mesh; + vkcv::asset::Scene mesh; const char* path = argc > 1 ? argv[1] : "resources/cube/cube.gltf"; - int result = vkcv::asset::loadMesh(path, mesh); + int result = vkcv::asset::loadScene(path, mesh); if (result == 1) { std::cout << "Mesh loading successful!" << std::endl; @@ -65,7 +71,7 @@ int main(int argc, const char** argv) { auto& attributes = mesh.vertexGroups[0].vertexBuffer.attributes; - std::sort(attributes.begin(), attributes.end(), [](const vkcv::VertexAttribute& x, const vkcv::VertexAttribute& y) { + std::sort(attributes.begin(), attributes.end(), [](const vkcv::asset::VertexAttribute& x, const vkcv::asset::VertexAttribute& y) { return static_cast<uint32_t>(x.type) < static_cast<uint32_t>(y.type); }); @@ -80,7 +86,7 @@ int main(int argc, const char** argv) { const vkcv::AttachmentDescription present_color_attachment( vkcv::AttachmentOperation::STORE, vkcv::AttachmentOperation::CLEAR, - core.getSwapchainImageFormat() + core.getSwapchain().getFormat() ); const vkcv::AttachmentDescription depth_attachment( @@ -89,45 +95,52 @@ int main(int argc, const char** argv) { vk::Format::eD32Sfloat ); - vkcv::PassConfig trianglePassDefinition({ present_color_attachment, depth_attachment }); - vkcv::PassHandle trianglePass = core.createPass(trianglePassDefinition); + vkcv::PassConfig firstMeshPassDefinition({ present_color_attachment, depth_attachment }); + vkcv::PassHandle firstMeshPass = core.createPass(firstMeshPassDefinition); - if (!trianglePass) { + if (!firstMeshPass) { std::cout << "Error. Could not create renderpass. Exiting." << std::endl; return EXIT_FAILURE; } - vkcv::ShaderProgram triangleShaderProgram{}; - triangleShaderProgram.addShader(vkcv::ShaderStage::VERTEX, std::filesystem::path("resources/shaders/vert.spv")); - triangleShaderProgram.addShader(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("resources/shaders/frag.spv")); - triangleShaderProgram.reflectShader(vkcv::ShaderStage::VERTEX); - triangleShaderProgram.reflectShader(vkcv::ShaderStage::FRAGMENT); - - std::vector<vkcv::DescriptorBinding> descriptorBindings = { - vkcv::DescriptorBinding(vkcv::DescriptorType::IMAGE_SAMPLED, 1, vkcv::ShaderStage::FRAGMENT), - vkcv::DescriptorBinding(vkcv::DescriptorType::SAMPLER, 1, vkcv::ShaderStage::FRAGMENT), - vkcv::DescriptorBinding(vkcv::DescriptorType::UNIFORM_BUFFER, 1, vkcv::ShaderStage::FRAGMENT), - vkcv::DescriptorBinding(vkcv::DescriptorType::IMAGE_SAMPLED, 1, vkcv::ShaderStage::FRAGMENT) , - vkcv::DescriptorBinding(vkcv::DescriptorType::SAMPLER, 1, vkcv::ShaderStage::FRAGMENT) }; + vkcv::ShaderProgram firstMeshProgram{}; + firstMeshProgram.addShader(vkcv::ShaderStage::VERTEX, std::filesystem::path("resources/shaders/vert.spv")); + firstMeshProgram.addShader(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("resources/shaders/frag.spv")); + + const std::vector<vkcv::VertexAttachment> vertexAttachments = firstMeshProgram.getVertexAttachments(); + + std::vector<vkcv::VertexBinding> bindings; + for (size_t i = 0; i < vertexAttachments.size(); i++) { + bindings.push_back(vkcv::VertexBinding(i, { vertexAttachments[i] })); + } + + const vkcv::VertexLayout firstMeshLayout (bindings); + + std::vector<vkcv::DescriptorBinding> descriptorBindings = { firstMeshProgram.getReflectedDescriptors()[0] }; vkcv::DescriptorSetHandle descriptorSet = core.createDescriptorSet(descriptorBindings); - const vkcv::PipelineConfig trianglePipelineDefinition( - triangleShaderProgram, + const vkcv::PipelineConfig firstMeshPipelineConfig { + firstMeshProgram, windowWidth, windowHeight, - trianglePass, - attributes, + firstMeshPass, + firstMeshLayout, { core.getDescriptorSet(descriptorSet).layout }, - true); - vkcv::PipelineHandle trianglePipeline = core.createGraphicsPipeline(trianglePipelineDefinition); + true + }; - if (!trianglePipeline) { + vkcv::PipelineHandle firstMeshPipeline = core.createGraphicsPipeline(firstMeshPipelineConfig); + + if (!firstMeshPipeline) { std::cout << "Error. Could not create graphics pipeline. Exiting." << std::endl; return EXIT_FAILURE; } - vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, mesh.texture_hack.w, mesh.texture_hack.h); - texture.fill(mesh.texture_hack.img); + //vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, mesh.texture_hack.w, mesh.texture_hack.h); + //texture.fill(mesh.texture_hack.img); + vkcv::asset::Texture &tex = mesh.textures[0]; + vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, tex.w, tex.h); + texture.fill(tex.data.data()); vkcv::SamplerHandle sampler = core.createSampler( vkcv::SamplerFilterType::LINEAR, @@ -174,8 +187,6 @@ int main(int argc, const char** argv) { vkcv::ShaderProgram shadowShader; shadowShader.addShader(vkcv::ShaderStage::VERTEX, "resources/shaders/shadow_vert.spv"); shadowShader.addShader(vkcv::ShaderStage::FRAGMENT, "resources/shaders/shadow_frag.spv"); - shadowShader.reflectShader(vkcv::ShaderStage::VERTEX); - shadowShader.reflectShader(vkcv::ShaderStage::FRAGMENT); const vk::Format shadowMapFormat = vk::Format::eD16Unorm; const std::vector<vkcv::AttachmentDescription> shadowAttachments = { @@ -186,14 +197,16 @@ int main(int argc, const char** argv) { const uint32_t shadowMapResolution = 1024; const vkcv::Image shadowMap = core.createImage(shadowMapFormat, shadowMapResolution, shadowMapResolution, 1); - const vkcv::PipelineConfig shadowPipeConfig( + const vkcv::PipelineConfig shadowPipeConfig { shadowShader, shadowMapResolution, shadowMapResolution, - shadowPass, - attributes, - {}, - false); + shadowPass, + firstMeshLayout, + {}, + false + }; + const vkcv::PipelineHandle shadowPipe = core.createGraphicsPipeline(shadowPipeConfig); struct LightInfo { @@ -212,7 +225,7 @@ int main(int argc, const char** argv) { vkcv::SamplerDescriptorWrite(1, sampler), vkcv::SamplerDescriptorWrite(4, shadowSampler) }; setWrites.uniformBufferWrites = { vkcv::UniformBufferDescriptorWrite(2, lightBuffer.getHandle()) }; - core.writeResourceDescription(descriptorSet, 0, setWrites); + core.writeDescriptorSet(descriptorSet, setWrites); auto start = std::chrono::system_clock::now(); const auto appStartTime = start; @@ -233,10 +246,13 @@ int main(int argc, const char** argv) { auto end = std::chrono::system_clock::now(); auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); + start = end; - cameraManager.getCamera().updateView(deltatime.count() * 0.000001); + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); - const float sunTheta = std::chrono::duration_cast<std::chrono::milliseconds>(end - appStartTime).count() * 0.001f; + auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - appStartTime); + + const float sunTheta = 0.001f * static_cast<float>(duration.count()); lightInfo.direction = glm::normalize(glm::vec3(std::cos(sunTheta), 1, std::sin(sunTheta))); const float shadowProjectionSize = 5.f; @@ -258,7 +274,7 @@ int main(int argc, const char** argv) { lightInfo.lightMatrix = projectionLight * viewLight; lightBuffer.fill({ lightInfo }); - const glm::mat4 viewProjectionCamera = cameraManager.getCamera().getProjection() * cameraManager.getCamera().getView(); + const glm::mat4 viewProjectionCamera = cameraManager.getActiveCamera().getMVP(); mainPassMatrices.clear(); mvpLight.clear(); @@ -286,8 +302,8 @@ int main(int argc, const char** argv) { core.recordDrawcallsToCmdStream( cmdStream, - trianglePass, - trianglePipeline, + firstMeshPass, + firstMeshPipeline, pushConstantData, drawcalls, renderTargets); diff --git a/projects/first_mesh/resources/Szene/Szene.bin b/projects/first_mesh/resources/Szene/Szene.bin new file mode 100644 index 0000000000000000000000000000000000000000..c87d27637516b0bbf864251dd162773f5cc53e06 --- /dev/null +++ b/projects/first_mesh/resources/Szene/Szene.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee4742718f720d589a2a03f5d879f8c50ba9057718d191a43b046eaa9071080d +size 70328 diff --git a/projects/first_mesh/resources/Szene/Szene.gltf b/projects/first_mesh/resources/Szene/Szene.gltf new file mode 100644 index 0000000000000000000000000000000000000000..e5a32b29af5d0a2ac5f497e60b4b92c1873e1df9 --- /dev/null +++ b/projects/first_mesh/resources/Szene/Szene.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75ba834118792ebbacf528a1690c7d04df4b4c8122b9f99a9aa9a9d075d2c86a +size 7421 diff --git a/projects/first_mesh/resources/Szene/boards2_vcyc.jpg b/projects/first_mesh/resources/Szene/boards2_vcyc.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2636039e272289c0fba3fa2d88a060b857501248 --- /dev/null +++ b/projects/first_mesh/resources/Szene/boards2_vcyc.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca33a6e58ddd1b37a6e6853a9aa0e7b15ca678937119194752393dd2a0a0564 +size 1192476 diff --git a/projects/first_mesh/resources/Szene/boards2_vcyc_jpg.jpg b/projects/first_mesh/resources/Szene/boards2_vcyc_jpg.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2636039e272289c0fba3fa2d88a060b857501248 --- /dev/null +++ b/projects/first_mesh/resources/Szene/boards2_vcyc_jpg.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca33a6e58ddd1b37a6e6853a9aa0e7b15ca678937119194752393dd2a0a0564 +size 1192476 diff --git a/projects/first_mesh/src/main.cpp b/projects/first_mesh/src/main.cpp index 599eae46ca0243d7eaacc06ec59c713edd5f1e72..6377a6726d3e9d1830518206133dd7780593d576 100644 --- a/projects/first_mesh/src/main.cpp +++ b/projects/first_mesh/src/main.cpp @@ -18,8 +18,6 @@ int main(int argc, const char** argv) { true ); - vkcv::CameraManager cameraManager(window, static_cast<float>(window.getWidth()), static_cast<float>(window.getHeight())); - window.initEvents(); vkcv::Core core = vkcv::Core::create( @@ -31,10 +29,10 @@ int main(int argc, const char** argv) { { "VK_KHR_swapchain" } ); - vkcv::asset::Mesh mesh; + vkcv::asset::Scene mesh; const char* path = argc > 1 ? argv[1] : "resources/cube/cube.gltf"; - int result = vkcv::asset::loadMesh(path, mesh); + int result = vkcv::asset::loadScene(path, mesh); if (result == 1) { std::cout << "Mesh loading successful!" << std::endl; @@ -65,7 +63,7 @@ int main(int argc, const char** argv) { const vkcv::AttachmentDescription present_color_attachment( vkcv::AttachmentOperation::STORE, vkcv::AttachmentOperation::CLEAR, - core.getSwapchainImageFormat() + core.getSwapchain().getFormat() ); const vkcv::AttachmentDescription depth_attachment( @@ -74,48 +72,57 @@ int main(int argc, const char** argv) { vk::Format::eD32Sfloat ); - vkcv::PassConfig trianglePassDefinition({ present_color_attachment, depth_attachment }); - vkcv::PassHandle trianglePass = core.createPass(trianglePassDefinition); + vkcv::PassConfig firstMeshPassDefinition({ present_color_attachment, depth_attachment }); + vkcv::PassHandle firstMeshPass = core.createPass(firstMeshPassDefinition); - if (!trianglePass) { + if (!firstMeshPass) { std::cout << "Error. Could not create renderpass. Exiting." << std::endl; return EXIT_FAILURE; } - vkcv::ShaderProgram triangleShaderProgram{}; - triangleShaderProgram.addShader(vkcv::ShaderStage::VERTEX, std::filesystem::path("resources/shaders/vert.spv")); - triangleShaderProgram.addShader(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("resources/shaders/frag.spv")); - triangleShaderProgram.reflectShader(vkcv::ShaderStage::VERTEX); - triangleShaderProgram.reflectShader(vkcv::ShaderStage::FRAGMENT); + vkcv::ShaderProgram firstMeshProgram{}; + firstMeshProgram.addShader(vkcv::ShaderStage::VERTEX, std::filesystem::path("resources/shaders/vert.spv")); + firstMeshProgram.addShader(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("resources/shaders/frag.spv")); auto& attributes = mesh.vertexGroups[0].vertexBuffer.attributes; - std::sort(attributes.begin(), attributes.end(), [](const vkcv::VertexAttribute& x, const vkcv::VertexAttribute& y) { + std::sort(attributes.begin(), attributes.end(), [](const vkcv::asset::VertexAttribute& x, const vkcv::asset::VertexAttribute& y) { return static_cast<uint32_t>(x.type) < static_cast<uint32_t>(y.type); }); - std::vector<vkcv::DescriptorBinding> descriptorBindings = { - vkcv::DescriptorBinding(vkcv::DescriptorType::IMAGE_SAMPLED, 1, vkcv::ShaderStage::FRAGMENT), - vkcv::DescriptorBinding(vkcv::DescriptorType::SAMPLER, 1, vkcv::ShaderStage::FRAGMENT) }; + const std::vector<vkcv::VertexAttachment> vertexAttachments = firstMeshProgram.getVertexAttachments(); + std::vector<vkcv::VertexBinding> bindings; + for (size_t i = 0; i < vertexAttachments.size(); i++) { + bindings.push_back(vkcv::VertexBinding(i, { vertexAttachments[i] })); + } + + const vkcv::VertexLayout firstMeshLayout (bindings); + + uint32_t setID = 0; + std::vector<vkcv::DescriptorBinding> descriptorBindings = { firstMeshProgram.getReflectedDescriptors()[setID] }; vkcv::DescriptorSetHandle descriptorSet = core.createDescriptorSet(descriptorBindings); - const vkcv::PipelineConfig trianglePipelineDefinition( - triangleShaderProgram, + const vkcv::PipelineConfig firstMeshPipelineConfig { + firstMeshProgram, UINT32_MAX, UINT32_MAX, - trianglePass, - mesh.vertexGroups[0].vertexBuffer.attributes, + firstMeshPass, + {firstMeshLayout}, { core.getDescriptorSet(descriptorSet).layout }, - true); - vkcv::PipelineHandle trianglePipeline = core.createGraphicsPipeline(trianglePipelineDefinition); + true + }; + vkcv::PipelineHandle firstMeshPipeline = core.createGraphicsPipeline(firstMeshPipelineConfig); - if (!trianglePipeline) { + if (!firstMeshPipeline) { std::cout << "Error. Could not create graphics pipeline. Exiting." << std::endl; return EXIT_FAILURE; } - vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, mesh.texture_hack.w, mesh.texture_hack.h); - texture.fill(mesh.texture_hack.img); + // FIXME There should be a test here to make sure there is at least 1 + // texture in the mesh. + vkcv::asset::Texture &tex = mesh.textures[0]; + vkcv::Image texture = core.createImage(vk::Format::eR8G8B8A8Srgb, tex.w, tex.h); + texture.fill(tex.data.data()); vkcv::SamplerHandle sampler = core.createSampler( vkcv::SamplerFilterType::LINEAR, @@ -125,15 +132,14 @@ int main(int argc, const char** argv) { ); const std::vector<vkcv::VertexBufferBinding> vertexBufferBindings = { - vkcv::VertexBufferBinding( mesh.vertexGroups[0].vertexBuffer.attributes[0].offset, vertexBuffer.getVulkanHandle() ), - vkcv::VertexBufferBinding( mesh.vertexGroups[0].vertexBuffer.attributes[1].offset, vertexBuffer.getVulkanHandle() ), - vkcv::VertexBufferBinding( mesh.vertexGroups[0].vertexBuffer.attributes[2].offset, vertexBuffer.getVulkanHandle() ) - }; + vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[0].offset), vertexBuffer.getVulkanHandle()), + vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[1].offset), vertexBuffer.getVulkanHandle()), + vkcv::VertexBufferBinding(static_cast<vk::DeviceSize>(attributes[2].offset), vertexBuffer.getVulkanHandle()) }; vkcv::DescriptorWrites setWrites; - setWrites.sampledImageWrites = { vkcv::SampledImageDescriptorWrite(0, texture.getHandle()) }; - setWrites.samplerWrites = { vkcv::SamplerDescriptorWrite(1, sampler) }; - core.writeResourceDescription(descriptorSet, 0, setWrites); + setWrites.sampledImageWrites = { vkcv::SampledImageDescriptorWrite(0, texture.getHandle()) }; + setWrites.samplerWrites = { vkcv::SamplerDescriptorWrite(1, sampler) }; + core.writeDescriptorSet(descriptorSet, setWrites); vkcv::ImageHandle depthBuffer = core.createImage(vk::Format::eD32Sfloat, windowWidth, windowHeight).getHandle(); @@ -144,7 +150,14 @@ int main(int argc, const char** argv) { vkcv::DescriptorSetUsage descriptorUsage(0, core.getDescriptorSet(descriptorSet).vulkanHandle); vkcv::DrawcallInfo drawcall(renderMesh, { descriptorUsage }); - auto start = std::chrono::system_clock::now(); + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex0 = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex1 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex0).setPosition(glm::vec3(0, 0, -3)); + + auto start = std::chrono::system_clock::now(); + while (window.isWindowOpen()) { vkcv::Window::pollEvents(); @@ -164,10 +177,11 @@ int main(int argc, const char** argv) { } auto end = std::chrono::system_clock::now(); - auto deltatime = end - start; + auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); + start = end; - cameraManager.getCamera().updateView(std::chrono::duration<double>(deltatime).count()); - const glm::mat4 mvp = cameraManager.getCamera().getProjection() * cameraManager.getCamera().getView(); + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); + glm::mat4 mvp = cameraManager.getActiveCamera().getMVP(); vkcv::PushConstantData pushConstantData((void*)&mvp, sizeof(glm::mat4)); @@ -176,14 +190,13 @@ int main(int argc, const char** argv) { core.recordDrawcallsToCmdStream( cmdStream, - trianglePass, - trianglePipeline, + firstMeshPass, + firstMeshPipeline, pushConstantData, { drawcall }, renderTargets); core.prepareSwapchainImageForPresent(cmdStream); core.submitCommandStream(cmdStream); - core.endFrame(); } diff --git a/projects/first_scene/.gitignore b/projects/first_scene/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b0d802667a184267e6ee764264e976dfead8e9dd --- /dev/null +++ b/projects/first_scene/.gitignore @@ -0,0 +1 @@ +first_scene diff --git a/projects/first_scene/CMakeLists.txt b/projects/first_scene/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b90739750011a36b4c1d9e0bff7cba986074228 --- /dev/null +++ b/projects/first_scene/CMakeLists.txt @@ -0,0 +1,28 @@ +cmake_minimum_required(VERSION 3.16) +project(first_scene) + +# setting c++ standard for the project +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# this should fix the execution path to load local files from the project +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + +# adding source files to the project +add_executable(first_scene src/main.cpp) + +# this should fix the execution path to load local files from the project (for MSVC) +if(MSVC) + set_target_properties(first_scene PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + set_target_properties(first_scene PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) + + # in addition to setting the output directory, the working directory has to be set + # by default visual studio sets the working directory to the build directory, when using the debugger + set_target_properties(first_scene PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +endif() + +# including headers of dependencies and the VkCV framework +target_include_directories(first_scene SYSTEM BEFORE PRIVATE ${vkcv_include} ${vkcv_includes} ${vkcv_asset_loader_include} ${vkcv_camera_include}) + +# linking with libraries from all dependencies and the VkCV framework +target_link_libraries(first_scene vkcv ${vkcv_libraries} vkcv_asset_loader ${vkcv_asset_loader_libraries} vkcv_camera) diff --git a/projects/first_scene/resources/Cutlery/Cutlery_chrome_BaseColor.png b/projects/first_scene/resources/Cutlery/Cutlery_chrome_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..8258525f22097f2382ec5c26ad0df7eb50718642 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Cutlery_chrome_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ce87f6407ee40ffa60983587aeb52333d59b4b1c01a53e11f4bb227ba1099d9 +size 109 diff --git a/projects/first_scene/resources/Cutlery/Cutlery_chrome_Normal.png b/projects/first_scene/resources/Cutlery/Cutlery_chrome_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..620fe7621cf35409ae8c04099dc8bc4bbc04343b --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Cutlery_chrome_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:68a0064d457a6f7994814b07d943deda778754128935689874334300ede6161d +size 2332064 diff --git a/projects/first_scene/resources/Cutlery/Cutlery_details_BaseColor.png b/projects/first_scene/resources/Cutlery/Cutlery_details_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..5570e88c569036b9d00155ef6113013aa23f2503 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Cutlery_details_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42c2715635081eb29c4489ce631798b0e9c881460efc0aa63d0e81641a0dcfe9 +size 108 diff --git a/projects/first_scene/resources/Cutlery/Cutlery_details_Normal.png b/projects/first_scene/resources/Cutlery/Cutlery_details_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..d07681f5bfa25c279321c3074e21e4900c5eb0fa --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Cutlery_details_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15b0133e140899c47ccf35b0f99a7e337e3110ae089f45d27faf9983f3e0a1f7 +size 770758 diff --git a/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_BaseColor.png b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..1845e8a7d586a0d23300ad9d04a82f1d5048fcf5 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea7c82c0f9e25afa401470df1fb6903f508fa138d21ad30f57a9153b0395b198 +size 521315 diff --git a/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_Normal.png b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..1c800c0489693b66d6163bdc2156d453b68ca19b --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Caps_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:119efbbc020244ff9b7ff16ac9795a6d4b1808d1b90d81d20d2c874d0dc8a924 +size 1693468 diff --git a/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_BaseColor.png b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..36f46ebf25158c78bc26d83860e1c08b2c9e96cf --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99896468c7d47dd5391d585eecf149f420eca3bfec31923c21fa86c45fe02d0f +size 108 diff --git a/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_Normal.png b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..28c205d4e70867ec58448ca8ba2c2117c611a367 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Paris_LiquorBottle_01_Glass_Wine_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b31618aa5adce4ad476bec2c03718c5ae097250e784344f2d298b8a74c3bfd46 +size 90 diff --git a/projects/first_scene/resources/Cutlery/Plates_Ceramic_BaseColor.png b/projects/first_scene/resources/Cutlery/Plates_Ceramic_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..e0104189a1190c160152101e9e328e81ed89121b --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Plates_Ceramic_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6eff6ccd12d8b39d60ae5ee91edd73d4d7838fcb5d9bc6ff0e671bdf009134e9 +size 109 diff --git a/projects/first_scene/resources/Cutlery/Plates_Ceramic_Normal.png b/projects/first_scene/resources/Cutlery/Plates_Ceramic_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..fa13483d25595ee6b3a00e7fe6ce48aed7b6aaca --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Plates_Ceramic_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe92c40ff4032fdaf10eeafd943657a0c6e0bfb3f38770f5654aa943a660f421 +size 59419 diff --git a/projects/first_scene/resources/Cutlery/Plates_Details_BaseColor-Plates_Details_BaseColor.png b/projects/first_scene/resources/Cutlery/Plates_Details_BaseColor-Plates_Details_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..b91d0ac62fbeabbef1ed78f1343f919836cbca40 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Plates_Details_BaseColor-Plates_Details_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ca7d436a68a2a1237aee6e763b2954f01666b21f1dbd46929a322ea277483d2 +size 779227 diff --git a/projects/first_scene/resources/Cutlery/Plates_Details_Normal.png b/projects/first_scene/resources/Cutlery/Plates_Details_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..6efd967984ee2e68b89de9e471b93396c13ca69a --- /dev/null +++ b/projects/first_scene/resources/Cutlery/Plates_Details_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b01fc6482054c64d7407b283731e57fce0601a8db28b6781c14fae3c6b30b0fe +size 504362 diff --git a/projects/first_scene/resources/Cutlery/ToffeeJar_Label_BaseColor.png b/projects/first_scene/resources/Cutlery/ToffeeJar_Label_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..d0e0c4f4134cb99d3765d6f078f71efab8861bf1 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/ToffeeJar_Label_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:df138ee68c1d455652d1b9ae3dd03e93fcd2f6a0d8a1f12e3710f39143088674 +size 1593466 diff --git a/projects/first_scene/resources/Cutlery/ToffeeJar_Label_Normal.png b/projects/first_scene/resources/Cutlery/ToffeeJar_Label_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..9f310653b5211575da3cab2f6deb47ec6826a936 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/ToffeeJar_Label_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6af5da97cbb25d79aea2dde8dd71ecbd495334fe34e99497ba17821be93fd7fd +size 2696676 diff --git a/projects/first_scene/resources/Cutlery/TransparentGlass_BaseColor.png b/projects/first_scene/resources/Cutlery/TransparentGlass_BaseColor.png new file mode 100644 index 0000000000000000000000000000000000000000..4e4f0fcb312b8f8bd0df965bfe6b8ac62ec5df4d --- /dev/null +++ b/projects/first_scene/resources/Cutlery/TransparentGlass_BaseColor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2796affdfdcf6bc805176d9f85505680b5ee52eeec625e9eaeea4f0ff3854883 +size 108 diff --git a/projects/first_scene/resources/Cutlery/TransparentGlass_Normal.png b/projects/first_scene/resources/Cutlery/TransparentGlass_Normal.png new file mode 100644 index 0000000000000000000000000000000000000000..28c205d4e70867ec58448ca8ba2c2117c611a367 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/TransparentGlass_Normal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b31618aa5adce4ad476bec2c03718c5ae097250e784344f2d298b8a74c3bfd46 +size 90 diff --git a/projects/first_scene/resources/Cutlery/cutlerySzene.bin b/projects/first_scene/resources/Cutlery/cutlerySzene.bin new file mode 100644 index 0000000000000000000000000000000000000000..ab9a0aa47205e8f3064d2f16a950d4733fb4f472 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/cutlerySzene.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f545b986e0a1ac5bff5d49693a52042aa37878425818f72c69c243da20d1f99d +size 183324 diff --git a/projects/first_scene/resources/Cutlery/cutlerySzene.glb b/projects/first_scene/resources/Cutlery/cutlerySzene.glb new file mode 100644 index 0000000000000000000000000000000000000000..b0c5f345aaaa3f96d7158a0992ee124aae99a69a --- /dev/null +++ b/projects/first_scene/resources/Cutlery/cutlerySzene.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb1bad604192ca36222c0ca485ba87b846ecbd11ee8254327e04e3c993b00116 +size 11150396 diff --git a/projects/first_scene/resources/Cutlery/cutlerySzene.gltf b/projects/first_scene/resources/Cutlery/cutlerySzene.gltf new file mode 100644 index 0000000000000000000000000000000000000000..53e339cda4511f3f1a8670b36469e184aac530e2 --- /dev/null +++ b/projects/first_scene/resources/Cutlery/cutlerySzene.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c77cd60e2327daca1a01044e45f2c38655f7b781bd07985fc0135328a8a96b57 +size 34312 diff --git a/projects/first_scene/resources/Sponza/Sponza.bin b/projects/first_scene/resources/Sponza/Sponza.bin new file mode 100644 index 0000000000000000000000000000000000000000..cfedd26ca5a67b6d0a47d44d13a75e14a141717a --- /dev/null +++ b/projects/first_scene/resources/Sponza/Sponza.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b809f7a17687dc99e6f41ca1ea32c06eded8779bf34d16f1f565d750b0ffd68 +size 6347696 diff --git a/projects/first_scene/resources/Sponza/Sponza.gltf b/projects/first_scene/resources/Sponza/Sponza.gltf new file mode 100644 index 0000000000000000000000000000000000000000..172ea07e21c94465211c860cd805355704cef230 --- /dev/null +++ b/projects/first_scene/resources/Sponza/Sponza.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5cc0ecad5c4694088ff820e663619c370421afc1323ac487406e8e9b4735d787 +size 713962 diff --git a/projects/first_scene/resources/Sponza/background.png b/projects/first_scene/resources/Sponza/background.png new file mode 100644 index 0000000000000000000000000000000000000000..b64def129da38f4e23d89e21b4af1039008a4327 --- /dev/null +++ b/projects/first_scene/resources/Sponza/background.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5b5f900ff8ed83a31750ec8e428b5b91273794ddcbfc4e4b8a6a7e781f8c686 +size 1417666 diff --git a/projects/first_scene/resources/Sponza/chain_texture.png b/projects/first_scene/resources/Sponza/chain_texture.png new file mode 100644 index 0000000000000000000000000000000000000000..c1e1768cff78e0614ad707eca8602a4c4edab5e5 --- /dev/null +++ b/projects/first_scene/resources/Sponza/chain_texture.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8362cfd472880daeaea37439326a4651d1338680ae69bb2513fc6b17c8de7d4 +size 490895 diff --git a/projects/first_scene/resources/Sponza/lion.png b/projects/first_scene/resources/Sponza/lion.png new file mode 100644 index 0000000000000000000000000000000000000000..c49c7f0ed31e762e19284d0d3624fbc47664e56b --- /dev/null +++ b/projects/first_scene/resources/Sponza/lion.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f882f746c3a9cd51a9c6eedc1189b97668721d91a3fe49232036e789912c652 +size 2088728 diff --git a/projects/first_scene/resources/Sponza/spnza_bricks_a_diff.png b/projects/first_scene/resources/Sponza/spnza_bricks_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..cde4c7a6511e9a5f03c63ad996437fcdba3ce2df --- /dev/null +++ b/projects/first_scene/resources/Sponza/spnza_bricks_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b94219c2f5f943f3f4715c74e7d1038bf0ab3b3b3216a758eaee67f875df0851 +size 1928829 diff --git a/projects/first_scene/resources/Sponza/sponza_arch_diff.png b/projects/first_scene/resources/Sponza/sponza_arch_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..bcd9bda2918d226039f9e2d03902d377b706fab6 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_arch_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0df2c8a01b2843b1c792b494f7173cdbc4f834840fc2177af3e5d690fceda57 +size 1596151 diff --git a/projects/first_scene/resources/Sponza/sponza_ceiling_a_diff.png b/projects/first_scene/resources/Sponza/sponza_ceiling_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..59de631ffac4414cabf69b2dc794c46fc187d6cb --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_ceiling_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab6c187a81aa68f4eba30119e17fce2e4882a9ec320f70c90482dbe9da82b1c6 +size 1872074 diff --git a/projects/first_scene/resources/Sponza/sponza_column_a_diff.png b/projects/first_scene/resources/Sponza/sponza_column_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..01a82432d3f9939bbefe850bdb900f1ff9a3f6db --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_column_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c291507e2808bb83e160ab4b020689817df273baad3713a9ad19ac15fac6826 +size 1840992 diff --git a/projects/first_scene/resources/Sponza/sponza_column_b_diff.png b/projects/first_scene/resources/Sponza/sponza_column_b_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..10a660cce2a5a9b8997772c746058ce23e7d45d7 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_column_b_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2820b0267c4289c6cedbb42721792a57ef244ec2d0935941011c2a7d3fe88a9b +size 2170433 diff --git a/projects/first_scene/resources/Sponza/sponza_column_c_diff.png b/projects/first_scene/resources/Sponza/sponza_column_c_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..bc46fd979044a938d3adca7601689e71504e48bf --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_column_c_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0bc993ff59865468ef4530798930c7dfefb07482d71db45bc2a520986b27735 +size 2066950 diff --git a/projects/first_scene/resources/Sponza/sponza_curtain_blue_diff.png b/projects/first_scene/resources/Sponza/sponza_curtain_blue_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..384c8c2c051160d530eb3ac8b05c9c60752a2d2b --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_curtain_blue_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b85c6bb3cd5105f48d3812ec8e7a1068521ce69e917300d79e136e19d45422fb +size 9510905 diff --git a/projects/first_scene/resources/Sponza/sponza_curtain_diff.png b/projects/first_scene/resources/Sponza/sponza_curtain_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..af842e9f5fe18c1f609875e00899a6770fa4488b --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_curtain_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:563c56bdbbee395a6ef7f0c51c8ac9223c162e517b4cdba0d4654e8de27c98d8 +size 9189263 diff --git a/projects/first_scene/resources/Sponza/sponza_curtain_green_diff.png b/projects/first_scene/resources/Sponza/sponza_curtain_green_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..6c9b6391a199407637fa71033d79fb58b8b4f0d7 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_curtain_green_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:238fe1c7f481388d1c1d578c2da8d411b99e8f0030ab62060a306db333124476 +size 8785458 diff --git a/projects/first_scene/resources/Sponza/sponza_details_diff.png b/projects/first_scene/resources/Sponza/sponza_details_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..12656686362c3e0a297e060491f33bd7351551f9 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_details_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb1223b3bb82f8757e7df25a6891f1239cdd7ec59990340e952fb2d6b7ea570c +size 1522643 diff --git a/projects/first_scene/resources/Sponza/sponza_fabric_blue_diff.png b/projects/first_scene/resources/Sponza/sponza_fabric_blue_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..879d16ef84722a4fc13e83a771778de326e4bc54 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_fabric_blue_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:467d290bf5d4b2a017da140ba9e244ed8a8a9be5418a9ac9bcb4ad572ae2d7ab +size 2229440 diff --git a/projects/first_scene/resources/Sponza/sponza_fabric_diff.png b/projects/first_scene/resources/Sponza/sponza_fabric_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..3311287a219d2148620b87fe428fea071688d051 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_fabric_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1594f59cc2848db26add47361f4e665e3d8afa147760ed915d839fea42b20287 +size 2267382 diff --git a/projects/first_scene/resources/Sponza/sponza_fabric_green_diff.png b/projects/first_scene/resources/Sponza/sponza_fabric_green_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..de110f369004388dae4cd5067c63428db3a07834 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_fabric_green_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:902b87faab221173bf370cea7c74cb9060b4d870ac6316b190dafded1cb12993 +size 2258220 diff --git a/projects/first_scene/resources/Sponza/sponza_flagpole_diff.png b/projects/first_scene/resources/Sponza/sponza_flagpole_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..5f6e0812a0df80346318baa3cb50a6888afc58f8 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_flagpole_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfffb62e770959c725d0f3db6dc7dbdd46a380ec55ef884dab94d44ca017b438 +size 1425673 diff --git a/projects/first_scene/resources/Sponza/sponza_floor_a_diff.png b/projects/first_scene/resources/Sponza/sponza_floor_a_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..788ed764f79ba724f04a2d603076a5b85013e188 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_floor_a_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a16f9230fa91f9f31dfca6216ce205f1ef132d44f3b012fbf6efc0fba69770ab +size 1996838 diff --git a/projects/first_scene/resources/Sponza/sponza_roof_diff.png b/projects/first_scene/resources/Sponza/sponza_roof_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..c5b84261fdd1cc776a94b3ce398c7806b895f9a3 --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_roof_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fc412138c20da19f8173e53545e771f4652558dff624d4dc67143e40efe562b +size 2320533 diff --git a/projects/first_scene/resources/Sponza/sponza_thorn_diff.png b/projects/first_scene/resources/Sponza/sponza_thorn_diff.png new file mode 100644 index 0000000000000000000000000000000000000000..7a9142674a7d4a6f94a48c5152cf0300743b597a --- /dev/null +++ b/projects/first_scene/resources/Sponza/sponza_thorn_diff.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a73a17c883cd0d0d67cfda2dc4118400a916366c05b9a5ac465f0c8b30fd9c8e +size 635001 diff --git a/projects/first_scene/resources/Sponza/vase_dif.png b/projects/first_scene/resources/Sponza/vase_dif.png new file mode 100644 index 0000000000000000000000000000000000000000..61236a81cb324af8797b05099cd264cefe189e56 --- /dev/null +++ b/projects/first_scene/resources/Sponza/vase_dif.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53d06f52bf9e59df4cf00237707cca76c4f692bda61a62b06a30d321311d6dd9 +size 1842101 diff --git a/projects/first_scene/resources/Sponza/vase_hanging.png b/projects/first_scene/resources/Sponza/vase_hanging.png new file mode 100644 index 0000000000000000000000000000000000000000..36a3cee71d8213225090c74f8c0dce33b9d44378 --- /dev/null +++ b/projects/first_scene/resources/Sponza/vase_hanging.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9d10b4f27a3c9a78d5bac882fdd4b6a6987c262f48fa490670fe5e235951e31 +size 1432804 diff --git a/projects/first_scene/resources/Sponza/vase_plant.png b/projects/first_scene/resources/Sponza/vase_plant.png new file mode 100644 index 0000000000000000000000000000000000000000..7ad95e702e229f1ebd803e5203a266d15f2c07b9 --- /dev/null +++ b/projects/first_scene/resources/Sponza/vase_plant.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2087371ff02212fb7014b6daefa191cf5676d2227193fff261a5d02f554cb8e +size 998089 diff --git a/projects/first_scene/resources/Sponza/vase_round.png b/projects/first_scene/resources/Sponza/vase_round.png new file mode 100644 index 0000000000000000000000000000000000000000..c17953abc000c44b8991e23c136c2b67348f3d1b --- /dev/null +++ b/projects/first_scene/resources/Sponza/vase_round.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa23d48d492d5d4ada2ddb27d1ef22952b214e6eb3b301c65f9d88442723d20a +size 1871399 diff --git a/projects/first_scene/resources/Szene/Szene.bin b/projects/first_scene/resources/Szene/Szene.bin new file mode 100644 index 0000000000000000000000000000000000000000..c87d27637516b0bbf864251dd162773f5cc53e06 --- /dev/null +++ b/projects/first_scene/resources/Szene/Szene.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee4742718f720d589a2a03f5d879f8c50ba9057718d191a43b046eaa9071080d +size 70328 diff --git a/projects/first_scene/resources/Szene/Szene.gltf b/projects/first_scene/resources/Szene/Szene.gltf new file mode 100644 index 0000000000000000000000000000000000000000..e5a32b29af5d0a2ac5f497e60b4b92c1873e1df9 --- /dev/null +++ b/projects/first_scene/resources/Szene/Szene.gltf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75ba834118792ebbacf528a1690c7d04df4b4c8122b9f99a9aa9a9d075d2c86a +size 7421 diff --git a/projects/first_scene/resources/Szene/boards2_vcyc.jpg b/projects/first_scene/resources/Szene/boards2_vcyc.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2636039e272289c0fba3fa2d88a060b857501248 --- /dev/null +++ b/projects/first_scene/resources/Szene/boards2_vcyc.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca33a6e58ddd1b37a6e6853a9aa0e7b15ca678937119194752393dd2a0a0564 +size 1192476 diff --git a/projects/first_scene/resources/Szene/boards2_vcyc_jpg.jpg b/projects/first_scene/resources/Szene/boards2_vcyc_jpg.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2636039e272289c0fba3fa2d88a060b857501248 --- /dev/null +++ b/projects/first_scene/resources/Szene/boards2_vcyc_jpg.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cca33a6e58ddd1b37a6e6853a9aa0e7b15ca678937119194752393dd2a0a0564 +size 1192476 diff --git a/projects/first_scene/resources/shaders/compile.bat b/projects/first_scene/resources/shaders/compile.bat new file mode 100644 index 0000000000000000000000000000000000000000..b4521235c40fe5fb163bab874560c2f219b7517f --- /dev/null +++ b/projects/first_scene/resources/shaders/compile.bat @@ -0,0 +1,3 @@ +%VULKAN_SDK%\Bin32\glslc.exe shader.vert -o vert.spv +%VULKAN_SDK%\Bin32\glslc.exe shader.frag -o frag.spv +pause \ No newline at end of file diff --git a/projects/first_scene/resources/shaders/frag.spv b/projects/first_scene/resources/shaders/frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..087e4e22fb2fcec27d99b3ff2aa1a705fe755796 Binary files /dev/null and b/projects/first_scene/resources/shaders/frag.spv differ diff --git a/projects/first_scene/resources/shaders/shader.frag b/projects/first_scene/resources/shaders/shader.frag new file mode 100644 index 0000000000000000000000000000000000000000..b5494bea7d6497e2e3dcd8559606864a71adb74e --- /dev/null +++ b/projects/first_scene/resources/shaders/shader.frag @@ -0,0 +1,15 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(location = 0) in vec3 passNormal; +layout(location = 1) in vec2 passUV; + +layout(location = 0) out vec3 outColor; + +layout(set=0, binding=0) uniform texture2D meshTexture; +layout(set=0, binding=1) uniform sampler textureSampler; + +void main() { + outColor = texture(sampler2D(meshTexture, textureSampler), passUV).rgb; + //outColor = passNormal * 0.5 + 0.5; +} \ No newline at end of file diff --git a/projects/first_scene/resources/shaders/shader.vert b/projects/first_scene/resources/shaders/shader.vert new file mode 100644 index 0000000000000000000000000000000000000000..76855152253b48b7400f016d063ed4f0e507435e --- /dev/null +++ b/projects/first_scene/resources/shaders/shader.vert @@ -0,0 +1,19 @@ +#version 450 +#extension GL_ARB_separate_shader_objects : enable + +layout(location = 0) in vec3 inPosition; +layout(location = 1) in vec3 inNormal; +layout(location = 2) in vec2 inUV; + +layout(location = 0) out vec3 passNormal; +layout(location = 1) out vec2 passUV; + +layout( push_constant ) uniform constants{ + mat4 mvp; +}; + +void main() { + gl_Position = mvp * vec4(inPosition, 1.0); + passNormal = inNormal; + passUV = inUV; +} \ No newline at end of file diff --git a/projects/first_scene/resources/shaders/vert.spv b/projects/first_scene/resources/shaders/vert.spv new file mode 100644 index 0000000000000000000000000000000000000000..374c023e14b351eb43cbcda5951cbb8b3d6f96a1 Binary files /dev/null and b/projects/first_scene/resources/shaders/vert.spv differ diff --git a/projects/first_scene/src/main.cpp b/projects/first_scene/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00a862cfd77b522e9d83b51e703ea48ce45e5d5c --- /dev/null +++ b/projects/first_scene/src/main.cpp @@ -0,0 +1,266 @@ +#include <iostream> +#include <vkcv/Core.hpp> +#include <GLFW/glfw3.h> +#include <vkcv/camera/CameraManager.hpp> +#include <chrono> +#include <vkcv/asset/asset_loader.hpp> +#include <vkcv/Logger.hpp> + +glm::mat4 arrayTo4x4Matrix(std::array<float,16> array){ + glm::mat4 matrix; + for (int i = 0; i < 4; i++){ + for (int j = 0; j < 4; j++){ + matrix[i][j] = array[j * 4 + i]; + } + } + return matrix; +} + +int main(int argc, const char** argv) { + const char* applicationName = "First Scene"; + + uint32_t windowWidth = 800; + uint32_t windowHeight = 600; + + vkcv::Window window = vkcv::Window::create( + applicationName, + windowWidth, + windowHeight, + true + ); + + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex0 = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex1 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex0).setPosition(glm::vec3(0, 0, -3)); + cameraManager.getCamera(camIndex0).setNearFar(0.1f, 30.0f); + + cameraManager.getCamera(camIndex1).setNearFar(0.1f, 30.0f); + + window.initEvents(); + + vkcv::Core core = vkcv::Core::create( + window, + applicationName, + VK_MAKE_VERSION(0, 0, 1), + { vk::QueueFlagBits::eGraphics ,vk::QueueFlagBits::eCompute , vk::QueueFlagBits::eTransfer }, + {}, + { "VK_KHR_swapchain" } + ); + + vkcv::asset::Scene scene; + + const char* path = argc > 1 ? argv[1] : "resources/Sponza/Sponza.gltf"; + int result = vkcv::asset::loadScene(path, scene); + + if (result == 1) { + std::cout << "Mesh loading successful!" << std::endl; + } + else { + std::cout << "Mesh loading failed: " << result << std::endl; + return 1; + } + + assert(!scene.vertexGroups.empty()); + std::vector<std::vector<uint8_t>> vBuffers; + std::vector<std::vector<uint8_t>> iBuffers; + + std::vector<vkcv::VertexBufferBinding> vBufferBindings; + std::vector<std::vector<vkcv::VertexBufferBinding>> vertexBufferBindings; + std::vector<vkcv::asset::VertexAttribute> vAttributes; + + for (int i = 0; i < scene.vertexGroups.size(); i++) { + + vBuffers.push_back(scene.vertexGroups[i].vertexBuffer.data); + iBuffers.push_back(scene.vertexGroups[i].indexBuffer.data); + + auto& attributes = scene.vertexGroups[i].vertexBuffer.attributes; + + std::sort(attributes.begin(), attributes.end(), [](const vkcv::asset::VertexAttribute& x, const vkcv::asset::VertexAttribute& y) { + return static_cast<uint32_t>(x.type) < static_cast<uint32_t>(y.type); + }); + } + + std::vector<vkcv::Buffer<uint8_t>> vertexBuffers; + for (const vkcv::asset::VertexGroup& group : scene.vertexGroups) { + vertexBuffers.push_back(core.createBuffer<uint8_t>( + vkcv::BufferType::VERTEX, + group.vertexBuffer.data.size())); + vertexBuffers.back().fill(group.vertexBuffer.data); + } + + std::vector<vkcv::Buffer<uint8_t>> indexBuffers; + for (const auto& dataBuffer : iBuffers) { + indexBuffers.push_back(core.createBuffer<uint8_t>( + vkcv::BufferType::INDEX, + dataBuffer.size())); + indexBuffers.back().fill(dataBuffer); + } + + int vertexBufferIndex = 0; + for (const auto& vertexGroup : scene.vertexGroups) { + for (const auto& attribute : vertexGroup.vertexBuffer.attributes) { + vAttributes.push_back(attribute); + vBufferBindings.push_back(vkcv::VertexBufferBinding(attribute.offset, vertexBuffers[vertexBufferIndex].getVulkanHandle())); + } + vertexBufferBindings.push_back(vBufferBindings); + vBufferBindings.clear(); + vertexBufferIndex++; + } + + const vkcv::AttachmentDescription present_color_attachment( + vkcv::AttachmentOperation::STORE, + vkcv::AttachmentOperation::CLEAR, + core.getSwapchain().getFormat() + ); + + const vkcv::AttachmentDescription depth_attachment( + vkcv::AttachmentOperation::STORE, + vkcv::AttachmentOperation::CLEAR, + vk::Format::eD32Sfloat + ); + + vkcv::PassConfig scenePassDefinition({ present_color_attachment, depth_attachment }); + vkcv::PassHandle scenePass = core.createPass(scenePassDefinition); + + if (!scenePass) { + std::cout << "Error. Could not create renderpass. Exiting." << std::endl; + return EXIT_FAILURE; + } + + vkcv::ShaderProgram sceneShaderProgram{}; + sceneShaderProgram.addShader(vkcv::ShaderStage::VERTEX, std::filesystem::path("resources/shaders/vert.spv")); + sceneShaderProgram.addShader(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("resources/shaders/frag.spv")); + + const std::vector<vkcv::VertexAttachment> vertexAttachments = sceneShaderProgram.getVertexAttachments(); + std::vector<vkcv::VertexBinding> bindings; + for (size_t i = 0; i < vertexAttachments.size(); i++) { + bindings.push_back(vkcv::VertexBinding(i, { vertexAttachments[i] })); + } + + const vkcv::VertexLayout sceneLayout(bindings); + + uint32_t setID = 0; + + std::vector<vkcv::DescriptorBinding> descriptorBindings = { sceneShaderProgram.getReflectedDescriptors()[setID] }; + + vkcv::SamplerHandle sampler = core.createSampler( + vkcv::SamplerFilterType::LINEAR, + vkcv::SamplerFilterType::LINEAR, + vkcv::SamplerMipmapMode::LINEAR, + vkcv::SamplerAddressMode::REPEAT + ); + + std::vector<vkcv::Image> sceneImages; + std::vector<vkcv::DescriptorSetHandle> descriptorSets; + for (const auto& vertexGroup : scene.vertexGroups) { + descriptorSets.push_back(core.createDescriptorSet(descriptorBindings)); + + const auto& material = scene.materials[vertexGroup.materialIndex]; + + int baseColorIndex = material.baseColor; + if (baseColorIndex < 0) { + vkcv_log(vkcv::LogLevel::WARNING, "Material lacks base color"); + baseColorIndex = 0; + } + + vkcv::asset::Texture& sceneTexture = scene.textures[baseColorIndex]; + + sceneImages.push_back(core.createImage(vk::Format::eR8G8B8A8Srgb, sceneTexture.w, sceneTexture.h)); + sceneImages.back().fill(sceneTexture.data.data()); + + vkcv::DescriptorWrites setWrites; + setWrites.sampledImageWrites = { vkcv::SampledImageDescriptorWrite(0, sceneImages.back().getHandle()) }; + setWrites.samplerWrites = { vkcv::SamplerDescriptorWrite(1, sampler) }; + core.writeDescriptorSet(descriptorSets.back(), setWrites); + } + + const vkcv::PipelineConfig scenePipelineDefsinition{ + sceneShaderProgram, + UINT32_MAX, + UINT32_MAX, + scenePass, + {sceneLayout}, + { core.getDescriptorSet(descriptorSets[0]).layout }, + true }; + vkcv::PipelineHandle scenePipeline = core.createGraphicsPipeline(scenePipelineDefsinition); + + if (!scenePipeline) { + std::cout << "Error. Could not create graphics pipeline. Exiting." << std::endl; + return EXIT_FAILURE; + } + + vkcv::ImageHandle depthBuffer = core.createImage(vk::Format::eD32Sfloat, windowWidth, windowHeight).getHandle(); + + const vkcv::ImageHandle swapchainInput = vkcv::ImageHandle::createSwapchainImageHandle(); + + std::vector<vkcv::DrawcallInfo> drawcalls; + for(int i = 0; i < scene.vertexGroups.size(); i++){ + vkcv::Mesh renderMesh(vertexBufferBindings[i], indexBuffers[i].getVulkanHandle(), scene.vertexGroups[i].numIndices); + + vkcv::DescriptorSetUsage descriptorUsage(0, core.getDescriptorSet(descriptorSets[i]).vulkanHandle); + + drawcalls.push_back(vkcv::DrawcallInfo(renderMesh, {descriptorUsage})); + } + + std::vector<glm::mat4> modelMatrices; + modelMatrices.resize(scene.vertexGroups.size(), glm::mat4(1.f)); + for (const auto &mesh : scene.meshes) { + const glm::mat4 m = arrayTo4x4Matrix(mesh.modelMatrix); + for (const auto &vertexGroupIndex : mesh.vertexGroups) { + modelMatrices[vertexGroupIndex] = m; + } + } + std::vector<glm::mat4> mvp; + + auto start = std::chrono::system_clock::now(); + while (window.isWindowOpen()) { + vkcv::Window::pollEvents(); + + if(window.getHeight() == 0 || window.getWidth() == 0) + continue; + + uint32_t swapchainWidth, swapchainHeight; + if (!core.beginFrame(swapchainWidth, swapchainHeight)) { + continue; + } + + if ((swapchainWidth != windowWidth) || ((swapchainHeight != windowHeight))) { + depthBuffer = core.createImage(vk::Format::eD32Sfloat, swapchainWidth, swapchainHeight).getHandle(); + + windowWidth = swapchainWidth; + windowHeight = swapchainHeight; + } + + auto end = std::chrono::system_clock::now(); + auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); + + start = end; + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); + glm::mat4 vp = cameraManager.getActiveCamera().getMVP(); + + mvp.clear(); + for (const auto& m : modelMatrices) { + mvp.push_back(vp * m); + } + + vkcv::PushConstantData pushConstantData((void*)mvp.data(), sizeof(glm::mat4)); + + const std::vector<vkcv::ImageHandle> renderTargets = { swapchainInput, depthBuffer }; + auto cmdStream = core.createCommandStream(vkcv::QueueType::Graphics); + + core.recordDrawcallsToCmdStream( + cmdStream, + scenePass, + scenePipeline, + pushConstantData, + drawcalls, + renderTargets); + core.prepareSwapchainImageForPresent(cmdStream); + core.submitCommandStream(cmdStream); + core.endFrame(); + } + + return 0; +} diff --git a/projects/first_triangle/CMakeLists.txt b/projects/first_triangle/CMakeLists.txt index e7c8373e085df6497060b8d1d8164cf740dfb01f..ba8c83c06fc804082e6a0a14c3c0414899ef3057 100644 --- a/projects/first_triangle/CMakeLists.txt +++ b/projects/first_triangle/CMakeLists.txt @@ -22,7 +22,7 @@ if(MSVC) endif() # including headers of dependencies and the VkCV framework -target_include_directories(first_triangle SYSTEM BEFORE PRIVATE ${vkcv_include} ${vkcv_includes} ${vkcv_testing_include} ${vkcv_camera_include}) +target_include_directories(first_triangle SYSTEM BEFORE PRIVATE ${vkcv_include} ${vkcv_includes} ${vkcv_testing_include} ${vkcv_camera_include} ${vkcv_shader_compiler_include} ${vkcv_gui_include}) # linking with libraries from all dependencies and the VkCV framework -target_link_libraries(first_triangle vkcv vkcv_testing vkcv_camera) +target_link_libraries(first_triangle vkcv vkcv_testing vkcv_camera vkcv_shader_compiler vkcv_gui) diff --git a/projects/first_triangle/shaders/comp.spv b/projects/first_triangle/shaders/comp.spv new file mode 100644 index 0000000000000000000000000000000000000000..b414e36b2bea66dab00746298e536d029091e0fd Binary files /dev/null and b/projects/first_triangle/shaders/comp.spv differ diff --git a/projects/first_triangle/shaders/compile.bat b/projects/first_triangle/shaders/compile.bat index b4521235c40fe5fb163bab874560c2f219b7517f..17743a7c49cdfc6e091c43a42a0adb755a731682 100644 --- a/projects/first_triangle/shaders/compile.bat +++ b/projects/first_triangle/shaders/compile.bat @@ -1,3 +1,4 @@ %VULKAN_SDK%\Bin32\glslc.exe shader.vert -o vert.spv %VULKAN_SDK%\Bin32\glslc.exe shader.frag -o frag.spv +%VULKAN_SDK%\Bin32\glslc.exe shader.comp -o comp.spv pause \ No newline at end of file diff --git a/projects/first_triangle/shaders/shader.comp b/projects/first_triangle/shaders/shader.comp new file mode 100644 index 0000000000000000000000000000000000000000..fad6cd0815f2f09bf92dcc3171e2e3723f5466df --- /dev/null +++ b/projects/first_triangle/shaders/shader.comp @@ -0,0 +1,25 @@ +#version 440 + +layout(std430, binding = 0) buffer testBuffer +{ + float test1[10]; + float test2[10]; + float test3[10]; +}; + +layout( push_constant ) uniform constants{ + float pushConstant; +}; + +layout(local_size_x = 5) in; + +void main(){ + + if(gl_GlobalInvocationID.x >= 10){ + return; + } + + test1[gl_GlobalInvocationID.x] = gl_GlobalInvocationID.x; + test2[gl_GlobalInvocationID.x] = 69; // nice! + test3[gl_GlobalInvocationID.x] = pushConstant; +} \ No newline at end of file diff --git a/projects/first_triangle/shaders/shader.frag b/projects/first_triangle/shaders/shader.frag index d26446a73020111695aa2c86166205796dfa5e44..080678beb011afe4b03aed3bf7ae7148b77932dc 100644 --- a/projects/first_triangle/shaders/shader.frag +++ b/projects/first_triangle/shaders/shader.frag @@ -4,6 +4,6 @@ layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; -void main() { +void main() { outColor = vec4(fragColor, 1.0); } \ No newline at end of file diff --git a/projects/first_triangle/src/main.cpp b/projects/first_triangle/src/main.cpp index 2ede653ff98e19159e0155b282cab1b309a13816..5a962b8983f6735530b38de5be679096fa997bd5 100644 --- a/projects/first_triangle/src/main.cpp +++ b/projects/first_triangle/src/main.cpp @@ -4,6 +4,9 @@ #include <vkcv/camera/CameraManager.hpp> #include <chrono> +#include <vkcv/shader/GLSLCompiler.hpp> +#include <vkcv/gui/GUI.hpp> + int main(int argc, const char** argv) { const char* applicationName = "First Triangle"; @@ -16,10 +19,8 @@ int main(int argc, const char** argv) { false ); - vkcv::CameraManager cameraManager(window, windowWidth, windowHeight); - window.initEvents(); - + vkcv::Core core = vkcv::Core::create( window, applicationName, @@ -28,6 +29,8 @@ int main(int argc, const char** argv) { {}, { "VK_KHR_swapchain" } ); + + vkcv::gui::GUI gui (core, window); const auto& context = core.getContext(); const vk::Instance& instance = context.getInstance(); @@ -81,7 +84,7 @@ int main(int argc, const char** argv) { const vkcv::AttachmentDescription present_color_attachment( vkcv::AttachmentOperation::STORE, vkcv::AttachmentOperation::CLEAR, - core.getSwapchainImageFormat()); + core.getSwapchain().getFormat()); vkcv::PassConfig trianglePassDefinition({ present_color_attachment }); vkcv::PassHandle trianglePass = core.createPass(trianglePassDefinition); @@ -93,19 +96,27 @@ int main(int argc, const char** argv) { } vkcv::ShaderProgram triangleShaderProgram{}; - triangleShaderProgram.addShader(vkcv::ShaderStage::VERTEX, std::filesystem::path("shaders/vert.spv")); - triangleShaderProgram.addShader(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("shaders/frag.spv")); - triangleShaderProgram.reflectShader(vkcv::ShaderStage::VERTEX); - triangleShaderProgram.reflectShader(vkcv::ShaderStage::FRAGMENT); - - const vkcv::PipelineConfig trianglePipelineDefinition( + vkcv::shader::GLSLCompiler compiler; + + compiler.compile(vkcv::ShaderStage::VERTEX, std::filesystem::path("shaders/shader.vert"), + [&triangleShaderProgram](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + triangleShaderProgram.addShader(shaderStage, path); + }); + + compiler.compile(vkcv::ShaderStage::FRAGMENT, std::filesystem::path("shaders/shader.frag"), + [&triangleShaderProgram](vkcv::ShaderStage shaderStage, const std::filesystem::path& path) { + triangleShaderProgram.addShader(shaderStage, path); + }); + + const vkcv::PipelineConfig trianglePipelineDefinition { triangleShaderProgram, (uint32_t)windowWidth, (uint32_t)windowHeight, trianglePass, {}, {}, - false); + false + }; vkcv::PipelineHandle trianglePipeline = core.createGraphicsPipeline(trianglePipelineDefinition); @@ -115,6 +126,29 @@ int main(int argc, const char** argv) { return EXIT_FAILURE; } + // Compute Pipeline + vkcv::ShaderProgram computeShaderProgram{}; + computeShaderProgram.addShader(vkcv::ShaderStage::COMPUTE, std::filesystem::path("shaders/comp.spv")); + + // take care, assuming shader has exactly one descriptor set + vkcv::DescriptorSetHandle computeDescriptorSet = core.createDescriptorSet(computeShaderProgram.getReflectedDescriptors()[0]); + + vkcv::PipelineHandle computePipeline = core.createComputePipeline( + computeShaderProgram, + { core.getDescriptorSet(computeDescriptorSet).layout }); + + struct ComputeTestBuffer { + float test1[10]; + float test2[10]; + float test3[10]; + }; + + vkcv::Buffer computeTestBuffer = core.createBuffer<ComputeTestBuffer>(vkcv::BufferType::STORAGE, 1); + + vkcv::DescriptorWrites computeDescriptorWrites; + computeDescriptorWrites.storageBufferWrites = { vkcv::StorageBufferDescriptorWrite(0, computeTestBuffer.getHandle()) }; + core.writeDescriptorSet(computeDescriptorSet, computeDescriptorWrites); + /* * BufferHandle triangleVertices = core.createBuffer(vertices); * BufferHandle triangleIndices = core.createBuffer(indices); @@ -139,6 +173,12 @@ int main(int argc, const char** argv) { const vkcv::ImageHandle swapchainInput = vkcv::ImageHandle::createSwapchainImageHandle(); + vkcv::camera::CameraManager cameraManager(window); + uint32_t camIndex = cameraManager.addCamera(vkcv::camera::ControllerType::PILOT); + uint32_t camIndex2 = cameraManager.addCamera(vkcv::camera::ControllerType::TRACKBALL); + + cameraManager.getCamera(camIndex).setPosition(glm::vec3(0, 0, -2)); + while (window.isWindowOpen()) { window.pollEvents(); @@ -149,10 +189,11 @@ int main(int argc, const char** argv) { } auto end = std::chrono::system_clock::now(); - auto deltatime = end - start; + auto deltatime = std::chrono::duration_cast<std::chrono::microseconds>(end - start); start = end; - cameraManager.getCamera().updateView(std::chrono::duration<double>(deltatime).count()); - const glm::mat4 mvp = cameraManager.getCamera().getProjection() * cameraManager.getCamera().getView(); + + cameraManager.update(0.000001 * static_cast<double>(deltatime.count())); + glm::mat4 mvp = cameraManager.getActiveCamera().getMVP(); vkcv::PushConstantData pushConstantData((void*)&mvp, sizeof(glm::mat4)); auto cmdStream = core.createCommandStream(vkcv::QueueType::Graphics); @@ -164,8 +205,27 @@ int main(int argc, const char** argv) { pushConstantData, { drawcall }, { swapchainInput }); + + const uint32_t dispatchSize[3] = { 2, 1, 1 }; + const float theMeaningOfLife = 42; + + core.recordComputeDispatchToCmdStream( + cmdStream, + computePipeline, + dispatchSize, + { vkcv::DescriptorSetUsage(0, core.getDescriptorSet(computeDescriptorSet).vulkanHandle) }, + vkcv::PushConstantData((void*)&theMeaningOfLife, sizeof(theMeaningOfLife))); + core.prepareSwapchainImageForPresent(cmdStream); core.submitCommandStream(cmdStream); + + gui.beginGUI(); + + ImGui::Begin("Hello world"); + ImGui::Text("This is a test!"); + ImGui::End(); + + gui.endGUI(); core.endFrame(); } diff --git a/src/vkcv/CommandResources.cpp b/src/vkcv/CommandResources.cpp index 71c990c3c222f2318c2f5744ff6295f667d9e6f8..a31e6967d85bd099fe5cbbc865b0e062212ca16e 100644 --- a/src/vkcv/CommandResources.cpp +++ b/src/vkcv/CommandResources.cpp @@ -1,6 +1,7 @@ #include "vkcv/CommandResources.hpp" #include <iostream> +#include "vkcv/Logger.hpp" namespace vkcv { @@ -62,7 +63,7 @@ namespace vkcv { return queueManager.getPresentQueue(); } else { - std::cerr << "getQueueForSubmit error: unknown queue type" << std::endl; + vkcv_log(LogLevel::ERROR, "Unknown queue type"); return queueManager.getGraphicsQueues().front(); // graphics is the most general queue } } diff --git a/src/vkcv/CommandStreamManager.cpp b/src/vkcv/CommandStreamManager.cpp index 9d0a236a4eaa5a166be77d143370a018b9ea7e73..5a5b359b912d9cef36e0b03379d7f0f6f0951381 100644 --- a/src/vkcv/CommandStreamManager.cpp +++ b/src/vkcv/CommandStreamManager.cpp @@ -1,6 +1,8 @@ #include "vkcv/CommandStreamManager.hpp" #include "vkcv/Core.hpp" +#include "vkcv/Logger.hpp" + namespace vkcv { CommandStreamManager::CommandStreamManager() noexcept : m_core(nullptr){} @@ -14,7 +16,7 @@ namespace vkcv { void CommandStreamManager::init(Core* core) { if (!core) { - std::cerr << "Error: CommandStreamManager::init requires valid core pointer" << std::endl; + vkcv_log(LogLevel::ERROR, "Requires valid core pointer"); } m_core = core; } @@ -57,7 +59,7 @@ namespace vkcv { const size_t id = handle.getId(); if (id >= m_commandStreams.size()) { - std::cerr << "Error: CommandStreamManager::recordCommandsToStream requires valid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Requires valid handle"); return; } @@ -71,7 +73,7 @@ namespace vkcv { const size_t id = handle.getId(); if (id >= m_commandStreams.size()) { - std::cerr << "Error: CommandStreamManager::addFinishCallbackToStream requires valid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Requires valid handle"); return; } @@ -86,7 +88,7 @@ namespace vkcv { const size_t id = handle.getId(); if (id >= m_commandStreams.size()) { - std::cerr << "Error: CommandStreamManager::submitCommandStreamSynchronous requires valid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Requires valid handle"); return; } CommandStream& stream = m_commandStreams[id]; @@ -111,7 +113,7 @@ namespace vkcv { vk::CommandBuffer CommandStreamManager::getStreamCommandBuffer(const CommandStreamHandle handle) { const size_t id = handle.getId(); if (id >= m_commandStreams.size()) { - std::cerr << "Error: CommandStreamManager::submitCommandStreamSynchronous requires valid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Requires valid handle"); return nullptr; } return m_commandStreams[id].cmdBuffer; diff --git a/src/vkcv/Core.cpp b/src/vkcv/Core.cpp index 9ed83d2a224119bd20fcfc81c5720b425de06bb6..49707d4cffc18719d8fbb18a9e632e12ba679c2e 100644 --- a/src/vkcv/Core.cpp +++ b/src/vkcv/Core.cpp @@ -16,6 +16,8 @@ #include "ImageLayoutTransitions.hpp" #include "vkcv/CommandStreamManager.hpp" +#include "vkcv/Logger.hpp" + namespace vkcv { @@ -33,7 +35,7 @@ namespace vkcv deviceExtensions ); - SwapChain swapChain = SwapChain::create(window, context); + Swapchain swapChain = Swapchain::create(window, context); std::vector<vk::ImageView> imageViews; imageViews = createImageViews( context, swapChain); @@ -52,8 +54,12 @@ namespace vkcv { return m_Context; } + + const Swapchain& Core::getSwapchain() const { + return m_swapchain; + } - Core::Core(Context &&context, Window &window, const SwapChain& swapChain, std::vector<vk::ImageView> imageViews, + Core::Core(Context &&context, Window &window, const Swapchain& swapChain, std::vector<vk::ImageView> imageViews, const CommandResources& commandResources, const SyncResources& syncResources) noexcept : m_Context(std::move(context)), m_window(window), @@ -74,8 +80,8 @@ namespace vkcv m_CommandStreamManager->init(this); m_ImageManager->m_core = this; - - e_resizeHandle = window.e_resize.add( [&](int width, int height) { + + e_resizeHandle = m_window.e_resize.add( [&](int width, int height) { m_swapchain.signalSwapchainRecreation(); }); @@ -84,6 +90,8 @@ namespace vkcv } Core::~Core() noexcept { + m_window.e_resize.remove(e_resizeHandle); + m_Context.getDevice().waitIdle(); for (auto image : m_swapchainImageViews) { m_Context.m_Device.destroyImageView(image); @@ -101,6 +109,13 @@ namespace vkcv return m_PipelineManager->createPipeline(config, *m_PassManager); } + PipelineHandle Core::createComputePipeline( + const ShaderProgram &shaderProgram, + const std::vector<vk::DescriptorSetLayout>& descriptorSetLayouts) + { + return m_PipelineManager->createComputePipeline(shaderProgram, descriptorSetLayouts); + } + PassHandle Core::createPass(const PassConfig &config) { @@ -125,7 +140,7 @@ namespace vkcv } if (result != vk::Result::eSuccess) { - std::cerr << vk::to_string(result) << std::endl; + vkcv_log(LogLevel::ERROR, "%s", vk::to_string(result).c_str()); return Result::ERROR; } @@ -149,7 +164,7 @@ namespace vkcv } if (acquireSwapchainImage() != Result::SUCCESS) { - std::cerr << "Acquire failed!" << std::endl; + vkcv_log(LogLevel::ERROR, "Acquire failed"); m_currentSwapchainImageIndex = std::numeric_limits<uint32_t>::max(); } @@ -223,7 +238,6 @@ namespace vkcv attachmentsViews.push_back(targetHandle); } - vk::Framebuffer framebuffer = nullptr; const vk::FramebufferCreateInfo createInfo( {}, renderpass, @@ -231,16 +245,21 @@ namespace vkcv attachmentsViews.data(), width, height, - 1); - if(m_Context.m_Device.createFramebuffer(&createInfo, nullptr, &framebuffer) != vk::Result::eSuccess) - { - std::cout << "FAILED TO CREATE TEMPORARY FRAMEBUFFER!" << std::endl; + 1 + ); + + vk::Framebuffer framebuffer = m_Context.m_Device.createFramebuffer(createInfo); + + if (!framebuffer) { + vkcv_log(LogLevel::ERROR, "Failed to create temporary framebuffer"); return; } - vk::Viewport dynamicViewport(0.0f, 0.0f, - static_cast<float>(width), static_cast<float>(height), - 0.0f, 1.0f); + vk::Viewport dynamicViewport( + 0.0f, 0.0f, + static_cast<float>(width), static_cast<float>(height), + 0.0f, 1.0f + ); vk::Rect2D dynamicScissor({0, 0}, {width, height}); @@ -298,6 +317,40 @@ namespace vkcv recordCommandsToStream(cmdStreamHandle, submitFunction, finishFunction); } + void Core::recordComputeDispatchToCmdStream( + CommandStreamHandle cmdStreamHandle, + PipelineHandle computePipeline, + const uint32_t dispatchCount[3], + const std::vector<DescriptorSetUsage>& descriptorSetUsages, + const PushConstantData& pushConstantData) { + + auto submitFunction = [&](const vk::CommandBuffer& cmdBuffer) { + + const auto pipelineLayout = m_PipelineManager->getVkPipelineLayout(computePipeline); + + cmdBuffer.bindPipeline(vk::PipelineBindPoint::eCompute, m_PipelineManager->getVkPipeline(computePipeline)); + for (const auto& usage : descriptorSetUsages) { + cmdBuffer.bindDescriptorSets( + vk::PipelineBindPoint::eCompute, + pipelineLayout, + usage.setLocation, + { usage.vulkanHandle }, + {}); + } + if (pushConstantData.sizePerDrawcall > 0) { + cmdBuffer.pushConstants( + pipelineLayout, + vk::ShaderStageFlagBits::eCompute, + 0, + pushConstantData.sizePerDrawcall, + pushConstantData.data); + } + cmdBuffer.dispatch(dispatchCount[0], dispatchCount[1], dispatchCount[2]); + }; + + recordCommandsToStream(cmdStreamHandle, submitFunction, nullptr); + } + void Core::endFrame() { if (m_currentSwapchainImageIndex == std::numeric_limits<uint32_t>::max()) { return; @@ -306,15 +359,17 @@ namespace vkcv const auto swapchainImages = m_Context.getDevice().getSwapchainImagesKHR(m_swapchain.getSwapchain()); const auto& queueManager = m_Context.getQueueManager(); - std::array<vk::Semaphore, 2> waitSemaphores{ - m_SyncResources.renderFinished, - m_SyncResources.swapchainImageAcquired }; + std::array<vk::Semaphore, 2> waitSemaphores{ + m_SyncResources.renderFinished, + m_SyncResources.swapchainImageAcquired + }; const vk::SwapchainKHR& swapchain = m_swapchain.getSwapchain(); const vk::PresentInfoKHR presentInfo( waitSemaphores, swapchain, - m_currentSwapchainImageIndex); + m_currentSwapchainImageIndex + ); vk::Result result; @@ -325,13 +380,9 @@ namespace vkcv } if (result != vk::Result::eSuccess) { - std::cout << "Error: swapchain present failed... " << vk::to_string(result) << std::endl; + vkcv_log(LogLevel::ERROR, "Swapchain present failed (%s)", vk::to_string(result).c_str()); } } - - vk::Format Core::getSwapchainImageFormat() { - return m_swapchain.getSwapchainFormat(); - } void Core::recordAndSubmitCommands( const SubmitInfo &submitInfo, @@ -347,11 +398,19 @@ namespace vkcv beginCommandBuffer(cmdBuffer, vk::CommandBufferUsageFlagBits::eOneTimeSubmit); record(cmdBuffer); cmdBuffer.end(); - - const vk::Fence waitFence = createFence(device); + + vk::Fence waitFence; + + if (!submitInfo.fence) { + waitFence = createFence(device); + } + submitCommandBufferToQueue(queue.handle, cmdBuffer, waitFence, submitInfo.waitSemaphores, submitInfo.signalSemaphores); waitForFence(device, waitFence); - device.destroyFence(waitFence); + + if (!submitInfo.fence) { + device.destroyFence(waitFence); + } device.freeCommandBuffers(cmdPool, cmdBuffer); @@ -402,10 +461,9 @@ namespace vkcv return m_DescriptorManager->createDescriptorSet(bindings); } - void Core::writeResourceDescription(DescriptorSetHandle handle, size_t setIndex, const DescriptorWrites &writes) { - m_DescriptorManager->writeResourceDescription( - handle, - setIndex, + void Core::writeDescriptorSet(DescriptorSetHandle handle, const DescriptorWrites &writes) { + m_DescriptorManager->writeDescriptorSet( + handle, writes, *m_ImageManager, *m_BufferManager, @@ -416,7 +474,7 @@ namespace vkcv return m_DescriptorManager->getDescriptorSet(handle); } - std::vector<vk::ImageView> Core::createImageViews( Context &context, SwapChain& swapChain){ + std::vector<vk::ImageView> Core::createImageViews( Context &context, Swapchain& swapChain){ std::vector<vk::ImageView> imageViews; std::vector<vk::Image> swapChainImages = context.getDevice().getSwapchainImagesKHR(swapChain.getSwapchain()); imageViews.reserve( swapChainImages.size() ); @@ -435,7 +493,7 @@ namespace vkcv vk::ImageViewCreateFlags(), image, vk::ImageViewType::e2D, - swapChain.getSwapchainFormat(), + swapChain.getFormat(), componentMapping, subResourceRange); @@ -465,4 +523,9 @@ namespace vkcv m_ImageManager->recordImageLayoutTransition(image, vk::ImageLayout::eShaderReadOnlyOptimal, cmdBuffer); }, nullptr); } + + const vk::ImageView& Core::getSwapchainImageView() const { + return m_swapchainImageViews[m_currentSwapchainImageIndex]; + } + } diff --git a/src/vkcv/DescriptorConfig.cpp b/src/vkcv/DescriptorConfig.cpp index be6cfc9b40baad6636e6bc6a2b6e803aacd7ddc0..54e879ac7e6ec7825a4c003899e3c264454c547f 100644 --- a/src/vkcv/DescriptorConfig.cpp +++ b/src/vkcv/DescriptorConfig.cpp @@ -2,10 +2,12 @@ namespace vkcv { DescriptorBinding::DescriptorBinding( + uint32_t bindingID, DescriptorType descriptorType, uint32_t descriptorCount, ShaderStage shaderStage) noexcept : + bindingID(bindingID), descriptorType(descriptorType), descriptorCount(descriptorCount), shaderStage(shaderStage) {} diff --git a/src/vkcv/DescriptorManager.cpp b/src/vkcv/DescriptorManager.cpp index a2efecbe7055122d28a864b7c722a5998be460e4..f591daf90b47b57a758b2b24c7fa87b5c33e3c46 100644 --- a/src/vkcv/DescriptorManager.cpp +++ b/src/vkcv/DescriptorManager.cpp @@ -1,5 +1,7 @@ #include "DescriptorManager.hpp" +#include "vkcv/Logger.hpp" + namespace vkcv { DescriptorManager::DescriptorManager(vk::Device device) noexcept: @@ -40,7 +42,7 @@ namespace vkcv //create each set's binding for (uint32_t i = 0; i < bindings.size(); i++) { vk::DescriptorSetLayoutBinding descriptorSetLayoutBinding( - i, + bindings[i].bindingID, convertDescriptorTypeFlag(bindings[i].descriptorType), bindings[i].descriptorCount, convertShaderStageFlag(bindings[i].shaderStage)); @@ -53,7 +55,7 @@ namespace vkcv vk::DescriptorSetLayoutCreateInfo layoutInfo({}, setBindings); if(m_Device.createDescriptorSetLayout(&layoutInfo, nullptr, &set.layout) != vk::Result::eSuccess) { - std::cout << "FAILED TO CREATE DESCRIPTOR SET LAYOUT" << std::endl; + vkcv_log(LogLevel::ERROR, "Failed to create descriptor set layout"); return DescriptorSetHandle(); }; @@ -69,10 +71,10 @@ namespace vkcv result = m_Device.allocateDescriptorSets(&allocInfo, &set.vulkanHandle); } if (result != vk::Result::eSuccess) { - std::cout << "FAILED TO ALLOCATE DESCRIPTOR SET" << std::endl; - std::cout << vk::to_string(result) << std::endl; + vkcv_log(LogLevel::ERROR, "Failed to create descriptor set (%s)", + vk::to_string(result).c_str()); + m_Device.destroy(set.layout); - return DescriptorSetHandle(); } }; @@ -90,9 +92,8 @@ namespace vkcv vk::DescriptorType type; }; - void DescriptorManager::writeResourceDescription( + void DescriptorManager::writeDescriptorSet( const DescriptorSetHandle &handle, - size_t setIndex, const DescriptorWrites &writes, const ImageManager &imageManager, const BufferManager &bufferManager, @@ -239,7 +240,7 @@ namespace vkcv case DescriptorType::IMAGE_STORAGE: return vk::DescriptorType::eStorageImage; default: - std::cerr << "Error: DescriptorManager::convertDescriptorTypeFlag, unknown DescriptorType" << std::endl; + vkcv_log(LogLevel::ERROR, "Unknown DescriptorType"); return vk::DescriptorType::eUniformBuffer; } } @@ -266,7 +267,7 @@ namespace vkcv void DescriptorManager::destroyDescriptorSetById(uint64_t id) { if (id >= m_DescriptorSets.size()) { - std::cerr << "Error: DescriptorManager::destroyResourceDescriptionById invalid id" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid id"); return; } @@ -282,7 +283,7 @@ namespace vkcv vk::DescriptorPool pool; if (m_Device.createDescriptorPool(&m_PoolInfo, nullptr, &pool) != vk::Result::eSuccess) { - std::cout << "FAILED TO ALLOCATE DESCRIPTOR POOL." << std::endl; + vkcv_log(LogLevel::WARNING, "Failed to allocate descriptor pool"); pool = nullptr; }; m_Pools.push_back(pool); diff --git a/src/vkcv/DescriptorManager.hpp b/src/vkcv/DescriptorManager.hpp index d8607b9312b25e71c7eb4af009efd92b834b40ec..d18be64f3b069af68cecce68f6fa623c81f8dfa4 100644 --- a/src/vkcv/DescriptorManager.hpp +++ b/src/vkcv/DescriptorManager.hpp @@ -23,9 +23,8 @@ namespace vkcv DescriptorSetHandle createDescriptorSet(const std::vector<DescriptorBinding> &descriptorBindings); - void writeResourceDescription( + void writeDescriptorSet( const DescriptorSetHandle &handle, - size_t setIndex, const DescriptorWrites &writes, const ImageManager &imageManager, const BufferManager &bufferManager, diff --git a/src/vkcv/ImageManager.cpp b/src/vkcv/ImageManager.cpp index cdfd32b009a8007b606c86bf087b3f921b2bb89f..1e3d19d02d7e86546d142bb64440364407e81824 100644 --- a/src/vkcv/ImageManager.cpp +++ b/src/vkcv/ImageManager.cpp @@ -6,6 +6,7 @@ #include "ImageManager.hpp" #include "vkcv/Core.hpp" #include "ImageLayoutTransitions.hpp" +#include "vkcv/Logger.hpp" #include <algorithm> @@ -206,7 +207,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::getVulkanImage invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return nullptr; } @@ -219,7 +220,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::getVulkanDeviceMemory invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return nullptr; } @@ -232,7 +233,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::getVulkanImageView invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return nullptr; } @@ -245,7 +246,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::switchImageLayout invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return; } @@ -280,7 +281,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::switchImageLayout invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return; } @@ -295,7 +296,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::fillImage invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return; } @@ -369,7 +370,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::getImageWidth invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return 0; } @@ -382,7 +383,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::getImageHeight invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return 0; } @@ -395,7 +396,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::getImageDepth invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return 0; } @@ -407,7 +408,7 @@ namespace vkcv { void ImageManager::destroyImageById(uint64_t id) { if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::destroyImageById invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return; } @@ -436,7 +437,7 @@ namespace vkcv { const uint64_t id = handle.getId(); if (id >= m_images.size()) { - std::cerr << "Error: ImageManager::destroyImageById invalid handle" << std::endl; + vkcv_log(LogLevel::ERROR, "Invalid handle"); return vk::Format::eUndefined; } diff --git a/src/vkcv/PipelineConfig.cpp b/src/vkcv/PipelineConfig.cpp deleted file mode 100644 index ad8437ca2a6c07862f66485c74c89ccba0d69ebe..0000000000000000000000000000000000000000 --- a/src/vkcv/PipelineConfig.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @authors Mara Vogt, Mark Mints - * @file src/vkcv/Pipeline.cpp - * @brief Pipeline class to handle shader stages - */ - -#include "vkcv/PipelineConfig.hpp" - -namespace vkcv { - - PipelineConfig::PipelineConfig( - const ShaderProgram& shaderProgram, - uint32_t width, - uint32_t height, - const PassHandle &passHandle, - const std::vector<VertexAttribute> &vertexAttributes, - const std::vector<vk::DescriptorSetLayout> &descriptorLayouts, - bool useDynamicViewport) - : - m_ShaderProgram(shaderProgram), - m_Height(height), - m_Width(width), - m_PassHandle(passHandle), - m_VertexAttributes(vertexAttributes), - m_DescriptorLayouts(descriptorLayouts), - m_UseDynamicViewport(useDynamicViewport) - {} -} diff --git a/src/vkcv/PipelineManager.cpp b/src/vkcv/PipelineManager.cpp index 28a64a243b9a7a8fc9372409ef3783901219c868..949e5b9f713f3cac72d67b8a22cae46fc12aef0d 100644 --- a/src/vkcv/PipelineManager.cpp +++ b/src/vkcv/PipelineManager.cpp @@ -1,13 +1,13 @@ #include "PipelineManager.hpp" #include "vkcv/Image.hpp" +#include "vkcv/Logger.hpp" namespace vkcv { PipelineManager::PipelineManager(vk::Device device) noexcept : m_Device{device}, - m_Pipelines{}, - m_Configs{} + m_Pipelines{} {} PipelineManager::~PipelineManager() noexcept @@ -18,17 +18,27 @@ namespace vkcv } // currently assuming default 32 bit formats, no lower precision or normalized variants supported - vk::Format vertexFormatToVulkanFormat(const VertexFormat format) { + vk::Format vertexFormatToVulkanFormat(const VertexAttachmentFormat format) { switch (format) { - case VertexFormat::FLOAT: return vk::Format::eR32Sfloat; - case VertexFormat::FLOAT2: return vk::Format::eR32G32Sfloat; - case VertexFormat::FLOAT3: return vk::Format::eR32G32B32Sfloat; - case VertexFormat::FLOAT4: return vk::Format::eR32G32B32A32Sfloat; - case VertexFormat::INT: return vk::Format::eR32Sint; - case VertexFormat::INT2: return vk::Format::eR32G32Sint; - case VertexFormat::INT3: return vk::Format::eR32G32B32Sint; - case VertexFormat::INT4: return vk::Format::eR32G32B32A32Sint; - default: std::cerr << "Warning: Unknown vertex format" << std::endl; return vk::Format::eUndefined; + case VertexAttachmentFormat::FLOAT: + return vk::Format::eR32Sfloat; + case VertexAttachmentFormat::FLOAT2: + return vk::Format::eR32G32Sfloat; + case VertexAttachmentFormat::FLOAT3: + return vk::Format::eR32G32B32Sfloat; + case VertexAttachmentFormat::FLOAT4: + return vk::Format::eR32G32B32A32Sfloat; + case VertexAttachmentFormat::INT: + return vk::Format::eR32Sint; + case VertexAttachmentFormat::INT2: + return vk::Format::eR32G32Sint; + case VertexAttachmentFormat::INT3: + return vk::Format::eR32G32B32Sint; + case VertexAttachmentFormat::INT4: + return vk::Format::eR32G32B32A32Sint; + default: + vkcv_log(LogLevel::WARNING, "Unknown vertex format"); + return vk::Format::eUndefined; } } @@ -40,7 +50,7 @@ namespace vkcv const bool existsFragmentShader = config.m_ShaderProgram.existsShader(ShaderStage::FRAGMENT); if (!(existsVertexShader && existsFragmentShader)) { - std::cout << "Core::createGraphicsPipeline requires vertex and fragment shader code" << std::endl; + vkcv_log(LogLevel::ERROR, "Requires vertex and fragment shader code"); return PipelineHandle(); } @@ -83,24 +93,24 @@ namespace vkcv std::vector<vk::VertexInputAttributeDescription> vertexAttributeDescriptions; std::vector<vk::VertexInputBindingDescription> vertexBindingDescriptions; - VertexLayout layout = config.m_ShaderProgram.getVertexLayout(); - std::unordered_map<uint32_t, VertexInputAttachment> attachments = layout.attachmentMap; + const VertexLayout &layout = config.m_VertexLayout; - for (int i = 0; i < attachments.size(); i++) { - VertexInputAttachment &attachment = attachments.at(i); - - uint32_t location = attachment.location; - uint32_t binding = i; - vk::Format vertexFormat = vertexFormatToVulkanFormat(attachment.format); - - //FIXME: hoping that order is the same and compatible: add explicit mapping and validation - const VertexAttribute attribute = config.m_VertexAttributes[i]; - - vertexAttributeDescriptions.emplace_back(location, binding, vertexFormatToVulkanFormat(attachment.format), 0); - vertexBindingDescriptions.emplace_back(vk::VertexInputBindingDescription( - binding, - attribute.stride + getFormatSize(attachment.format), - vk::VertexInputRate::eVertex)); + // iterate over the layout's specified, mutually exclusive buffer bindings that make up a vertex buffer + for (const auto &vertexBinding : layout.vertexBindings) + { + vertexBindingDescriptions.emplace_back(vertexBinding.bindingLocation, + vertexBinding.stride, + vk::VertexInputRate::eVertex); + + // iterate over the bindings' specified, mutually exclusive vertex input attachments that make up a vertex + for(const auto &vertexAttachment: vertexBinding.vertexAttachments) + { + vertexAttributeDescriptions.emplace_back(vertexAttachment.inputLocation, + vertexBinding.bindingLocation, + vertexFormatToVulkanFormat(vertexAttachment.format), + vertexAttachment.offset % vertexBinding.stride); + + } } // Handover Containers to PipelineVertexInputStateCreateIngo Struct @@ -182,6 +192,7 @@ namespace vkcv {}, (config.m_DescriptorLayouts), (pushConstantRange)); + vk::PipelineLayout vkPipelineLayout{}; if (m_Device.createPipelineLayout(&pipelineLayoutCreateInfo, nullptr, &vkPipelineLayout) != vk::Result::eSuccess) { @@ -259,8 +270,7 @@ namespace vkcv m_Device.destroy(fragmentModule); const uint64_t id = m_Pipelines.size(); - m_Pipelines.push_back({ vkPipeline, vkPipelineLayout }); - m_Configs.push_back(config); + m_Pipelines.push_back({ vkPipeline, vkPipelineLayout, config }); return PipelineHandle(id, [&](uint64_t id) { destroyPipelineById(id); }); } @@ -308,10 +318,78 @@ namespace vkcv } } - const PipelineConfig &PipelineManager::getPipelineConfig(const PipelineHandle &handle) const + const PipelineConfig& PipelineManager::getPipelineConfig(const PipelineHandle &handle) const { const uint64_t id = handle.getId(); - return m_Configs.at(id); + + if (id >= m_Pipelines.size()) { + static PipelineConfig dummyConfig; + vkcv_log(LogLevel::ERROR, "Invalid handle"); + return dummyConfig; + } + + return m_Pipelines[id].m_config; } + PipelineHandle PipelineManager::createComputePipeline( + const ShaderProgram &shaderProgram, + const std::vector<vk::DescriptorSetLayout> &descriptorSetLayouts) { + + // Temporally handing over the Shader Program instead of a pipeline config + vk::ShaderModule computeModule{}; + if (createShaderModule(computeModule, shaderProgram, ShaderStage::COMPUTE) != vk::Result::eSuccess) + return PipelineHandle(); + + vk::PipelineShaderStageCreateInfo pipelineComputeShaderStageInfo( + {}, + vk::ShaderStageFlagBits::eCompute, + computeModule, + "main", + nullptr + ); + + vk::PipelineLayoutCreateInfo pipelineLayoutCreateInfo({}, descriptorSetLayouts); + + const size_t pushConstantSize = shaderProgram.getPushConstantSize(); + vk::PushConstantRange pushConstantRange(vk::ShaderStageFlagBits::eCompute, 0, pushConstantSize); + if (pushConstantSize > 0) { + pipelineLayoutCreateInfo.setPushConstantRangeCount(1); + pipelineLayoutCreateInfo.setPPushConstantRanges(&pushConstantRange); + } + + vk::PipelineLayout vkPipelineLayout{}; + if (m_Device.createPipelineLayout(&pipelineLayoutCreateInfo, nullptr, &vkPipelineLayout) != vk::Result::eSuccess) + { + m_Device.destroy(computeModule); + return PipelineHandle(); + } + + vk::ComputePipelineCreateInfo computePipelineCreateInfo{}; + computePipelineCreateInfo.stage = pipelineComputeShaderStageInfo; + computePipelineCreateInfo.layout = vkPipelineLayout; + + vk::Pipeline vkPipeline; + if (m_Device.createComputePipelines(nullptr, 1, &computePipelineCreateInfo, nullptr, &vkPipeline)!= vk::Result::eSuccess) + { + m_Device.destroy(computeModule); + return PipelineHandle(); + } + + m_Device.destroy(computeModule); + + const uint64_t id = m_Pipelines.size(); + m_Pipelines.push_back({ vkPipeline, vkPipelineLayout, PipelineConfig() }); + + return PipelineHandle(id, [&](uint64_t id) { destroyPipelineById(id); }); + } + + // There is an issue for refactoring the Pipeline Manager. + // While including Compute Pipeline Creation, some private helper functions where introduced: + + vk::Result PipelineManager::createShaderModule(vk::ShaderModule &module, const ShaderProgram &shaderProgram, const ShaderStage stage) + { + std::vector<char> code = shaderProgram.getShader(stage).shaderCode; + vk::ShaderModuleCreateInfo moduleInfo({}, code.size(), reinterpret_cast<uint32_t*>(code.data())); + return m_Device.createShaderModule(&moduleInfo, nullptr, &module); + } } \ No newline at end of file diff --git a/src/vkcv/PipelineManager.hpp b/src/vkcv/PipelineManager.hpp index e243151f7248c07fa0287bb2eaf698e5080f7f61..b153eb4632b844e84b92953fe8abf6666a13e0c9 100644 --- a/src/vkcv/PipelineManager.hpp +++ b/src/vkcv/PipelineManager.hpp @@ -14,14 +14,16 @@ namespace vkcv struct Pipeline { vk::Pipeline m_handle; vk::PipelineLayout m_layout; + PipelineConfig m_config; }; vk::Device m_Device; std::vector<Pipeline> m_Pipelines; - std::vector<PipelineConfig> m_Configs; void destroyPipelineById(uint64_t id); - + + vk::Result createShaderModule(vk::ShaderModule &module, const ShaderProgram &shaderProgram, ShaderStage stage); + public: PipelineManager() = delete; // no default ctor explicit PipelineManager(vk::Device device) noexcept; // ctor @@ -35,6 +37,10 @@ namespace vkcv PipelineHandle createPipeline(const PipelineConfig &config, PassManager& passManager); + PipelineHandle createComputePipeline( + const ShaderProgram& shaderProgram, + const std::vector<vk::DescriptorSetLayout>& descriptorSetLayouts); + [[nodiscard]] vk::Pipeline getVkPipeline(const PipelineHandle &handle) const; diff --git a/src/vkcv/QueueManager.cpp b/src/vkcv/QueueManager.cpp index e4d1a2d3a3302fc435c4c278322c08f51f19be6b..df6c74cccf6c4652adc6a4c78802f282ea6ae293 100644 --- a/src/vkcv/QueueManager.cpp +++ b/src/vkcv/QueueManager.cpp @@ -4,7 +4,7 @@ #include <iostream> #include "vkcv/QueueManager.hpp" - +#include "vkcv/Logger.hpp" namespace vkcv { @@ -95,7 +95,8 @@ namespace vkcv { found = true; } } - std::cerr << "Warning: not enough \"" << vk::to_string(qFlag) << "\"-Queues." << std::endl; + + vkcv_log(LogLevel::WARNING, "Not enough %s queues", vk::to_string(qFlag).c_str()); } break; case vk::QueueFlagBits::eCompute: @@ -116,7 +117,8 @@ namespace vkcv { found = true; } } - std::cerr << "Warning: not enough \"" << vk::to_string(qFlag) << "\"-Queues." << std::endl; + + vkcv_log(LogLevel::WARNING, "Not enough %s queues", vk::to_string(qFlag).c_str()); } break; case vk::QueueFlagBits::eTransfer: @@ -137,7 +139,8 @@ namespace vkcv { found = true; } } - std::cerr << "Warning: not enough \"" << vk::to_string(qFlag) << "\"-Queues." << std::endl; + + vkcv_log(LogLevel::WARNING, "Not enough %s queues", vk::to_string(qFlag).c_str()); } break; default: diff --git a/src/vkcv/ShaderProgram.cpp b/src/vkcv/ShaderProgram.cpp index 3eea7ed21d99af2768d48e62af47cbdef94c7ef1..971797d9a42d071a1730ebf31a0b554f92fa361f 100644 --- a/src/vkcv/ShaderProgram.cpp +++ b/src/vkcv/ShaderProgram.cpp @@ -5,7 +5,7 @@ */ #include "vkcv/ShaderProgram.hpp" -#include <algorithm> +#include "vkcv/Logger.hpp" namespace vkcv { /** @@ -14,32 +14,36 @@ namespace vkcv { * @param[in] relative path to the shader code * @return vector of chars as a buffer for the code */ - std::vector<char> readShaderCode(const std::filesystem::path &shaderPath) - { - std::ifstream file(shaderPath.string(), std::ios::ate | std::ios::binary); + std::vector<char> readShaderCode(const std::filesystem::path &shaderPath) { + std::ifstream file (shaderPath.string(), std::ios::ate | std::ios::binary); + if (!file.is_open()) { - std::cout << "The file could not be opened." << std::endl; + vkcv_log(LogLevel::ERROR, "The file could not be opened"); return std::vector<char>{}; } + size_t fileSize = (size_t)file.tellg(); std::vector<char> buffer(fileSize); + file.seekg(0); file.read(buffer.data(), fileSize); + file.close(); + return buffer; } - VertexFormat convertFormat(spirv_cross::SPIRType::BaseType basetype, uint32_t vecsize){ + VertexAttachmentFormat convertFormat(spirv_cross::SPIRType::BaseType basetype, uint32_t vecsize){ switch (basetype) { case spirv_cross::SPIRType::Int: switch (vecsize) { case 1: - return VertexFormat::INT; + return VertexAttachmentFormat::INT; case 2: - return VertexFormat::INT2; + return VertexAttachmentFormat::INT2; case 3: - return VertexFormat::INT3; + return VertexAttachmentFormat::INT3; case 4: - return VertexFormat::INT4; + return VertexAttachmentFormat::INT4; default: break; } @@ -47,13 +51,13 @@ namespace vkcv { case spirv_cross::SPIRType::Float: switch (vecsize) { case 1: - return VertexFormat::FLOAT; + return VertexAttachmentFormat::FLOAT; case 2: - return VertexFormat::FLOAT2; + return VertexAttachmentFormat::FLOAT2; case 3: - return VertexFormat::FLOAT3; + return VertexAttachmentFormat::FLOAT3; case 4: - return VertexFormat::FLOAT4; + return VertexAttachmentFormat::FLOAT4; default: break; } @@ -61,27 +65,31 @@ namespace vkcv { default: break; } - std::cout << "Shader Program Reflection: unknown Vertex Format" << std::endl; - return VertexFormat::FLOAT; + + vkcv_log(LogLevel::WARNING, "Unknown vertex format"); + return VertexAttachmentFormat::FLOAT; } ShaderProgram::ShaderProgram() noexcept : m_Shaders{}, - m_VertexLayout{} + m_VertexAttachments{}, + m_DescriptorSets{} {} bool ShaderProgram::addShader(ShaderStage shaderStage, const std::filesystem::path &shaderPath) { - if(m_Shaders.find(shaderStage) != m_Shaders.end()) - std::cout << "Found existing shader stage. Overwriting." << std::endl; + if(m_Shaders.find(shaderStage) != m_Shaders.end()) { + vkcv_log(LogLevel::WARNING, "Overwriting existing shader stage"); + } const std::vector<char> shaderCode = readShaderCode(shaderPath); - if (shaderCode.empty()) - return false; - else - { + + if (shaderCode.empty()) { + return false; + } else { Shader shader{shaderCode, shaderStage}; m_Shaders.insert(std::make_pair(shaderStage, shader)); + reflectShader(shaderStage); return true; } } @@ -104,31 +112,94 @@ namespace vkcv { auto shaderCodeChar = m_Shaders.at(shaderStage).shaderCode; std::vector<uint32_t> shaderCode; - for (uint32_t i = 0; i < shaderCodeChar.size()/4; i++) { + for (uint32_t i = 0; i < shaderCodeChar.size()/4; i++) shaderCode.push_back(((uint32_t*) shaderCodeChar.data())[i]); - } spirv_cross::Compiler comp(move(shaderCode)); spirv_cross::ShaderResources resources = comp.get_shader_resources(); - if (shaderStage == ShaderStage::VERTEX) { - std::vector<VertexInputAttachment> inputVec; - uint32_t offset = 0; + //reflect vertex input + if (shaderStage == ShaderStage::VERTEX) + { + // spirv-cross API (hopefully) returns the stage_inputs in order + for (uint32_t i = 0; i < resources.stage_inputs.size(); i++) + { + // spirv-cross specific objects + auto& stage_input = resources.stage_inputs[i]; + const spirv_cross::SPIRType& base_type = comp.get_type(stage_input.base_type_id); + + // vertex input location + const uint32_t attachment_loc = comp.get_decoration(stage_input.id, spv::DecorationLocation); + // vertex input name + const std::string attachment_name = stage_input.name; + // vertex input format (implies its size) + const VertexAttachmentFormat attachment_format = convertFormat(base_type.basetype, base_type.vecsize); + + m_VertexAttachments.emplace_back(attachment_loc, attachment_name, attachment_format); + } + } - for (uint32_t i = 0; i < resources.stage_inputs.size(); i++) { - auto& u = resources.stage_inputs[i]; - const spirv_cross::SPIRType& base_type = comp.get_type(u.base_type_id); + //reflect descriptor sets (uniform buffer, storage buffer, sampler, sampled image, storage image) + std::vector<std::pair<uint32_t, DescriptorBinding>> bindings; + int32_t maxSetID = -1; + for (uint32_t i = 0; i < resources.uniform_buffers.size(); i++) { + auto& u = resources.uniform_buffers[i]; + const spirv_cross::SPIRType& base_type = comp.get_type(u.base_type_id); + std::pair descriptor(comp.get_decoration(u.id, spv::DecorationDescriptorSet), + DescriptorBinding(comp.get_decoration(u.id, spv::DecorationBinding), DescriptorType::UNIFORM_BUFFER, base_type.vecsize, shaderStage)); + bindings.push_back(descriptor); + if ((int32_t)comp.get_decoration(u.id, spv::DecorationDescriptorSet) > maxSetID) + maxSetID = comp.get_decoration(u.id, spv::DecorationDescriptorSet); + } - VertexInputAttachment input = VertexInputAttachment(comp.get_decoration(u.id, spv::DecorationLocation), - 0, - convertFormat(base_type.basetype, base_type.vecsize), - offset); - inputVec.push_back(input); - offset += base_type.vecsize * base_type.width / 8; - } + for (uint32_t i = 0; i < resources.storage_buffers.size(); i++) { + auto& u = resources.storage_buffers[i]; + const spirv_cross::SPIRType& base_type = comp.get_type(u.base_type_id); + std::pair descriptor(comp.get_decoration(u.id, spv::DecorationDescriptorSet), + DescriptorBinding(comp.get_decoration(u.id, spv::DecorationBinding), DescriptorType::STORAGE_BUFFER, base_type.vecsize, shaderStage)); + bindings.push_back(descriptor); + if ((int32_t)comp.get_decoration(u.id, spv::DecorationDescriptorSet) > maxSetID) + maxSetID = comp.get_decoration(u.id, spv::DecorationDescriptorSet); + } - m_VertexLayout = VertexLayout(inputVec); - } + for (uint32_t i = 0; i < resources.separate_samplers.size(); i++) { + auto& u = resources.separate_samplers[i]; + const spirv_cross::SPIRType& base_type = comp.get_type(u.base_type_id); + std::pair descriptor(comp.get_decoration(u.id, spv::DecorationDescriptorSet), + DescriptorBinding(comp.get_decoration(u.id, spv::DecorationBinding), DescriptorType::SAMPLER, base_type.vecsize, shaderStage)); + bindings.push_back(descriptor); + if ((int32_t)comp.get_decoration(u.id, spv::DecorationDescriptorSet) > maxSetID) + maxSetID = comp.get_decoration(u.id, spv::DecorationDescriptorSet); + } + + for (uint32_t i = 0; i < resources.separate_images.size(); i++) { + auto& u = resources.separate_images[i]; + const spirv_cross::SPIRType& base_type = comp.get_type(u.base_type_id); + std::pair descriptor(comp.get_decoration(u.id, spv::DecorationDescriptorSet), + DescriptorBinding(comp.get_decoration(u.id, spv::DecorationBinding), DescriptorType::IMAGE_SAMPLED, base_type.vecsize, shaderStage)); + bindings.push_back(descriptor); + if ((int32_t)comp.get_decoration(u.id, spv::DecorationDescriptorSet) > maxSetID) + maxSetID = comp.get_decoration(u.id, spv::DecorationDescriptorSet); + + } + + for (uint32_t i = 0; i < resources.storage_images.size(); i++) { + auto& u = resources.storage_images[i]; + const spirv_cross::SPIRType& base_type = comp.get_type(u.base_type_id); + std::pair descriptor(comp.get_decoration(u.id, spv::DecorationDescriptorSet), + DescriptorBinding(comp.get_decoration(u.id, spv::DecorationBinding), DescriptorType::IMAGE_STORAGE, base_type.vecsize, shaderStage)); + bindings.push_back(descriptor); + if ((int32_t)comp.get_decoration(u.id, spv::DecorationDescriptorSet) > maxSetID) + maxSetID = comp.get_decoration(u.id, spv::DecorationDescriptorSet); + } + if (maxSetID != -1) { + if((int32_t)m_DescriptorSets.size() <= maxSetID) m_DescriptorSets.resize(maxSetID + 1); + for (const auto &binding : bindings) { + m_DescriptorSets[binding.first].push_back(binding.second); + } + } + + //reflect push constants for (const auto &pushConstantBuffer : resources.push_constant_buffers) { for (const auto &range : comp.get_active_buffer_ranges(pushConstantBuffer.id)) { const size_t size = range.range + range.offset; @@ -137,11 +208,17 @@ namespace vkcv { } } - const VertexLayout& ShaderProgram::getVertexLayout() const{ - return m_VertexLayout; + const std::vector<VertexAttachment> &ShaderProgram::getVertexAttachments() const + { + return m_VertexAttachments; } - size_t ShaderProgram::getPushConstantSize() const { + const std::vector<std::vector<DescriptorBinding>>& ShaderProgram::getReflectedDescriptors() const { + return m_DescriptorSets; + } + + size_t ShaderProgram::getPushConstantSize() const + { return m_pushConstantSize; } } diff --git a/src/vkcv/SwapChain.cpp b/src/vkcv/Swapchain.cpp similarity index 88% rename from src/vkcv/SwapChain.cpp rename to src/vkcv/Swapchain.cpp index b787536b66cfd802dfd435a773a584c875eeb391..639e949bc442588ece4e13b92bd032ecbd513352 100644 --- a/src/vkcv/SwapChain.cpp +++ b/src/vkcv/Swapchain.cpp @@ -1,4 +1,4 @@ -#include <vkcv/SwapChain.hpp> +#include <vkcv/Swapchain.hpp> #include <utility> #define GLFW_INCLUDE_VULKAN @@ -27,44 +27,44 @@ namespace vkcv return vk::SurfaceKHR(surface); } - SwapChain::SwapChain(const Surface &surface, + Swapchain::Swapchain(const Surface &surface, vk::SwapchainKHR swapchain, vk::Format format, vk::ColorSpaceKHR colorSpace, vk::PresentModeKHR presentMode, uint32_t imageCount, vk::Extent2D extent) noexcept : - m_Surface(surface), - m_Swapchain(swapchain), - m_SwapchainFormat(format), - m_SwapchainColorSpace(colorSpace), - m_SwapchainPresentMode(presentMode), - m_SwapchainImageCount(imageCount), - m_Extent(extent), - m_RecreationRequired(false) + m_Surface(surface), + m_Swapchain(swapchain), + m_Format(format), + m_ColorSpace(colorSpace), + m_PresentMode(presentMode), + m_ImageCount(imageCount), + m_Extent(extent), + m_RecreationRequired(false) {} - SwapChain::SwapChain(const SwapChain &other) : + Swapchain::Swapchain(const Swapchain &other) : m_Surface(other.m_Surface), m_Swapchain(other.m_Swapchain), - m_SwapchainFormat(other.m_SwapchainFormat), - m_SwapchainColorSpace(other.m_SwapchainColorSpace), - m_SwapchainPresentMode(other.m_SwapchainPresentMode), - m_SwapchainImageCount(other.m_SwapchainImageCount), + m_Format(other.m_Format), + m_ColorSpace(other.m_ColorSpace), + m_PresentMode(other.m_PresentMode), + m_ImageCount(other.m_ImageCount), m_Extent(other.m_Extent), m_RecreationRequired(other.m_RecreationRequired.load()) {} - const vk::SwapchainKHR& SwapChain::getSwapchain() const { + const vk::SwapchainKHR& Swapchain::getSwapchain() const { return m_Swapchain; } - vk::SurfaceKHR SwapChain::getSurface() const { + vk::SurfaceKHR Swapchain::getSurface() const { return m_Surface.handle; } - vk::Format SwapChain::getSwapchainFormat() const{ - return m_SwapchainFormat; + vk::Format Swapchain::getFormat() const{ + return m_Format; } /** @@ -162,7 +162,7 @@ namespace vkcv * @param context that keeps instance, physicalDevice and a device. * @return swapchain */ - SwapChain SwapChain::create(const Window &window, const Context &context) { + Swapchain Swapchain::create(const Window &window, const Context &context) { const vk::Instance& instance = context.getInstance(); const vk::PhysicalDevice& physicalDevice = context.getPhysicalDevice(); const vk::Device& device = context.getDevice(); @@ -199,7 +199,7 @@ namespace vkcv vk::SwapchainKHR swapchain = device.createSwapchainKHR(swapchainCreateInfo); - return SwapChain(surface, + return Swapchain(surface, swapchain, chosenSurfaceFormat.format, chosenSurfaceFormat.colorSpace, @@ -208,11 +208,11 @@ namespace vkcv chosenExtent); } - bool SwapChain::shouldUpdateSwapchain() const { + bool Swapchain::shouldUpdateSwapchain() const { return m_RecreationRequired; } - void SwapChain::updateSwapchain(const Context &context, const Window &window) { + void Swapchain::updateSwapchain(const Context &context, const Window &window) { if (!m_RecreationRequired.exchange(false)) return; @@ -222,9 +222,9 @@ namespace vkcv vk::SwapchainCreateInfoKHR swapchainCreateInfo( vk::SwapchainCreateFlagsKHR(), m_Surface.handle, - m_SwapchainImageCount, - m_SwapchainFormat, - m_SwapchainColorSpace, + m_ImageCount, + m_Format, + m_ColorSpace, extent2D, 1, vk::ImageUsageFlagBits::eColorAttachment, @@ -233,7 +233,7 @@ namespace vkcv nullptr, vk::SurfaceTransformFlagBitsKHR::eIdentity, vk::CompositeAlphaFlagBitsKHR::eOpaque, - m_SwapchainPresentMode, + m_PresentMode, true, oldSwapchain ); @@ -244,19 +244,19 @@ namespace vkcv m_Extent = extent2D; } - void SwapChain::signalSwapchainRecreation() { + void Swapchain::signalSwapchainRecreation() { m_RecreationRequired = true; } - const vk::Extent2D& SwapChain::getExtent() const { + const vk::Extent2D& Swapchain::getExtent() const { return m_Extent; } - SwapChain::~SwapChain() { + Swapchain::~Swapchain() { // needs to be destroyed by creator } - uint32_t SwapChain::getImageCount() { - return m_SwapchainImageCount; + uint32_t Swapchain::getImageCount() const { + return m_ImageCount; } } diff --git a/src/vkcv/VertexLayout.cpp b/src/vkcv/VertexLayout.cpp index b06c6743e1e19a5e282af248ab6b590eb97529fd..fa079a3264ae47b32461bda26485adb97b0be280 100644 --- a/src/vkcv/VertexLayout.cpp +++ b/src/vkcv/VertexLayout.cpp @@ -3,51 +3,60 @@ // #include "vkcv/VertexLayout.hpp" +#include "vkcv/Logger.hpp" namespace vkcv { - uint32_t getFormatSize(VertexFormat format) { + uint32_t getFormatSize(VertexAttachmentFormat format) { switch (format) { - case VertexFormat::FLOAT: + case VertexAttachmentFormat::FLOAT: return 4; - case VertexFormat::FLOAT2: + case VertexAttachmentFormat::FLOAT2: return 8; - case VertexFormat::FLOAT3: + case VertexAttachmentFormat::FLOAT3: return 12; - case VertexFormat::FLOAT4: + case VertexAttachmentFormat::FLOAT4: return 16; - case VertexFormat::INT: + case VertexAttachmentFormat::INT: return 4; - case VertexFormat::INT2: + case VertexAttachmentFormat::INT2: return 8; - case VertexFormat::INT3: + case VertexAttachmentFormat::INT3: return 12; - case VertexFormat::INT4: + case VertexAttachmentFormat::INT4: return 16; default: - break; + vkcv_log(LogLevel::WARNING, "No format given"); + return 0; } - std::cout << "VertexLayout: No format given" << std::endl; - return 0; } - VertexInputAttachment::VertexInputAttachment(uint32_t location, uint32_t binding, VertexFormat format, uint32_t offset) noexcept: - location{location}, - binding{binding}, + VertexAttachment::VertexAttachment(uint32_t inputLocation, const std::string &name, VertexAttachmentFormat format) noexcept: + inputLocation{inputLocation}, + name{name}, format{format}, - offset{offset} - {} - - VertexLayout::VertexLayout() noexcept : - stride{0}, - attachmentMap() + offset{0} {} - VertexLayout::VertexLayout(const std::vector<VertexInputAttachment> &inputs) noexcept { - stride = 0; - for (const auto &input : inputs) { - attachmentMap.insert(std::make_pair(input.location, input)); - stride += getFormatSize(input.format); + + VertexBinding::VertexBinding(uint32_t bindingLocation, const std::vector<VertexAttachment> &attachments) noexcept : + bindingLocation{bindingLocation}, + stride{0}, + vertexAttachments{attachments} + { + uint32_t offset = 0; + for (auto &attachment : vertexAttachments) + { + offset += getFormatSize(attachment.format); + attachment.offset = offset; } + stride = offset; } + VertexLayout::VertexLayout() noexcept : + vertexBindings{} + {} + + VertexLayout::VertexLayout(const std::vector<VertexBinding> &bindings) noexcept : + vertexBindings{bindings} + {} } \ No newline at end of file diff --git a/src/vkcv/Window.cpp b/src/vkcv/Window.cpp index c21271b78f7501721d5c0496d0344dd68e2e7e52..2436619300c24f035cba727481dfce8e1b397c9b 100644 --- a/src/vkcv/Window.cpp +++ b/src/vkcv/Window.cpp @@ -24,22 +24,25 @@ namespace vkcv { glfwTerminate(); } } + + GLFWwindow* Window::createGLFWWindow(const char *windowTitle, int width, int height, bool resizable) { + if(s_WindowCount == 0) { + glfwInit(); + } + + s_WindowCount++; + + width = std::max(width, 1); + height = std::max(height, 1); + + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + glfwWindowHint(GLFW_RESIZABLE, resizable ? GLFW_TRUE : GLFW_FALSE); + + return glfwCreateWindow(width, height, windowTitle, nullptr, nullptr); + } Window Window::create( const char *windowTitle, int width, int height, bool resizable) { - if(s_WindowCount == 0) { - glfwInit(); - } - s_WindowCount++; - - width = std::max(width, 1); - height = std::max(height, 1); - - glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - glfwWindowHint(GLFW_RESIZABLE, resizable ? GLFW_TRUE : GLFW_FALSE); - GLFWwindow *window; - window = glfwCreateWindow(width, height, windowTitle, nullptr, nullptr); - - return Window(window); + return Window(createGLFWWindow(windowTitle, width, height, resizable)); } void Window::initEvents() { @@ -55,6 +58,8 @@ namespace vkcv { glfwSetKeyCallback(m_window, Window::onKeyEvent); glfwSetScrollCallback(m_window, Window::onMouseScrollEvent); + + glfwSetCharCallback(m_window, Window::onCharEvent); } void Window::pollEvents() { @@ -62,7 +67,6 @@ namespace vkcv { } void Window::onMouseButtonEvent(GLFWwindow *callbackWindow, int button, int action, int mods) { - auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); if (window != nullptr) { @@ -71,7 +75,6 @@ namespace vkcv { } void Window::onMouseMoveEvent(GLFWwindow *callbackWindow, double x, double y) { - auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); if (window != nullptr) { @@ -88,7 +91,6 @@ namespace vkcv { } void Window::onResize(GLFWwindow *callbackWindow, int width, int height) { - auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); if (window != nullptr) { @@ -97,13 +99,20 @@ namespace vkcv { } void Window::onKeyEvent(GLFWwindow *callbackWindow, int key, int scancode, int action, int mods) { - auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); if (window != nullptr) { window->e_key(key, scancode, action, mods); } } + + void Window::onCharEvent(GLFWwindow *callbackWindow, unsigned int c) { + auto window = static_cast<Window *>(glfwGetWindowUserPointer(callbackWindow)); + + if (window != nullptr) { + window->e_char(c); + } + } bool Window::isWindowOpen() const { return !glfwWindowShouldClose(m_window);