Compare commits
19 Commits
f4e77e30a8
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bca88e51ed | ||
|
|
0b15b55520 | ||
|
|
ed9d01010a | ||
|
|
02fe285a9d | ||
|
|
c12325d30c | ||
|
|
201f5896ce | ||
|
|
d34bb57402 | ||
|
|
dea1ffee49 | ||
|
|
2eb42da357 | ||
|
|
ff7f3e86ee | ||
|
|
36fbbefe55 | ||
|
|
0f08088f39 | ||
|
|
c3924b05c1 | ||
|
|
cfce4b3069 | ||
|
|
edcf13d62a | ||
|
|
5dc0974d50 | ||
|
|
4c1226f658 | ||
|
|
46d5e41e29 | ||
|
|
e887b2b393 |
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
# Compiled shader output #
|
||||
*.spv
|
||||
7
.idea/dictionaries/project.xml
generated
Normal file
7
.idea/dictionaries/project.xml
generated
Normal file
@@ -0,0 +1,7 @@
|
||||
<component name="ProjectDictionaryState">
|
||||
<dictionary name="project">
|
||||
<words>
|
||||
<w>spirv</w>
|
||||
</words>
|
||||
</dictionary>
|
||||
</component>
|
||||
23
.idea/editor.xml
generated
23
.idea/editor.xml
generated
@@ -1,6 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="BackendCodeEditorSettings">
|
||||
<option name="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=6EF66A4B_002D3E31_002D529B_002D8F75_002D540403659512_002Fd_003Asrc_002Fd_003Amanagers_002Fd_003Avulkan_002Ff_003AVulkanManagerRender_002Ecpp/@EntryIndexedValue" value="ForceIncluded" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CDeclarationWithImplicitIntType/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CommentTypo/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=ConstevalIfIsAlwaysConstant/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
@@ -131,8 +132,8 @@
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNoDiscardExpression/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNodiscardFunctionWithoutReturnValue/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonExceptionSafeResourceAcquisition/@EntryIndexedValue" value="HINT" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonExplicitConversionOperator/@EntryIndexedValue" value="HINT" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonExplicitConvertingConstructor/@EntryIndexedValue" value="HINT" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonExplicitConversionOperator/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonExplicitConvertingConstructor/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonInlineFunctionDefinitionInHeaderFile/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNonInlineVariableDefinitionInHeaderFile/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppNotAllPathsReturnValue/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
@@ -252,5 +253,23 @@
|
||||
<option name="/Default/CodeStyle/CodeFormatting/CppCodeStyle/OverridingFunctionStyle/@EntryValue" value="VirtualAndOverride" type="string" />
|
||||
<option name="/Default/CodeStyle/CodeFormatting/CppCodeStyle/UseAutoCommonCase/@EntryValue" value="Never" type="string" />
|
||||
<option name="/Default/CodeStyle/CppIncludeDirective/SortIncludeDirectives/@EntryValue" value="true" type="bool" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=0AFB7787612DF743B09AD9412E48D4CC/@EntryIndexedValue" value="<NamingElement Priority="7" Title="Local variables"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="local variable" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="aaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=0B82708A1BA7774EB13D27F245698A56/@EntryIndexedValue" value="<NamingElement Priority="1" Title="Classes and structs"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="__interface" /><type Name="class" /><type Name="struct" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=1350D079A82E0740947E85445B5AF47C/@EntryIndexedValue" value="<NamingElement Priority="6" Title="Parameters"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="function parameter" /><type Name="lambda parameter" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="aaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=1CBDD658AEE8EA4382EE1F914B5B3314/@EntryIndexedValue" value="<NamingElement Priority="18" Title="Namespaces"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="namespace" /><type Name="namespace alias" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=2229A2BE1AA9214483A51F028530E042/@EntryIndexedValue" value="<NamingElement Priority="4" Title="Unions"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="union" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=2B232F1067F0324F8FF4B9D63ACECDB2/@EntryIndexedValue" value="<NamingElement Priority="16" Title="Other constants"><Descriptor Static="True" Constexpr="Indeterminate" Const="True" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="class field" /><type Name="local variable" /><type Name="struct field" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AA_BB" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=4203BE6F332C5149B409B4D5F7197E54/@EntryIndexedValue" value="<NamingElement Priority="15" Title="Enumerators"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="scoped enumerator" /><type Name="unscoped enumerator" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AA_BB" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=5653BA7B6222F349B94149A2A53C35B8/@EntryIndexedValue" value="<NamingElement Priority="14" Title="Union members"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="union member" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="m_" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=72514D5DF422D442B71A277F97B72887/@EntryIndexedValue" value="<NamingElement Priority="8" Title="Global variables"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="global variable" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AA_BB" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=821F3C5CF47D5640AD3511BCBADE17C4/@EntryIndexedValue" value="<NamingElement Priority="9" Title="Lambdas"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="lambda" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="aaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=8F69F48E2532F54CBAA0039D4557825E/@EntryIndexedValue" value="<NamingElement Priority="10" Title="Global functions"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="global function" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=A42D627FA43B054F91D1E1C4281D8896/@EntryIndexedValue" value="<NamingElement Priority="2" Title="Concepts"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="concept" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=A4FAA2257682A94F8C2C93E123FAFC7A/@EntryIndexedValue" value="<NamingElement Priority="19" Title="Typedefs"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="type alias" /><type Name="typedef" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=A7EBF16DA3BDCB42A0B710704BC8A053/@EntryIndexedValue" value="<NamingElement Priority="3" Title="Enums"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="enum" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=B6E900853D6D05429D8C57765B2E546A/@EntryIndexedValue" value="<NamingElement Priority="11" Title="Class and struct methods"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="member function" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=B82A063F0DDD98498A70D8D7EBB97F8D/@EntryIndexedValue" value="<NamingElement Priority="12" Title="Class and struct fields"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="class field" /><type Name="struct field" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="m_" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=BBE8AA08E662BF409B2CB08EC597C493/@EntryIndexedValue" value="<NamingElement Priority="13" Title="Class and struct public fields"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="PUBLIC"><type Name="class field" /><type Name="struct field" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="m_" Suffix="" Style="AaBb" /></NamingElement>" type="string" />
|
||||
<option name="/Default/CodeStyle/Naming/CppNamingOptions/Rules/=BF0D1AE66D64FE4FAF613448A12051A0/@EntryIndexedValue" value="<NamingElement Priority="17" Title="Global constants"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="True" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="global variable" /></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AA_BB" /></NamingElement>" type="string" />
|
||||
</component>
|
||||
</project>
|
||||
7
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
7
.idea/inspectionProfiles/Project_Default.xml
generated
Normal file
@@ -0,0 +1,7 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="CppNonExplicitConversionOperator" enabled="false" level="HINT" enabled_by_default="false" />
|
||||
<inspection_tool class="CppNonExplicitConvertingConstructor" enabled="false" level="HINT" enabled_by_default="false" />
|
||||
</profile>
|
||||
</component>
|
||||
1
.idea/vcs.xml
generated
1
.idea/vcs.xml
generated
@@ -3,5 +3,6 @@
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$/cmake-build-debug/_deps/glfw-src" vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$/cmake-build-release/_deps/glfw-src" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -27,18 +27,45 @@ FetchContent_Declare(
|
||||
|
||||
FetchContent_MakeAvailable(glfw)
|
||||
|
||||
# Compiles the shaders #
|
||||
set(SHADER_DIR "${CMAKE_SOURCE_DIR}/shaders")
|
||||
file(GLOB SHADERS
|
||||
"${SHADER_DIR}/*.frag"
|
||||
"${SHADER_DIR}/*.vert"
|
||||
)
|
||||
|
||||
foreach (SHADER ${SHADERS})
|
||||
get_filename_component(FILENAME_WE ${SHADER} NAME_WE)
|
||||
set(SPIRV_FILE "${SHADER_DIR}/${FILENAME_WE}.spv")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${SPIRV_FILE}
|
||||
COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V ${SHADER} -o ${SPIRV_FILE}
|
||||
DEPENDS ${SHADER}
|
||||
COMMENT "Compiling shader ${FILENAME}"
|
||||
)
|
||||
|
||||
list(APPEND SPIRV_BINARY_FILES ${SPIRV_FILE})
|
||||
endforeach()
|
||||
|
||||
add_custom_target(CompileShaders ALL DEPENDS ${SPIRV_BINARY_FILES})
|
||||
|
||||
# Creates the output binary
|
||||
project(VulkanRenderer LANGUAGES CXX)
|
||||
add_executable(VulkanRenderer
|
||||
main.cpp
|
||||
src/main.cpp
|
||||
src/managers/GLFWManager.h
|
||||
src/managers/GLFWManager.cpp
|
||||
src/managers/VulkanManagerInit.cpp
|
||||
src/managers/VulkanManagerRender.cpp
|
||||
src/managers/VulkanManager.h
|
||||
src/managers/vulkan/VulkanManagerInit.cpp
|
||||
src/managers/vulkan/VulkanManagerRender.cpp
|
||||
src/managers/vulkan/VulkanManager.h
|
||||
src/VulkanRenderer.h
|
||||
src/RendererTypes.h
|
||||
src/Mesh.h
|
||||
)
|
||||
|
||||
add_dependencies(VulkanRenderer CompileShaders)
|
||||
|
||||
target_precompile_headers(VulkanRenderer PRIVATE src/VulkanRenderer.h)
|
||||
|
||||
# Links the libraries to the binary #
|
||||
|
||||
23
README.md
Normal file
23
README.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# Vulkan Renderer
|
||||
|
||||
This project is a small Vulkan renderer written in C++ (and GLSL) with CMake as the build process.
|
||||
It currently can render basic triangles in 2D space with a given colour.
|
||||
|
||||
### Build
|
||||
|
||||
```
|
||||
mkdir build
|
||||
cd build
|
||||
cmake ..
|
||||
cmake --build .
|
||||
```
|
||||
|
||||
This will work on most operating systems and compile all C++ and GLSL code to their required binary formats.
|
||||
Then all you will need to do is run the outputted binary to see the example scene.
|
||||
|
||||
### Planed Features
|
||||
|
||||
- Texture Support
|
||||
- 3D space
|
||||
- Free camera
|
||||
- Mesh (.obj) loading
|
||||
47
main.cpp
47
main.cpp
@@ -1,47 +0,0 @@
|
||||
#include "src/VulkanRenderer.h"
|
||||
|
||||
#include "src/managers/GLFWManager.h"
|
||||
#include "src/managers/VulkanManager.h"
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
void CleanupAllAndExit(int code)
|
||||
{
|
||||
if (!GLFWManager::Cleanup())
|
||||
std::exit(EXIT_FAILURE);
|
||||
|
||||
if (!VulkanManager::Cleanup())
|
||||
std::exit(EXIT_FAILURE);
|
||||
|
||||
std::exit(code);
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace PB::Renderer; // Project namespace
|
||||
|
||||
/* Initializes GLFW and creates window */
|
||||
if (!GLFWManager::Init())
|
||||
return -1;
|
||||
|
||||
GLFWwindow* window = GLFWManager::CreateWindow(800, 600, "Vulkan window");
|
||||
if (!window)
|
||||
return -1;
|
||||
|
||||
/* Runs Vulkan initialisation functions */
|
||||
if (!VulkanManager::InitAll(window))
|
||||
CleanupAllAndExit(EXIT_FAILURE);
|
||||
|
||||
/* Polls window events whilst it is still open */
|
||||
while (!glfwWindowShouldClose(window))
|
||||
{
|
||||
glfwPollEvents();
|
||||
|
||||
if (!VulkanManager::RenderPass(window))
|
||||
CleanupAllAndExit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Cleans up GLFW and Vulkan */
|
||||
CleanupAllAndExit(EXIT_SUCCESS);
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
#version 450
|
||||
layout(location = 0) out vec4 outColor;
|
||||
|
||||
layout(push_constant) uniform PC {
|
||||
vec4 color;
|
||||
} pc;
|
||||
|
||||
void main()
|
||||
{
|
||||
outColor = vec4(1.0, 0.0, 0.0, 1.0); // red
|
||||
outColor = pc.color;
|
||||
}
|
||||
|
||||
BIN
shaders/frag.spv
BIN
shaders/frag.spv
Binary file not shown.
BIN
shaders/vert.spv
BIN
shaders/vert.spv
Binary file not shown.
@@ -1,13 +1,8 @@
|
||||
#version 450
|
||||
|
||||
vec2 positions[3] = vec2[]
|
||||
(
|
||||
vec2(0.0, -0.5),
|
||||
vec2(0.5, 0.5),
|
||||
vec2(-0.5, 0.5)
|
||||
);
|
||||
layout(location = 0) in vec2 inPosition;
|
||||
|
||||
void main()
|
||||
{
|
||||
gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0);
|
||||
gl_Position = vec4(inPosition, 0.0, 1.0);
|
||||
}
|
||||
|
||||
11
src/Mesh.h
Normal file
11
src/Mesh.h
Normal file
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#include <vector>
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
struct Mesh
|
||||
{
|
||||
std::vector<float> vertices;
|
||||
std::vector<int> indices;
|
||||
};
|
||||
}
|
||||
34
src/RendererTypes.h
Normal file
34
src/RendererTypes.h
Normal file
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
struct Color
|
||||
{
|
||||
float r = 0.0f, g = 0.0f, b = 0.0f, a = 0.0f;
|
||||
};
|
||||
|
||||
namespace Colors
|
||||
{
|
||||
constexpr Color white = {1.0f, 1.0f, 1.0f, 1.0f};
|
||||
constexpr Color red = {1.0f, 0.0f, 0.0f, 1.0f};
|
||||
constexpr Color green = {0.0f, 1.0f, 0.0f, 1.0f};
|
||||
constexpr Color blue = {0.0f, 0.0f, 1.0f, 1.0f};
|
||||
constexpr Color yellow = {1.0f, 1.0f, 0.0f, 1.0f};
|
||||
constexpr Color cyan = {0.0f, 1.0f, 1.0f, 1.0f};
|
||||
constexpr Color magenta = {1.0f, 0.0f, 1.0f, 1.0f};
|
||||
}
|
||||
|
||||
class VulkanHandle
|
||||
{
|
||||
public:
|
||||
VulkanHandle(void* _handle) : handle(_handle) {}
|
||||
|
||||
template<typename Ty> operator Ty() { return static_cast<Ty>(handle); }
|
||||
void* get() const { return handle; }
|
||||
|
||||
private:
|
||||
void* handle = nullptr;
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef NDEBUG
|
||||
#define PB_DEBUG
|
||||
namespace PB::Renderer
|
||||
{
|
||||
constexpr bool DEBUG_MODE = true;
|
||||
constexpr const char* MODE_NAME = "DEBUG";
|
||||
}
|
||||
#else
|
||||
#define PB_RELEASE
|
||||
namespace PB::Renderer
|
||||
{
|
||||
constexpr bool DEBUG_MODE = false;
|
||||
constexpr const char* MODE_NAME = "RELEASE";
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Includes general project .h files */
|
||||
|
||||
#include "RendererTypes.h"
|
||||
|
||||
/* Includes dependencies */
|
||||
|
||||
#include <vulkan/vulkan.h>
|
||||
@@ -9,9 +29,10 @@
|
||||
|
||||
/* Commonly used C++ STD files */
|
||||
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
79
src/main.cpp
Normal file
79
src/main.cpp
Normal file
@@ -0,0 +1,79 @@
|
||||
#include "Mesh.h"
|
||||
#include "VulkanRenderer.h"
|
||||
|
||||
#include "managers/GLFWManager.h"
|
||||
#include "managers/vulkan/VulkanManager.h"
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
void CleanupAllAndExit(const int code)
|
||||
{
|
||||
if (!GLFWManager::Cleanup())
|
||||
std::exit(EXIT_FAILURE);
|
||||
|
||||
if (!VulkanManager::Cleanup())
|
||||
std::exit(EXIT_FAILURE);
|
||||
|
||||
std::exit(code);
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace PB::Renderer; // Project namespace
|
||||
|
||||
/* Initializes GLFW and creates a window */
|
||||
GLFWwindow* window = GLFWManager::Init(800, 600, "Vulkan window");
|
||||
if (window == nullptr)
|
||||
return -1;
|
||||
|
||||
/* Runs Vulkan initialisation functions */
|
||||
if (!VulkanManager::Init(window))
|
||||
CleanupAllAndExit(EXIT_FAILURE);
|
||||
|
||||
/* Adds runtime objects */
|
||||
{
|
||||
VulkanManager::CreateNewRenderObject
|
||||
(
|
||||
Colors::red, Mesh
|
||||
{
|
||||
.vertices =
|
||||
{
|
||||
0.0f, -0.5f,
|
||||
0.5f, 0.9f,
|
||||
-0.5f, 0.5f
|
||||
},
|
||||
|
||||
.indices = { 0, 1, 2 }
|
||||
}
|
||||
);
|
||||
|
||||
VulkanManager::CreateNewRenderObject
|
||||
(
|
||||
Colors::yellow, Mesh
|
||||
{
|
||||
.vertices =
|
||||
{
|
||||
-0.9f, 0.0f,
|
||||
-0.9f, -0.9f,
|
||||
0.0f, -0.9f
|
||||
},
|
||||
|
||||
.indices = { 0, 1, 2 }
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/* Polls window events whilst it is still open */
|
||||
while (!glfwWindowShouldClose(window))
|
||||
{
|
||||
glfwPollEvents();
|
||||
GLFWManager::UpdateWindowTitleFPSInfo();
|
||||
|
||||
if (VulkanManager::RenderPass(window) == false)
|
||||
CleanupAllAndExit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Cleans up GLFW and Vulkan */
|
||||
CleanupAllAndExit(EXIT_SUCCESS);
|
||||
}
|
||||
@@ -2,53 +2,111 @@
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
std::vector<GLFWwindow*> GLFWManager::s_Windows;
|
||||
GLFWwindow* GLFWManager::s_Window = nullptr;
|
||||
|
||||
bool GLFWManager::Init()
|
||||
int GLFWManager::s_FramesInTheLastSecond = 0;
|
||||
int GLFWManager::s_FpsCounter = 0;
|
||||
|
||||
double GLFWManager::s_LastDeltaUpdateTime = 0.0;
|
||||
double GLFWManager::s_LastFPSUpdateTime = 0.0;
|
||||
|
||||
std::string GLFWManager::s_BaseWindowTitle = {};
|
||||
|
||||
bool GLFWManager::s_Fullscreen = false;
|
||||
|
||||
int GLFWManager::s_WindowedWidth = 800;
|
||||
int GLFWManager::s_WindowedHeight = 600;
|
||||
int GLFWManager::s_WindowedPosX = 50;
|
||||
int GLFWManager::s_WindowedPosY = 50;
|
||||
|
||||
GLFWwindow* GLFWManager::Init(const int width, const int height, const char* title)
|
||||
{
|
||||
const bool success = glfwInit();
|
||||
if (!success)
|
||||
{
|
||||
std::cout << "PB::Renderer::GLFWManager::Init(): glfwInit() failed" << std::endl;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* Stops GLFW from creating openGL contexts */
|
||||
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
|
||||
return success;
|
||||
}
|
||||
|
||||
bool GLFWManager::Cleanup()
|
||||
{
|
||||
/* Closes all windows */
|
||||
for (GLFWwindow* window : s_Windows)
|
||||
glfwDestroyWindow(window);
|
||||
|
||||
glfwTerminate();
|
||||
return true; // Cannot fail (yet)
|
||||
}
|
||||
|
||||
GLFWwindow* GLFWManager::CreateWindow(int width, int height, const char* title)
|
||||
{
|
||||
/* Checks for valid window size before creation */
|
||||
if (width < 0 || height < 0)
|
||||
{
|
||||
std::cout << "PB::Renderer::GLFWManager::CreateWindow(): width or height must be < 0" << std::endl;
|
||||
return nullptr;
|
||||
}
|
||||
GLFWwindow* window = glfwCreateWindow(width, height, title, nullptr, nullptr);
|
||||
|
||||
/* Stores the window and returns it to the user */
|
||||
s_Windows.push_back(window);
|
||||
return window;
|
||||
/* Creates the window */
|
||||
s_Window = glfwCreateWindow(width, height, title, nullptr, nullptr);
|
||||
s_BaseWindowTitle = title;
|
||||
|
||||
/* Adds callbacks to the window and returns it */
|
||||
glfwSetKeyCallback(s_Window, KeyCallback);
|
||||
|
||||
return s_Window;
|
||||
}
|
||||
|
||||
GLFWwindow* GLFWManager::GetWindow(int index)
|
||||
bool GLFWManager::Cleanup()
|
||||
{
|
||||
/* Checks input is within the bounds before fetching */
|
||||
if (index >= s_Windows.size() || index < 0)
|
||||
{
|
||||
std::cout << "PB::Renderer::GLFWManager::GetWindow(): index out of bounds" << std::endl;
|
||||
return nullptr;
|
||||
if (s_Window != nullptr)
|
||||
glfwDestroyWindow(s_Window);
|
||||
|
||||
glfwTerminate();
|
||||
return true; // Cannot fail (yet)
|
||||
}
|
||||
|
||||
return s_Windows[index];
|
||||
void GLFWManager::UpdateWindowTitleFPSInfo()
|
||||
{
|
||||
const double currentTime = glfwGetTime();
|
||||
s_FramesInTheLastSecond++;
|
||||
|
||||
if (currentTime - s_LastFPSUpdateTime > 1.0f)
|
||||
{
|
||||
s_FpsCounter = s_FramesInTheLastSecond / (currentTime - s_LastFPSUpdateTime);
|
||||
s_FramesInTheLastSecond = 0;
|
||||
s_LastFPSUpdateTime = currentTime;
|
||||
}
|
||||
|
||||
const double deltaTime = currentTime - s_LastDeltaUpdateTime;
|
||||
s_LastDeltaUpdateTime = currentTime;
|
||||
|
||||
const std::string fullTitle = s_BaseWindowTitle + '('
|
||||
+ std::to_string(s_FpsCounter) + " FPS | "
|
||||
+ std::to_string(deltaTime) + " ms)";
|
||||
|
||||
glfwSetWindowTitle(s_Window, fullTitle.c_str());
|
||||
}
|
||||
|
||||
void GLFWManager::KeyCallback(GLFWwindow* window, const int key, const int scancode, const int action, const int mode)
|
||||
{
|
||||
if (action != GLFW_PRESS)
|
||||
return;
|
||||
|
||||
switch (key)
|
||||
{
|
||||
case GLFW_KEY_F11:
|
||||
{
|
||||
s_Fullscreen = !s_Fullscreen;
|
||||
if (s_Fullscreen)
|
||||
{
|
||||
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
|
||||
const GLFWvidmode* videoMode = glfwGetVideoMode(monitor);
|
||||
|
||||
glfwGetWindowPos(window, &s_WindowedPosX, &s_WindowedPosY);
|
||||
glfwGetWindowSize(window, &s_WindowedWidth, &s_WindowedHeight);
|
||||
|
||||
glfwSetWindowMonitor(window, monitor, 0, 0, videoMode->width, videoMode->height, videoMode->refreshRate);
|
||||
return;
|
||||
}
|
||||
|
||||
glfwSetWindowMonitor(window, nullptr, s_WindowedPosX, s_WindowedPosY, s_WindowedWidth, s_WindowedHeight, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,14 +6,31 @@ namespace PB::Renderer
|
||||
{
|
||||
class GLFWManager
|
||||
{
|
||||
private:
|
||||
static std::vector<GLFWwindow*> s_Windows;
|
||||
|
||||
public:
|
||||
static bool Init();
|
||||
static GLFWwindow* Init(int width, int height, const char* title = "Unnamed window");
|
||||
__forceinline static GLFWwindow* GetWindow() { return s_Window; }
|
||||
|
||||
static bool Cleanup();
|
||||
|
||||
static GLFWwindow* CreateWindow(int width, int height, const char* title = "Unnamed window");
|
||||
static GLFWwindow* GetWindow(int index = 0);
|
||||
static __forceinline void PollEvents() { glfwPollEvents(); }
|
||||
static void UpdateWindowTitleFPSInfo();
|
||||
|
||||
private:
|
||||
static GLFWwindow* s_Window;
|
||||
|
||||
static int s_FramesInTheLastSecond;
|
||||
static int s_FpsCounter;
|
||||
static double s_LastDeltaUpdateTime;
|
||||
static double s_LastFPSUpdateTime;
|
||||
|
||||
static std::string s_BaseWindowTitle;
|
||||
|
||||
static bool s_Fullscreen;
|
||||
static int s_WindowedWidth;
|
||||
static int s_WindowedHeight;
|
||||
static int s_WindowedPosX;
|
||||
static int s_WindowedPosY;
|
||||
|
||||
static void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mode);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "../VulkanRenderer.h"
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
struct QueueFamilyIndices
|
||||
{
|
||||
std::optional<uint32_t> graphicsFamily = std::nullopt;
|
||||
std::optional<uint32_t> presentFamily = std::nullopt;
|
||||
|
||||
[[nodiscard]] bool Complete() const
|
||||
{
|
||||
return graphicsFamily && presentFamily;
|
||||
}
|
||||
};
|
||||
|
||||
struct SwapChainSupportDetails
|
||||
{
|
||||
VkSurfaceCapabilitiesKHR capabilities;
|
||||
std::vector<VkSurfaceFormatKHR> formats;
|
||||
std::vector<VkPresentModeKHR> presentModes;
|
||||
};
|
||||
|
||||
class VulkanManager
|
||||
{
|
||||
public:
|
||||
VulkanManager() = delete;
|
||||
~VulkanManager() = delete;
|
||||
|
||||
static bool InitAll(GLFWwindow* window);
|
||||
static std::optional<VkInstance> Init();
|
||||
static bool Cleanup();
|
||||
|
||||
static std::optional<VkSurfaceKHR> CreateSurface(GLFWwindow* window);
|
||||
static bool PickPhysicalDevice();
|
||||
static bool CreateLogicalDevice();
|
||||
static bool CreateSwapChain(GLFWwindow* window);
|
||||
static bool CreateImageViews();
|
||||
static bool CreateRenderPass();
|
||||
static bool CreateFramebuffer();
|
||||
static bool CreateGraphicsPipeline();
|
||||
static bool CreateCommandBuffers();
|
||||
static void CreateSemaphores();
|
||||
|
||||
static bool RenderPass(GLFWwindow* window);
|
||||
|
||||
private:
|
||||
static bool IsDeviceSuitable(VkPhysicalDevice device, VkSurfaceKHR surface);
|
||||
static QueueFamilyIndices FindQueueFamilies(VkPhysicalDevice device, VkSurfaceKHR surface);
|
||||
static bool CheckDeviceExtensionSupport(VkPhysicalDevice device);
|
||||
|
||||
static SwapChainSupportDetails QuerySwapChainSupport();
|
||||
static VkSurfaceFormatKHR ChooseSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
|
||||
static VkPresentModeKHR ChoosePresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
|
||||
static VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
|
||||
|
||||
static VkShaderModule CreateShaderModule(const std::string& filename);
|
||||
|
||||
static std::optional<VkInstance> s_Instance;
|
||||
static std::optional<VkSurfaceKHR> s_Surface;
|
||||
|
||||
static VkPhysicalDevice s_PhysicalDevice;
|
||||
static QueueFamilyIndices s_QueueIndices;
|
||||
|
||||
static VkDevice s_Device;
|
||||
|
||||
static VkQueue s_GraphicsQueue;
|
||||
static VkQueue s_PresentQueue;
|
||||
|
||||
static VkSwapchainKHR s_SwapChain;
|
||||
static std::vector<VkImage> s_SwapChainImages;
|
||||
static std::vector<VkImageView> s_SwapChainImageViews;
|
||||
static VkFormat s_SwapChainImageFormat;
|
||||
static VkExtent2D s_SwapChainExtent;
|
||||
|
||||
static VkRenderPass s_RenderPass;
|
||||
static std::vector<VkFramebuffer> s_Framebuffers;
|
||||
|
||||
static VkPipelineLayout s_PipelineLayout;
|
||||
static VkPipeline s_RenderPipeline;
|
||||
|
||||
static VkCommandPool s_CommandPool;
|
||||
static std::vector<VkCommandBuffer> s_CommandBuffers;
|
||||
|
||||
static VkSemaphore s_ImageAvailableSemaphore;
|
||||
static VkSemaphore s_RenderFinishedSemaphore;
|
||||
};
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
#include "VulkanManager.h"
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
bool VulkanManager::RenderPass(GLFWwindow* window)
|
||||
{
|
||||
uint32_t imageIndex;
|
||||
VkResult result = vkAcquireNextImageKHR(
|
||||
s_Device,
|
||||
s_SwapChain,
|
||||
UINT64_MAX,
|
||||
s_ImageAvailableSemaphore,
|
||||
VK_NULL_HANDLE,
|
||||
&imageIndex
|
||||
);
|
||||
|
||||
if (result == VK_ERROR_OUT_OF_DATE_KHR)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::RenderPass(): Failed to acquire swap chain image!" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
VkSubmitInfo submitInfo{};
|
||||
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
|
||||
VkSemaphore waitSemaphores[] = { s_ImageAvailableSemaphore };
|
||||
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
|
||||
submitInfo.waitSemaphoreCount = 1;
|
||||
submitInfo.pWaitSemaphores = waitSemaphores;
|
||||
submitInfo.pWaitDstStageMask = waitStages;
|
||||
|
||||
submitInfo.commandBufferCount = 1;
|
||||
submitInfo.pCommandBuffers = &s_CommandBuffers[imageIndex];
|
||||
|
||||
VkSemaphore signalSemaphores[] = { s_RenderFinishedSemaphore };
|
||||
submitInfo.signalSemaphoreCount = 1;
|
||||
submitInfo.pSignalSemaphores = signalSemaphores;
|
||||
|
||||
if (vkQueueSubmit(s_GraphicsQueue, 1, &submitInfo, VK_NULL_HANDLE) != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::RenderPass(): Failed to submit draw command buffer!" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
VkPresentInfoKHR presentInfo{};
|
||||
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
|
||||
presentInfo.waitSemaphoreCount = 1;
|
||||
presentInfo.pWaitSemaphores = signalSemaphores;
|
||||
|
||||
VkSwapchainKHR swapChains[] = { s_SwapChain };
|
||||
presentInfo.swapchainCount = 1;
|
||||
presentInfo.pSwapchains = swapChains;
|
||||
presentInfo.pImageIndices = &imageIndex;
|
||||
|
||||
result = vkQueuePresentKHR(s_PresentQueue, &presentInfo);
|
||||
|
||||
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
else if (result != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::RenderPass(): Failed to present swap chain image!" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
vkQueueWaitIdle(s_PresentQueue);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
201
src/managers/vulkan/VulkanManager.h
Normal file
201
src/managers/vulkan/VulkanManager.h
Normal file
@@ -0,0 +1,201 @@
|
||||
#pragma once
|
||||
|
||||
#include "../../VulkanRenderer.h"
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
struct Mesh;
|
||||
|
||||
class VulkanManager
|
||||
{
|
||||
public:
|
||||
// === Public functions === //
|
||||
|
||||
/* Static class so (de)constructors have been deleted to stop accidental creation */
|
||||
VulkanManager() = delete;
|
||||
~VulkanManager() = delete;
|
||||
|
||||
/* Shorthand for calling all the initialisation functions, returns false if any fail */
|
||||
static bool Init(GLFWwindow* window);
|
||||
|
||||
/* Frees ALL allocated Vulkan resources */
|
||||
static bool Cleanup();
|
||||
|
||||
/*
|
||||
Creates the global Vulkan instance, which connects the application to Vulkan.
|
||||
Defines the application info and imports the needed (GLFW) extensions.
|
||||
*/
|
||||
static bool CreateInstance();
|
||||
|
||||
/*
|
||||
Ties a surface to the window to present images. Abstracts platform specific code.
|
||||
Required for creating a swap chain.
|
||||
*/
|
||||
static bool CreateSurface(GLFWwindow* window);
|
||||
|
||||
/*
|
||||
Scans for all available GPUs and picks the first one that supports the necessary capabilities.
|
||||
Only looks for discrete (non-integrated) GPUs and uses that for all rendering.
|
||||
*/
|
||||
static bool PickPhysicalDevice();
|
||||
|
||||
/*
|
||||
Creates a logical device which handles the commands from Vulkan to hardware instructions.
|
||||
Also requests the queues needed.
|
||||
*/
|
||||
static bool CreateLogicalDevice();
|
||||
|
||||
/*
|
||||
Creates a swap chain with suitable image formats, present modes and image dimensions.
|
||||
The swap chain is the series of images that are displayed to the screen.
|
||||
*/
|
||||
static bool CreateSwapChain(GLFWwindow* window);
|
||||
|
||||
/*
|
||||
Each swap chain image requires a view, which describes how shaders and
|
||||
the pipeline interact with the image data.
|
||||
*/
|
||||
static bool CreateImageViews();
|
||||
|
||||
/*
|
||||
Defines the attachments (such as color and depth) and defines how they are rendered.
|
||||
Also defines the subpasses and dependencies between them.
|
||||
*/
|
||||
static bool CreateRenderPass();
|
||||
|
||||
/*
|
||||
Creates a framebuffer for each swap chain image, pairing the render pass with the relevant image.
|
||||
Each framebuffer is a specific set of attachments used drawing a render pass instance.
|
||||
*/
|
||||
static bool CreateFramebuffer();
|
||||
|
||||
/*
|
||||
Assembles shaders, fixed function state and creates the render pipeline.
|
||||
Also checks that the render pass is compatible.
|
||||
*/
|
||||
static bool CreateGraphicsPipeline();
|
||||
|
||||
/*
|
||||
Allocates a command pool and command buffers.
|
||||
The buffers represent the exact instructions the GPU will execute.
|
||||
*/
|
||||
static bool CreateCommandBuffers();
|
||||
|
||||
/*
|
||||
Creates sync between coordinate operations between different parts of the rendering.
|
||||
Required to stop race conditions between frames.
|
||||
*/
|
||||
static bool CreateSemaphores();
|
||||
|
||||
/*
|
||||
Draws a frame to the screen using the command buffers and sync objects.
|
||||
*/
|
||||
static bool RenderPass(GLFWwindow* window);
|
||||
|
||||
static void CreateNewRenderObject(Color color, const Mesh& mesh);
|
||||
|
||||
private:
|
||||
// === Internal helper structs === //
|
||||
|
||||
struct RenderObject
|
||||
{
|
||||
VkBuffer VertexBuffer{};
|
||||
VkDeviceMemory VertexBufferMemory{};
|
||||
|
||||
VkBuffer IndexBuffer{};
|
||||
VkDeviceMemory IndexBufferMemory{};
|
||||
|
||||
Color DrawColor;
|
||||
|
||||
uint32_t IndexCount{};
|
||||
};
|
||||
|
||||
struct QueueFamilyIndices
|
||||
{
|
||||
static constexpr uint32_t UNDEFINED_UINT32_VALUE = 0xFFFFFFFF;
|
||||
|
||||
uint32_t graphicsFamily = UNDEFINED_UINT32_VALUE;
|
||||
uint32_t presentFamily = UNDEFINED_UINT32_VALUE;
|
||||
|
||||
[[nodiscard]] bool Complete() const
|
||||
{
|
||||
return
|
||||
graphicsFamily != UNDEFINED_UINT32_VALUE &&
|
||||
presentFamily != UNDEFINED_UINT32_VALUE;
|
||||
}
|
||||
};
|
||||
|
||||
struct SwapChainSupportDetails
|
||||
{
|
||||
VkSurfaceCapabilitiesKHR capabilities;
|
||||
std::vector<VkSurfaceFormatKHR> formats;
|
||||
std::vector<VkPresentModeKHR> presentModes;
|
||||
};
|
||||
|
||||
struct BufferCreationInfo
|
||||
{
|
||||
VkDeviceSize size;
|
||||
VkBufferUsageFlags usage;
|
||||
VkMemoryPropertyFlags properties;
|
||||
};
|
||||
|
||||
// === Vulkan init helpers === //
|
||||
|
||||
static bool IsDeviceSuitable(VulkanHandle device);
|
||||
static QueueFamilyIndices FindQueueFamilies(VulkanHandle device);
|
||||
static bool CheckDeviceExtensionSupport(VulkanHandle device);
|
||||
|
||||
static SwapChainSupportDetails QuerySwapChainSupport();
|
||||
static VkSurfaceFormatKHR ChooseSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
|
||||
static VkPresentModeKHR ChoosePresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
|
||||
static VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
|
||||
|
||||
static VkShaderModule CreateShaderModule(const std::string& filename);
|
||||
|
||||
// === Vulkan render helpers === //
|
||||
|
||||
static VkResult RenderPassInternal();
|
||||
|
||||
static void RecreateSwapChain(GLFWwindow* window);
|
||||
static void CleanupSwapChain();
|
||||
static VkResult RecordCommandBuffer(uint32_t imageIndex);
|
||||
|
||||
static uint32_t FindMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties);
|
||||
static void CreateBuffer(VkBuffer& buffer, VkDeviceMemory& memory, const BufferCreationInfo& info);
|
||||
|
||||
// === Custom resources === //
|
||||
|
||||
static std::vector<RenderObject> s_RenderObjects;
|
||||
|
||||
// === Vulkan resources === //
|
||||
|
||||
static VkInstance s_Instance;
|
||||
static VkSurfaceKHR s_Surface;
|
||||
|
||||
static VkPhysicalDevice s_PhysicalDevice;
|
||||
static QueueFamilyIndices s_QueueIndices;
|
||||
|
||||
static VkDevice s_Device;
|
||||
|
||||
static VkQueue s_GraphicsQueue;
|
||||
static VkQueue s_PresentQueue;
|
||||
|
||||
static VkSwapchainKHR s_SwapChain;
|
||||
static std::vector<VkImage> s_SwapChainImages;
|
||||
static std::vector<VkImageView> s_SwapChainImageViews;
|
||||
static VkFormat s_SwapChainImageFormat;
|
||||
static VkExtent2D s_SwapChainExtent;
|
||||
|
||||
static VkRenderPass s_RenderPass;
|
||||
static std::vector<VkFramebuffer> s_Framebuffers;
|
||||
|
||||
static VkPipelineLayout s_PipelineLayout;
|
||||
static VkPipeline s_RenderPipeline;
|
||||
|
||||
static VkCommandPool s_CommandPool;
|
||||
static std::vector<VkCommandBuffer> s_CommandBuffers;
|
||||
|
||||
static VkSemaphore s_ImageAvailableSemaphore;
|
||||
static VkSemaphore s_RenderFinishedSemaphore;
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,36 @@
|
||||
#include "VulkanManager.h"
|
||||
|
||||
#ifdef PB_DEBUG
|
||||
|
||||
static VKAPI_ATTR VkBool32 VKAPI_CALL VulkanErrorDebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT, VkDebugUtilsMessageTypeFlagsEXT, const VkDebugUtilsMessengerCallbackDataEXT* data, void*)
|
||||
{
|
||||
static std::set<int32_t> seenErrors;
|
||||
if (seenErrors.contains(data->messageIdNumber))
|
||||
return VK_FALSE;
|
||||
|
||||
seenErrors.insert(data->messageIdNumber);
|
||||
|
||||
std::cout << "\nVULKAN ERROR [" << data->pMessageIdName << "]: \n" << data->pMessage << "\n" << std::endl;
|
||||
return VK_FALSE;
|
||||
}
|
||||
|
||||
static VkDebugUtilsMessengerEXT gDebugMessenger;
|
||||
|
||||
#endif // PB_DEBUG
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
std::optional<VkInstance> VulkanManager::s_Instance = std::nullopt;
|
||||
std::optional<VkSurfaceKHR> VulkanManager::s_Surface = std::nullopt;
|
||||
// === Custom resources === //
|
||||
|
||||
std::vector<VulkanManager::RenderObject> VulkanManager::s_RenderObjects = {};
|
||||
|
||||
// === Vulkan Resources === //
|
||||
|
||||
VkInstance VulkanManager::s_Instance = VK_NULL_HANDLE;
|
||||
VkSurfaceKHR VulkanManager::s_Surface = VK_NULL_HANDLE;
|
||||
|
||||
VkPhysicalDevice VulkanManager::s_PhysicalDevice = VK_NULL_HANDLE;
|
||||
QueueFamilyIndices VulkanManager::s_QueueIndices;
|
||||
VulkanManager::QueueFamilyIndices VulkanManager::s_QueueIndices;
|
||||
|
||||
VkDevice VulkanManager::s_Device = VK_NULL_HANDLE;
|
||||
|
||||
@@ -14,54 +38,106 @@ namespace PB::Renderer
|
||||
VkQueue VulkanManager::s_PresentQueue = VK_NULL_HANDLE;
|
||||
|
||||
VkSwapchainKHR VulkanManager::s_SwapChain = VK_NULL_HANDLE;
|
||||
std::vector<VkImage> VulkanManager::s_SwapChainImages = {};
|
||||
std::vector<VkImageView> VulkanManager::s_SwapChainImageViews = {};
|
||||
std::vector<VkImage> VulkanManager::s_SwapChainImages;
|
||||
std::vector<VkImageView> VulkanManager::s_SwapChainImageViews;
|
||||
VkFormat VulkanManager::s_SwapChainImageFormat = {};
|
||||
VkExtent2D VulkanManager::s_SwapChainExtent = {};
|
||||
VkExtent2D VulkanManager::s_SwapChainExtent;
|
||||
|
||||
VkRenderPass VulkanManager::s_RenderPass = VK_NULL_HANDLE;
|
||||
std::vector<VkFramebuffer> VulkanManager::s_Framebuffers = {};
|
||||
std::vector<VkFramebuffer> VulkanManager::s_Framebuffers;
|
||||
|
||||
VkPipelineLayout VulkanManager::s_PipelineLayout = {};
|
||||
VkPipeline VulkanManager::s_RenderPipeline = {};
|
||||
|
||||
VkCommandPool VulkanManager::s_CommandPool = VK_NULL_HANDLE;
|
||||
std::vector<VkCommandBuffer> VulkanManager::s_CommandBuffers = {};
|
||||
std::vector<VkCommandBuffer> VulkanManager::s_CommandBuffers;
|
||||
|
||||
VkSemaphore VulkanManager::s_ImageAvailableSemaphore = VK_NULL_HANDLE;
|
||||
VkSemaphore VulkanManager::s_RenderFinishedSemaphore = VK_NULL_HANDLE;
|
||||
|
||||
bool VulkanManager::InitAll(GLFWwindow* window)
|
||||
bool VulkanManager::Init(GLFWwindow* window)
|
||||
{
|
||||
if (const std::optional<VkInstance> instance = VulkanManager::Init(); !instance)
|
||||
return false;
|
||||
std::cout << "Initializing Vulkan with [" << MODE_NAME << "] profile" << std::endl;
|
||||
|
||||
if (const std::optional<VkSurfaceKHR> surface = VulkanManager::CreateSurface(window); !surface)
|
||||
return false;
|
||||
|
||||
if (!(
|
||||
VulkanManager::PickPhysicalDevice() &&
|
||||
VulkanManager::CreateLogicalDevice() &&
|
||||
VulkanManager::CreateSwapChain(window) &&
|
||||
VulkanManager::CreateImageViews() &&
|
||||
VulkanManager::CreateRenderPass() &&
|
||||
VulkanManager::CreateFramebuffer() &&
|
||||
VulkanManager::CreateGraphicsPipeline() &&
|
||||
VulkanManager::CreateCommandBuffers()
|
||||
)) {
|
||||
return false;
|
||||
return
|
||||
CreateInstance() &&
|
||||
CreateSurface(window) &&
|
||||
PickPhysicalDevice() &&
|
||||
CreateLogicalDevice() &&
|
||||
CreateSwapChain(window) &&
|
||||
CreateImageViews() &&
|
||||
CreateRenderPass() &&
|
||||
CreateFramebuffer() &&
|
||||
CreateGraphicsPipeline() &&
|
||||
CreateCommandBuffers() &&
|
||||
CreateSemaphores();
|
||||
}
|
||||
|
||||
VulkanManager::CreateSemaphores();
|
||||
bool VulkanManager::Cleanup()
|
||||
{
|
||||
for (const RenderObject& object : s_RenderObjects)
|
||||
{
|
||||
vkDestroyBuffer(s_Device, object.IndexBuffer, nullptr);
|
||||
vkDestroyBuffer(s_Device, object.VertexBuffer, nullptr);
|
||||
|
||||
vkFreeMemory(s_Device, object.IndexBufferMemory, nullptr);
|
||||
vkFreeMemory(s_Device, object.VertexBufferMemory, nullptr);
|
||||
}
|
||||
|
||||
if (s_Device != VK_NULL_HANDLE)
|
||||
vkDeviceWaitIdle(s_Device);
|
||||
|
||||
if (s_ImageAvailableSemaphore != VK_NULL_HANDLE)
|
||||
vkDestroySemaphore(s_Device, s_ImageAvailableSemaphore, nullptr);
|
||||
|
||||
if (s_RenderFinishedSemaphore != VK_NULL_HANDLE)
|
||||
vkDestroySemaphore(s_Device, s_RenderFinishedSemaphore, nullptr);
|
||||
|
||||
if (s_CommandPool != VK_NULL_HANDLE)
|
||||
vkDestroyCommandPool(s_Device, s_CommandPool, nullptr);
|
||||
|
||||
for (const VkFramebuffer& fb : s_Framebuffers)
|
||||
vkDestroyFramebuffer(s_Device, fb, nullptr);
|
||||
|
||||
if (s_RenderPipeline != VK_NULL_HANDLE)
|
||||
vkDestroyPipeline(s_Device, s_RenderPipeline, nullptr);
|
||||
|
||||
if (s_PipelineLayout != VK_NULL_HANDLE)
|
||||
vkDestroyPipelineLayout(s_Device, s_PipelineLayout, nullptr);
|
||||
|
||||
if (s_RenderPass != VK_NULL_HANDLE)
|
||||
vkDestroyRenderPass(s_Device, s_RenderPass, nullptr);
|
||||
|
||||
for (const VkImageView& view : s_SwapChainImageViews)
|
||||
vkDestroyImageView(s_Device, view, nullptr);
|
||||
|
||||
if (s_SwapChain != VK_NULL_HANDLE)
|
||||
vkDestroySwapchainKHR(s_Device, s_SwapChain, nullptr);
|
||||
|
||||
if (s_Device != VK_NULL_HANDLE)
|
||||
vkDestroyDevice(s_Device, nullptr);
|
||||
|
||||
if (s_Surface != VK_NULL_HANDLE)
|
||||
vkDestroySurfaceKHR(s_Instance, s_Surface, nullptr);
|
||||
|
||||
#ifdef PB_DEBUG
|
||||
|
||||
if (gDebugMessenger != VK_NULL_HANDLE)
|
||||
{
|
||||
if (const auto func = reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(s_Instance, "vkDestroyDebugUtilsMessengerEXT")); func != nullptr)
|
||||
func(s_Instance, gDebugMessenger, nullptr);
|
||||
}
|
||||
|
||||
#endif // PB_DEBUG
|
||||
|
||||
if (s_Instance != VK_NULL_HANDLE)
|
||||
vkDestroyInstance(s_Instance, nullptr);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<VkInstance> VulkanManager::Init()
|
||||
bool VulkanManager::CreateInstance()
|
||||
{
|
||||
/* Stops multi initialisation */
|
||||
if (s_Instance != std::nullopt)
|
||||
return s_Instance;
|
||||
|
||||
VkApplicationInfo appInfo;
|
||||
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
||||
appInfo.pNext = nullptr;
|
||||
@@ -71,75 +147,89 @@ namespace PB::Renderer
|
||||
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
|
||||
appInfo.apiVersion = VK_API_VERSION_1_3;
|
||||
|
||||
VkInstanceCreateInfo createInfo;
|
||||
VkInstanceCreateInfo createInfo{};
|
||||
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
||||
createInfo.pNext = nullptr;
|
||||
createInfo.pApplicationInfo = &appInfo;
|
||||
|
||||
if constexpr (DEBUG_MODE)
|
||||
{
|
||||
static const std::vector LAYERS =
|
||||
{
|
||||
"VK_LAYER_KHRONOS_validation",
|
||||
};
|
||||
|
||||
createInfo.enabledLayerCount = LAYERS.size();
|
||||
createInfo.ppEnabledLayerNames = LAYERS.data();
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
createInfo.enabledLayerCount = 0;
|
||||
createInfo.ppEnabledLayerNames = nullptr;
|
||||
}
|
||||
|
||||
/* Imports GLFW extensions */
|
||||
/* Imports extensions */
|
||||
uint32_t glfwExtensionCount = 0;
|
||||
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
|
||||
createInfo.enabledExtensionCount = glfwExtensionCount;
|
||||
createInfo.ppEnabledExtensionNames = glfwExtensions;
|
||||
|
||||
std::vector extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
|
||||
if constexpr (DEBUG_MODE)
|
||||
{
|
||||
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
||||
}
|
||||
|
||||
createInfo.enabledExtensionCount = extensions.size();
|
||||
createInfo.ppEnabledExtensionNames = extensions.data();
|
||||
|
||||
/* Creates the Vulkan instance */
|
||||
VkInstance instance;
|
||||
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
|
||||
if (const VkResult result = vkCreateInstance(&createInfo, nullptr, &instance); result != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::Init(): Could not create Vulkan instance" << std::endl;
|
||||
return std::nullopt;
|
||||
std::cout << "PB::Renderer::VulkanManager::Init(): Could not create Vulkan instance: [" << result << "]" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Adds a debug messenger */
|
||||
#ifdef PB_DEBUG
|
||||
|
||||
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo;
|
||||
debugCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
|
||||
debugCreateInfo.messageSeverity =
|
||||
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
|
||||
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
|
||||
debugCreateInfo.messageType =
|
||||
VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
|
||||
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
|
||||
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
|
||||
debugCreateInfo.pfnUserCallback = VulkanErrorDebugCallback;
|
||||
|
||||
if (const auto func = reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT")); func != nullptr)
|
||||
func(instance, &debugCreateInfo, nullptr, &gDebugMessenger);
|
||||
|
||||
#endif // PB_DEBUG
|
||||
|
||||
s_Instance = instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
bool VulkanManager::Cleanup()
|
||||
{
|
||||
if (s_Surface != std::nullopt)
|
||||
vkDestroySurfaceKHR(s_Instance.value(), s_Surface.value(), nullptr);
|
||||
|
||||
if (s_Instance != std::nullopt)
|
||||
vkDestroyInstance(s_Instance.value(), nullptr);
|
||||
|
||||
s_Instance = std::nullopt;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<VkSurfaceKHR> VulkanManager::CreateSurface(GLFWwindow* window)
|
||||
bool VulkanManager::CreateSurface(GLFWwindow* window)
|
||||
{
|
||||
if (s_Instance == std::nullopt)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::CreateSurface(): No Vulkan instance" << std::endl;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
VkSurfaceKHR surface;
|
||||
if (glfwCreateWindowSurface(s_Instance.value(), window, nullptr, &surface) != VK_SUCCESS)
|
||||
if (glfwCreateWindowSurface(s_Instance, window, nullptr, &surface) != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::CreateSurface(): Failed to create Vulkan Surface" << std::endl;
|
||||
return std::nullopt;
|
||||
return false;
|
||||
}
|
||||
|
||||
s_Surface = surface;
|
||||
return surface;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VulkanManager::PickPhysicalDevice()
|
||||
{
|
||||
if (s_Instance == std::nullopt || s_Surface == std::nullopt)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::PickPhysicalDevice(): No Vulkan instance or surface" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
const VkInstance& instance = s_Instance.value();
|
||||
const VkSurfaceKHR& surface = s_Surface.value();
|
||||
|
||||
uint32_t deviceCount = 0;
|
||||
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
|
||||
vkEnumeratePhysicalDevices(s_Instance, &deviceCount, nullptr);
|
||||
if (deviceCount == 0)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::PickPhysicalDevice(): No GPU with Vulkan support" << std::endl;
|
||||
@@ -147,14 +237,14 @@ namespace PB::Renderer
|
||||
}
|
||||
|
||||
std::vector<VkPhysicalDevice> devices(deviceCount);
|
||||
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
|
||||
vkEnumeratePhysicalDevices(s_Instance, &deviceCount, devices.data());
|
||||
|
||||
for (const auto& device : devices)
|
||||
{
|
||||
if (IsDeviceSuitable(device, surface))
|
||||
if (IsDeviceSuitable(device))
|
||||
{
|
||||
s_PhysicalDevice = device;
|
||||
s_QueueIndices = FindQueueFamilies(device, surface);
|
||||
s_QueueIndices = FindQueueFamilies(device);
|
||||
|
||||
VkPhysicalDeviceProperties deviceProperties;
|
||||
vkGetPhysicalDeviceProperties(device, &deviceProperties);
|
||||
@@ -169,9 +259,9 @@ namespace PB::Renderer
|
||||
return false;
|
||||
}
|
||||
|
||||
bool VulkanManager::IsDeviceSuitable(VkPhysicalDevice device, VkSurfaceKHR surface)
|
||||
bool VulkanManager::IsDeviceSuitable(VulkanHandle device)
|
||||
{
|
||||
const QueueFamilyIndices indices = FindQueueFamilies(device, surface);
|
||||
const QueueFamilyIndices indices = FindQueueFamilies(device);
|
||||
|
||||
if (const bool extensionsSupported = CheckDeviceExtensionSupport(device); !extensionsSupported)
|
||||
return false;
|
||||
@@ -179,9 +269,9 @@ namespace PB::Renderer
|
||||
VkSurfaceCapabilitiesKHR capabilities;
|
||||
uint32_t formatCount, presentCount;
|
||||
|
||||
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &capabilities);
|
||||
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentCount, nullptr);
|
||||
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, s_Surface, &capabilities);
|
||||
vkGetPhysicalDeviceSurfaceFormatsKHR(device, s_Surface, &formatCount, nullptr);
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR(device, s_Surface, &presentCount, nullptr);
|
||||
const bool swapChainAdequate = formatCount > 0 && presentCount > 0;
|
||||
|
||||
VkPhysicalDeviceProperties deviceProperties;
|
||||
@@ -191,7 +281,7 @@ namespace PB::Renderer
|
||||
return indices.Complete() && swapChainAdequate && discreteGPU;
|
||||
}
|
||||
|
||||
QueueFamilyIndices VulkanManager::FindQueueFamilies(VkPhysicalDevice device, VkSurfaceKHR surface)
|
||||
VulkanManager::QueueFamilyIndices VulkanManager::FindQueueFamilies(VulkanHandle device)
|
||||
{
|
||||
QueueFamilyIndices indices;
|
||||
|
||||
@@ -209,7 +299,7 @@ namespace PB::Renderer
|
||||
}
|
||||
|
||||
VkBool32 presentSupport = false;
|
||||
vkGetPhysicalDeviceSurfaceSupportKHR(device, index, surface, &presentSupport);
|
||||
vkGetPhysicalDeviceSurfaceSupportKHR(device, index, s_Surface, &presentSupport);
|
||||
if (presentSupport)
|
||||
{
|
||||
indices.presentFamily = index;
|
||||
@@ -226,9 +316,9 @@ namespace PB::Renderer
|
||||
return indices;
|
||||
}
|
||||
|
||||
bool VulkanManager::CheckDeviceExtensionSupport(VkPhysicalDevice device)
|
||||
bool VulkanManager::CheckDeviceExtensionSupport(VulkanHandle device)
|
||||
{
|
||||
const std::vector<const char*> REQUIRED_EXTENSIONS = {
|
||||
const std::vector REQUIRED_EXTENSIONS = {
|
||||
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
|
||||
};
|
||||
|
||||
@@ -244,15 +334,14 @@ namespace PB::Renderer
|
||||
}
|
||||
|
||||
return required.empty();
|
||||
|
||||
}
|
||||
|
||||
bool VulkanManager::CreateLogicalDevice()
|
||||
{
|
||||
std::set<uint32_t> uniqueQueueFamilies =
|
||||
std::set uniqueQueueFamilies =
|
||||
{
|
||||
s_QueueIndices.graphicsFamily.value(),
|
||||
s_QueueIndices.presentFamily.value()
|
||||
s_QueueIndices.graphicsFamily,
|
||||
s_QueueIndices.presentFamily
|
||||
};
|
||||
|
||||
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
|
||||
@@ -270,7 +359,7 @@ namespace PB::Renderer
|
||||
|
||||
VkPhysicalDeviceFeatures deviceFeatures{};
|
||||
|
||||
const std::vector<const char*> extensions = {
|
||||
const std::vector extensions = {
|
||||
VK_KHR_SWAPCHAIN_EXTENSION_NAME
|
||||
};
|
||||
|
||||
@@ -288,8 +377,8 @@ namespace PB::Renderer
|
||||
return false;
|
||||
}
|
||||
|
||||
vkGetDeviceQueue(s_Device, s_QueueIndices.graphicsFamily.value(), 0, &s_GraphicsQueue);
|
||||
vkGetDeviceQueue(s_Device, s_QueueIndices.presentFamily.value(), 0, &s_PresentQueue);
|
||||
vkGetDeviceQueue(s_Device, s_QueueIndices.graphicsFamily, 0, &s_GraphicsQueue);
|
||||
vkGetDeviceQueue(s_Device, s_QueueIndices.presentFamily, 0, &s_PresentQueue);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -308,7 +397,7 @@ namespace PB::Renderer
|
||||
|
||||
VkSwapchainCreateInfoKHR createInfo{};
|
||||
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
|
||||
createInfo.surface = s_Surface.value();
|
||||
createInfo.surface = s_Surface;
|
||||
|
||||
createInfo.minImageCount = imageCount;
|
||||
createInfo.imageFormat = format;
|
||||
@@ -319,11 +408,11 @@ namespace PB::Renderer
|
||||
|
||||
const uint32_t queueFamilyIndices[] =
|
||||
{
|
||||
s_QueueIndices.graphicsFamily.value(),
|
||||
s_QueueIndices.presentFamily.value()
|
||||
s_QueueIndices.graphicsFamily,
|
||||
s_QueueIndices.presentFamily
|
||||
};
|
||||
|
||||
if (s_QueueIndices.graphicsFamily.value() != s_QueueIndices.presentFamily.value())
|
||||
if (s_QueueIndices.graphicsFamily != s_QueueIndices.presentFamily)
|
||||
{
|
||||
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
|
||||
createInfo.queueFamilyIndexCount = 2;
|
||||
@@ -358,21 +447,20 @@ namespace PB::Renderer
|
||||
return true;
|
||||
}
|
||||
|
||||
SwapChainSupportDetails VulkanManager::QuerySwapChainSupport()
|
||||
VulkanManager::SwapChainSupportDetails VulkanManager::QuerySwapChainSupport()
|
||||
{
|
||||
SwapChainSupportDetails details;
|
||||
const VkSurfaceKHR surface = s_Surface.value();
|
||||
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(s_PhysicalDevice, surface, &details.capabilities);
|
||||
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(s_PhysicalDevice, s_Surface, &details.capabilities);
|
||||
|
||||
uint32_t formatCount;
|
||||
vkGetPhysicalDeviceSurfaceFormatsKHR(s_PhysicalDevice, surface, &formatCount, nullptr);
|
||||
vkGetPhysicalDeviceSurfaceFormatsKHR(s_PhysicalDevice, s_Surface, &formatCount, nullptr);
|
||||
details.formats.resize(formatCount);
|
||||
vkGetPhysicalDeviceSurfaceFormatsKHR(s_PhysicalDevice, surface, &formatCount, details.formats.data());
|
||||
vkGetPhysicalDeviceSurfaceFormatsKHR(s_PhysicalDevice, s_Surface, &formatCount, details.formats.data());
|
||||
|
||||
uint32_t presentModeCount;
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR(s_PhysicalDevice, surface, &presentModeCount, nullptr);
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR(s_PhysicalDevice, s_Surface, &presentModeCount, nullptr);
|
||||
details.presentModes.resize(presentModeCount);
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR(s_PhysicalDevice, surface, &presentModeCount, details.presentModes.data());
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR(s_PhysicalDevice, s_Surface, &presentModeCount, details.presentModes.data());
|
||||
|
||||
return details;
|
||||
}
|
||||
@@ -553,10 +641,30 @@ namespace PB::Renderer
|
||||
|
||||
VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
|
||||
|
||||
struct Vertex { float pos[2]; };
|
||||
|
||||
// Binding description
|
||||
VkVertexInputBindingDescription binding{};
|
||||
binding.binding = 0;
|
||||
binding.stride = sizeof(Vertex);
|
||||
binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
|
||||
|
||||
// Attribute description
|
||||
VkVertexInputAttributeDescription attribute{};
|
||||
attribute.location = 0; // matches layout(location = 0)
|
||||
attribute.binding = 0;
|
||||
attribute.format = VK_FORMAT_R32G32_SFLOAT; // vec2
|
||||
attribute.offset = offsetof(Vertex, pos);
|
||||
|
||||
VkVertexInputBindingDescription bindingDescriptions[] = { binding };
|
||||
VkVertexInputAttributeDescription attributeDescriptions[] = { attribute };
|
||||
|
||||
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
|
||||
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
|
||||
vertexInputInfo.vertexBindingDescriptionCount = 0;
|
||||
vertexInputInfo.vertexAttributeDescriptionCount = 0;
|
||||
vertexInputInfo.vertexBindingDescriptionCount = 1;
|
||||
vertexInputInfo.pVertexBindingDescriptions = bindingDescriptions;
|
||||
vertexInputInfo.vertexAttributeDescriptionCount = 1;
|
||||
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions;
|
||||
|
||||
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
|
||||
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
|
||||
@@ -598,7 +706,8 @@ namespace PB::Renderer
|
||||
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
|
||||
|
||||
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
|
||||
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT
|
||||
colorBlendAttachment.colorWriteMask =
|
||||
VK_COLOR_COMPONENT_R_BIT
|
||||
| VK_COLOR_COMPONENT_G_BIT
|
||||
| VK_COLOR_COMPONENT_B_BIT
|
||||
| VK_COLOR_COMPONENT_A_BIT;
|
||||
@@ -610,28 +719,47 @@ namespace PB::Renderer
|
||||
colorBlending.attachmentCount = 1;
|
||||
colorBlending.pAttachments = &colorBlendAttachment;
|
||||
|
||||
VkPushConstantRange range{};
|
||||
range.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
range.offset = 0;
|
||||
range.size = sizeof(Color); // TEMPORARY
|
||||
|
||||
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
|
||||
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||||
pipelineLayoutInfo.setLayoutCount = 0;
|
||||
pipelineLayoutInfo.pNext = nullptr;
|
||||
|
||||
pipelineLayoutInfo.pushConstantRangeCount = 1;
|
||||
pipelineLayoutInfo.pPushConstantRanges = ⦥
|
||||
|
||||
|
||||
if (vkCreatePipelineLayout(s_Device, &pipelineLayoutInfo, nullptr, &s_PipelineLayout) != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::VulkanManager::CreateGraphicsPipeline(): Failed to create pipeline layout\n";
|
||||
return false;
|
||||
}
|
||||
|
||||
VkGraphicsPipelineCreateInfo pipelineInfo{};
|
||||
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
|
||||
pipelineInfo.stageCount = 2;
|
||||
pipelineInfo.pStages = shaderStages;
|
||||
|
||||
pipelineInfo.pVertexInputState = &vertexInputInfo;
|
||||
pipelineInfo.pInputAssemblyState = &inputAssembly;
|
||||
pipelineInfo.pViewportState = &viewportState;
|
||||
pipelineInfo.pRasterizationState = &rasterizer;
|
||||
pipelineInfo.pMultisampleState = &multisampling;
|
||||
pipelineInfo.pColorBlendState = &colorBlending;
|
||||
|
||||
pipelineInfo.layout = s_PipelineLayout;
|
||||
pipelineInfo.renderPass = s_RenderPass;
|
||||
pipelineInfo.subpass = 0;
|
||||
|
||||
if (vkCreateGraphicsPipelines(s_Device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &s_RenderPipeline) != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::VulkanManager::CreateGraphicsPipeline(): Failed to create graphics pipeline\n";
|
||||
return false;
|
||||
}
|
||||
|
||||
vkDestroyShaderModule(s_Device, vertShaderModule, nullptr);
|
||||
vkDestroyShaderModule(s_Device, fragShaderModule, nullptr);
|
||||
@@ -651,7 +779,7 @@ namespace PB::Renderer
|
||||
const size_t fileSize = file.tellg();
|
||||
std::vector<char> buffer(fileSize);
|
||||
file.seekg(0);
|
||||
file.read(buffer.data(), fileSize);
|
||||
file.read(buffer.data(), static_cast<std::streamsize>(fileSize));
|
||||
file.close();
|
||||
|
||||
VkShaderModuleCreateInfo createInfo{};
|
||||
@@ -673,10 +801,13 @@ namespace PB::Renderer
|
||||
VkCommandPoolCreateInfo poolInfo{};
|
||||
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
|
||||
poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
|
||||
poolInfo.queueFamilyIndex = s_QueueIndices.graphicsFamily.value();
|
||||
poolInfo.queueFamilyIndex = s_QueueIndices.graphicsFamily;
|
||||
|
||||
if (vkCreateCommandPool(s_Device, &poolInfo, nullptr, &s_CommandPool) != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::CreateCommandBuffers(): Could not create command pool" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
s_CommandBuffers.resize(s_Framebuffers.size());
|
||||
|
||||
@@ -686,48 +817,32 @@ namespace PB::Renderer
|
||||
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
|
||||
allocInfo.commandBufferCount = static_cast<uint32_t>(s_CommandBuffers.size());
|
||||
|
||||
if (vkAllocateCommandBuffers(s_Device, &allocInfo, s_CommandBuffers.data()) != VK_SUCCESS) // <- Crashes here
|
||||
return false;
|
||||
|
||||
for (size_t i = 0; i < s_CommandBuffers.size(); i++)
|
||||
if (vkAllocateCommandBuffers(s_Device, &allocInfo, s_CommandBuffers.data()) != VK_SUCCESS)
|
||||
{
|
||||
VkCommandBufferBeginInfo beginInfo{};
|
||||
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
||||
|
||||
vkBeginCommandBuffer(s_CommandBuffers[i], &beginInfo);
|
||||
|
||||
VkRenderPassBeginInfo renderPassInfo{};
|
||||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
||||
renderPassInfo.renderPass = s_RenderPass;
|
||||
renderPassInfo.framebuffer = s_Framebuffers[i];
|
||||
renderPassInfo.renderArea.offset = {0, 0};
|
||||
renderPassInfo.renderArea.extent = s_SwapChainExtent;
|
||||
|
||||
VkClearValue clearColor = {0.0f, 0.0f, 0.0f, 1.0f};
|
||||
renderPassInfo.clearValueCount = 1;
|
||||
renderPassInfo.pClearValues = &clearColor;
|
||||
|
||||
vkCmdBeginRenderPass(s_CommandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
||||
|
||||
vkCmdBindPipeline(s_CommandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, s_RenderPipeline);
|
||||
|
||||
vkCmdDraw(s_CommandBuffers[i], 3, 1, 0, 0);
|
||||
|
||||
vkCmdEndRenderPass(s_CommandBuffers[i]);
|
||||
|
||||
if (vkEndCommandBuffer(s_CommandBuffers[i]) != VK_SUCCESS)
|
||||
std::cout << "PB::Renderer::VulkanManager::CreateCommandBuffers(): Could not allocate command buffers" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void VulkanManager::CreateSemaphores()
|
||||
bool VulkanManager::CreateSemaphores()
|
||||
{
|
||||
VkSemaphoreCreateInfo createInfo{};
|
||||
createInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
|
||||
|
||||
vkCreateSemaphore(s_Device, &createInfo, nullptr, &s_ImageAvailableSemaphore);
|
||||
vkCreateSemaphore(s_Device, &createInfo, nullptr, &s_RenderFinishedSemaphore);
|
||||
if (vkCreateSemaphore(s_Device, &createInfo, nullptr, &s_ImageAvailableSemaphore) != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::CreateSemaphores(): Could not create semaphore" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (vkCreateSemaphore(s_Device, &createInfo, nullptr, &s_RenderFinishedSemaphore) != VK_SUCCESS)
|
||||
{
|
||||
std::cout << "PB::Renderer::VulkanManager::CreateSemaphores(): Could not create semaphore" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
236
src/managers/vulkan/VulkanManagerRender.cpp
Normal file
236
src/managers/vulkan/VulkanManagerRender.cpp
Normal file
@@ -0,0 +1,236 @@
|
||||
#include "VulkanManager.h"
|
||||
#include "../../Mesh.h"
|
||||
|
||||
#define CHECK_RESULT(res) if (res != VK_SUCCESS) { return res; }
|
||||
|
||||
namespace PB::Renderer
|
||||
{
|
||||
bool VulkanManager::RenderPass(GLFWwindow* window)
|
||||
{
|
||||
switch (const VkResult result = RenderPassInternal())
|
||||
{
|
||||
case VK_ERROR_OUT_OF_DATE_KHR:
|
||||
case VK_SUBOPTIMAL_KHR:
|
||||
RecreateSwapChain(window);
|
||||
return true;
|
||||
|
||||
default:
|
||||
return result == VK_SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
void VulkanManager::CreateNewRenderObject(const Color color, const Mesh& mesh)
|
||||
{
|
||||
RenderObject obj{};
|
||||
obj.IndexCount = mesh.indices.size();
|
||||
obj.DrawColor = color;
|
||||
|
||||
BufferCreationInfo vertexCreationInfo{};
|
||||
vertexCreationInfo.size = mesh.vertices.size() * sizeof(float);;
|
||||
vertexCreationInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
|
||||
vertexCreationInfo.properties = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
|
||||
CreateBuffer(obj.VertexBuffer, obj.VertexBufferMemory, vertexCreationInfo);
|
||||
|
||||
void* data;
|
||||
vkMapMemory(s_Device, obj.VertexBufferMemory, 0, mesh.vertices.size() * sizeof(float), 0, &data);
|
||||
std::memcpy(data, mesh.vertices.data(), mesh.vertices.size() * sizeof(float));
|
||||
vkUnmapMemory(s_Device, obj.VertexBufferMemory);
|
||||
|
||||
BufferCreationInfo indexCreationInfo{};
|
||||
indexCreationInfo.size = mesh.indices.size() * sizeof(uint32_t);
|
||||
indexCreationInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
|
||||
indexCreationInfo.properties = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
|
||||
CreateBuffer(obj.IndexBuffer, obj.IndexBufferMemory, indexCreationInfo);
|
||||
|
||||
vkMapMemory(s_Device, obj.IndexBufferMemory, 0, mesh.indices.size() * sizeof(uint32_t), 0, &data);
|
||||
std::memcpy(data, mesh.indices.data(), mesh.indices.size() * sizeof(uint32_t));
|
||||
vkUnmapMemory(s_Device, obj.IndexBufferMemory);
|
||||
|
||||
s_RenderObjects.push_back(obj);
|
||||
}
|
||||
|
||||
void VulkanManager::RecreateSwapChain(GLFWwindow* window)
|
||||
{
|
||||
int width, height;
|
||||
glfwGetFramebufferSize(window, &width, &height);
|
||||
|
||||
/* Pauses if minimised */
|
||||
while (width == 0 || height == 0)
|
||||
{
|
||||
glfwGetFramebufferSize(window, &width, &height);
|
||||
glfwWaitEvents();
|
||||
}
|
||||
|
||||
/* Waits until device is idle before recreating swap chain */
|
||||
vkDeviceWaitIdle(s_Device);
|
||||
CleanupSwapChain();
|
||||
|
||||
CreateSwapChain(window);
|
||||
CreateImageViews();
|
||||
CreateRenderPass();
|
||||
CreateFramebuffer();
|
||||
CreateGraphicsPipeline();
|
||||
CreateCommandBuffers();
|
||||
CreateSemaphores();
|
||||
}
|
||||
|
||||
void VulkanManager::CleanupSwapChain()
|
||||
{
|
||||
for (const VkFramebuffer& framebuffer : s_Framebuffers)
|
||||
{
|
||||
vkDestroyFramebuffer(s_Device, framebuffer, nullptr);
|
||||
}
|
||||
s_Framebuffers.clear();
|
||||
|
||||
vkFreeCommandBuffers(s_Device, s_CommandPool, static_cast<uint32_t>(s_CommandBuffers.size()), s_CommandBuffers.data());
|
||||
vkDestroyPipeline(s_Device, s_RenderPipeline, nullptr);
|
||||
vkDestroyPipelineLayout(s_Device, s_PipelineLayout, nullptr);
|
||||
vkDestroyRenderPass(s_Device, s_RenderPass, nullptr);
|
||||
|
||||
for (const VkImageView& view : s_SwapChainImageViews)
|
||||
{
|
||||
vkDestroyImageView(s_Device, view, nullptr);
|
||||
}
|
||||
|
||||
vkDestroySwapchainKHR(s_Device, s_SwapChain, nullptr);
|
||||
}
|
||||
|
||||
VkResult VulkanManager::RecordCommandBuffer(const uint32_t imageIndex)
|
||||
{
|
||||
VkResult result = VK_SUCCESS;
|
||||
|
||||
const VkCommandBuffer& cmd = s_CommandBuffers[imageIndex];
|
||||
VkCommandBufferBeginInfo beginInfo{};
|
||||
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
||||
beginInfo.flags = 0;
|
||||
beginInfo.pInheritanceInfo = nullptr;
|
||||
|
||||
result = vkBeginCommandBuffer(cmd, &beginInfo);
|
||||
CHECK_RESULT(result);
|
||||
|
||||
VkRenderPassBeginInfo renderPassInfo{};
|
||||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
||||
renderPassInfo.renderPass = s_RenderPass;
|
||||
renderPassInfo.framebuffer = s_Framebuffers[imageIndex];
|
||||
renderPassInfo.renderArea.offset = { 0, 0 };
|
||||
renderPassInfo.renderArea.extent = s_SwapChainExtent;
|
||||
|
||||
VkClearValue clearValue[2];
|
||||
clearValue[0].color = { 0.0f, 0.0f, 0.0f, 1.0f };
|
||||
clearValue[1].depthStencil = { 1.0f, 0 };
|
||||
|
||||
renderPassInfo.clearValueCount = 2;
|
||||
renderPassInfo.pClearValues = clearValue;
|
||||
|
||||
vkCmdBeginRenderPass(cmd, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, s_RenderPipeline);
|
||||
|
||||
for (const auto& renderObject : s_RenderObjects)
|
||||
{
|
||||
VkBuffer vertexBuffer = { renderObject.VertexBuffer };
|
||||
constexpr VkDeviceSize offsets[] = { 0 };
|
||||
|
||||
vkCmdBindVertexBuffers(cmd, 0, 1, &vertexBuffer, offsets);
|
||||
vkCmdBindIndexBuffer(cmd, renderObject.IndexBuffer, 0, VK_INDEX_TYPE_UINT32);
|
||||
vkCmdPushConstants(cmd, s_PipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(Color), &renderObject.DrawColor);
|
||||
|
||||
vkCmdDrawIndexed(cmd, renderObject.IndexCount, 1, 0, 0, 0);
|
||||
}
|
||||
|
||||
vkCmdEndRenderPass(cmd);
|
||||
result = vkEndCommandBuffer(cmd);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
VkResult VulkanManager::RenderPassInternal()
|
||||
{
|
||||
uint32_t imageIndex;
|
||||
VkResult result = vkAcquireNextImageKHR(
|
||||
s_Device,
|
||||
s_SwapChain,
|
||||
UINT64_MAX,
|
||||
s_ImageAvailableSemaphore,
|
||||
VK_NULL_HANDLE,
|
||||
&imageIndex
|
||||
);
|
||||
CHECK_RESULT(result);
|
||||
|
||||
result = RecordCommandBuffer(imageIndex);
|
||||
CHECK_RESULT(result);
|
||||
|
||||
VkSubmitInfo submitInfo{};
|
||||
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
|
||||
const VkSemaphore waitSemaphores[] = { s_ImageAvailableSemaphore };
|
||||
constexpr VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
|
||||
submitInfo.waitSemaphoreCount = 1;
|
||||
submitInfo.pWaitSemaphores = waitSemaphores;
|
||||
submitInfo.pWaitDstStageMask = waitStages;
|
||||
|
||||
submitInfo.commandBufferCount = 1;
|
||||
submitInfo.pCommandBuffers = &s_CommandBuffers[imageIndex];
|
||||
|
||||
const VkSemaphore signalSemaphores[] = { s_RenderFinishedSemaphore };
|
||||
submitInfo.signalSemaphoreCount = 1;
|
||||
submitInfo.pSignalSemaphores = signalSemaphores;
|
||||
|
||||
result = vkQueueSubmit(s_GraphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
|
||||
CHECK_RESULT(result);
|
||||
|
||||
VkPresentInfoKHR presentInfo{};
|
||||
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
|
||||
presentInfo.waitSemaphoreCount = 1;
|
||||
presentInfo.pWaitSemaphores = signalSemaphores;
|
||||
|
||||
const VkSwapchainKHR swapChains[] = { s_SwapChain };
|
||||
presentInfo.swapchainCount = 1;
|
||||
presentInfo.pSwapchains = swapChains;
|
||||
presentInfo.pImageIndices = &imageIndex;
|
||||
|
||||
result = vkQueuePresentKHR(s_PresentQueue, &presentInfo);
|
||||
CHECK_RESULT(result);
|
||||
|
||||
vkQueueWaitIdle(s_PresentQueue);
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
uint32_t VulkanManager::FindMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties)
|
||||
{
|
||||
VkPhysicalDeviceMemoryProperties memProperties;
|
||||
vkGetPhysicalDeviceMemoryProperties(s_PhysicalDevice, &memProperties);
|
||||
|
||||
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
|
||||
{
|
||||
bool typeSupported = (typeFilter & (1 << i)) != 0;
|
||||
bool hasProperties = (memProperties.memoryTypes[i].propertyFlags & properties) == properties;
|
||||
|
||||
if (typeSupported && hasProperties)
|
||||
return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
void VulkanManager::CreateBuffer(VkBuffer& buffer, VkDeviceMemory& memory, const BufferCreationInfo& info)
|
||||
{
|
||||
VkBufferCreateInfo bufferInfo{};
|
||||
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
bufferInfo.size = info.size;
|
||||
bufferInfo.usage = info.usage;
|
||||
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
|
||||
vkCreateBuffer(s_Device, &bufferInfo, nullptr, &buffer);
|
||||
|
||||
VkMemoryRequirements memRequirements;
|
||||
vkGetBufferMemoryRequirements(s_Device, buffer, &memRequirements);
|
||||
|
||||
VkMemoryAllocateInfo allocInfo{};
|
||||
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
allocInfo.allocationSize = memRequirements.size;
|
||||
allocInfo.memoryTypeIndex = FindMemoryType(memRequirements.memoryTypeBits, info.properties);
|
||||
|
||||
vkAllocateMemory(s_Device, &allocInfo, nullptr, &memory);
|
||||
vkBindBufferMemory(s_Device, buffer, memory, 0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user