From d6907f0503ae88482d08fe4c040040215847de7f Mon Sep 17 00:00:00 2001 From: Anish Bhobe Date: Wed, 2 Jul 2025 15:45:56 +0200 Subject: [PATCH] clean: Mass renames, format, fixed scheme. --- .clang-format | 6 +- Blaze.sln.DotSettings | 29 +- Blaze/Blaze.vcxproj | 2 - Blaze/Source/AppState.cpp | 79 ++-- Blaze/Source/AppState.h | 24 +- Blaze/Source/Blaze.cpp | 308 +++++++------- Blaze/Source/BufferManager.cpp | 234 ++++++----- Blaze/Source/BufferManager.h | 69 +-- Blaze/Source/CgltfImpl.cpp | 2 +- Blaze/Source/EntityManager.cpp | 101 +++-- Blaze/Source/EntityManager.h | 53 ++- Blaze/Source/Frame.cpp | 146 +++---- Blaze/Source/Frame.h | 39 +- Blaze/Source/FreeList.cpp | 65 +-- Blaze/Source/FreeList.h | 22 +- Blaze/Source/GlobalMemory.cpp | 53 +-- Blaze/Source/GlobalMemory.h | 29 +- Blaze/Source/MathUtil.h | 11 - Blaze/Source/MiscData.cpp | 314 +++++++------- Blaze/Source/MiscData.h | 13 +- Blaze/Source/ModelLoader.cpp | 714 ++++++++++++++++---------------- Blaze/Source/ModelLoader.h | 33 +- Blaze/Source/RID.cpp | 0 Blaze/Source/RID.h | 7 +- Blaze/Source/RenderDevice.cpp | 422 ++++++++++--------- Blaze/Source/RenderDevice.h | 54 ++- Blaze/Source/TextureManager.cpp | 231 +++++------ Blaze/Source/TextureManager.h | 68 +-- 28 files changed, 1585 insertions(+), 1543 deletions(-) delete mode 100644 Blaze/Source/MathUtil.h delete mode 100644 Blaze/Source/RID.cpp diff --git a/.clang-format b/.clang-format index 6f1b1fc..5d13640 100644 --- a/.clang-format +++ b/.clang-format @@ -21,6 +21,7 @@ AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakTemplateDeclarations: Yes BinPackArguments: false BinPackParameters: false +PackConstructorInitializers: CurrentLine BraceWrapping: AfterCaseLabel: true AfterClass: true @@ -42,7 +43,8 @@ BraceWrapping: SplitEmptyNamespace: false BreakConstructorInitializers: BeforeComma ConstructorInitializerIndentWidth: 2 -Cpp11BracedListStyle: false +ContinuationIndentWidth: 2 +Cpp11BracedListStyle: true IncludeCategories: - Regex: ^<.* Priority: 1 @@ -70,4 +72,4 @@ ConstructorInitializerAllOnOneLineOrOnePerLine: true SpaceInEmptyParentheses: false SpacesInConditionalStatement: true SpacesInCStyleCastParentheses: false -AlignArrayOfStructures: Right \ No newline at end of file +AlignArrayOfStructures: Left \ No newline at end of file diff --git a/Blaze.sln.DotSettings b/Blaze.sln.DotSettings index 6b6b4b5..edc32da 100644 --- a/Blaze.sln.DotSettings +++ b/Blaze.sln.DotSettings @@ -1,4 +1,27 @@  - <NamingElement Priority="10"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="member function" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="" Style="aa_bb" /></Policy></NamingElement> - <NamingElement Priority="7"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="local variable" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></NamingElement> - <NamingElement Priority="6"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="function parameter" /><type Name="lambda parameter" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></NamingElement> \ No newline at end of file + True + FromPath + ID + <NamingElement Priority="11"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="class field" /><type Name="struct field" /></Descriptor><Policy Inspect="True" Prefix="m_" Suffix="" Style="aaBb" /></NamingElement> + <NamingElement Priority="10"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="member function" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="" Suffix="" Style="aa_bb" /></Policy></NamingElement> + <NamingElement Priority="12"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="PUBLIC"><type Name="class field" /><type Name="struct field" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></NamingElement> + <NamingElement Priority="1"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="__interface" /><type Name="class" /><type Name="enum" /><type Name="struct" /><type Name="union" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></NamingElement> + <NamingElement Priority="2"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE" /><Policy Inspect="True" Prefix="" Suffix="" Style="aa_bb" /></NamingElement> + <NamingElement Priority="14"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="scoped enumerator" /><type Name="unscoped enumerator" /></Descriptor><Policy Inspect="True" Prefix="k" Suffix="" Style="AaBb" /></NamingElement> + <NamingElement Priority="3"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="enum" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></NamingElement> + <NamingElement Priority="16"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="True" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="global variable" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AA_BB" /></NamingElement> + <NamingElement Priority="9"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="global function" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></NamingElement> + <NamingElement Priority="8"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="global variable" /></Descriptor><Policy Inspect="True" Prefix="g_" Suffix="" Style="AaBb" /></NamingElement> + + <NamingElement Priority="19"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="macro" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="" Suffix="" Style="AA_BB" /></Policy></NamingElement> + <NamingElement Priority="17"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="namespace" /><type Name="namespace alias" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></NamingElement> + <NamingElement Priority="15"><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" Prefix="k" Suffix="" Style="AaBb" /></NamingElement> + + <NamingElement Priority="18"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="type alias" /><type Name="typedef" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="" Suffix="" Style="aa_bb" /></Policy></NamingElement> + <NamingElement Priority="13"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="union member" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></NamingElement> + <NamingElement Priority="4"><Descriptor Static="Indeterminate" Constexpr="Indeterminate" Const="Indeterminate" Volatile="Indeterminate" Accessibility="NOT_APPLICABLE"><type Name="union" /></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></NamingElement> + True + C:\Users\Eon\source\repos\Blaze\Blaze.sln.DotSettings + + True + 1 \ No newline at end of file diff --git a/Blaze/Blaze.vcxproj b/Blaze/Blaze.vcxproj index 4f798be..710debe 100644 --- a/Blaze/Blaze.vcxproj +++ b/Blaze/Blaze.vcxproj @@ -202,7 +202,6 @@ - @@ -219,7 +218,6 @@ - diff --git a/Blaze/Source/AppState.cpp b/Blaze/Source/AppState.cpp index 42e3638..25cc869 100644 --- a/Blaze/Source/AppState.cpp +++ b/Blaze/Source/AppState.cpp @@ -8,80 +8,73 @@ #include "RenderDevice.h" #include "TextureManager.h" -bool AppState::isInit() const +namespace Blaze { - return window and renderDevice and renderDevice->isInit(); + +bool AppState::IsInit() const +{ + return window and renderDevice and renderDevice->IsInit(); } -void AppState::destroy() +void AppState::Destroy() { - if ( !isInit() ) return; + if ( !IsInit() ) return; - renderDevice->waitIdle(); + renderDevice->WaitIdle(); - Take( miscData )->destroy( *renderDevice ); + Take( miscData )->Destroy( *renderDevice ); - Take( entityManager )->destroy(); + Take( entityManager )->Destroy(); - Take( renderDevice )->destroy(); + Take( renderDevice )->Destroy(); SDL_DestroyWindow( Take( window ) ); } -AppState::AppState( SDL_Window* window, RenderDevice* renderDevice, EntityManager* entityManager, MiscData* miscData ) +AppState::AppState( + SDL_Window* window, RenderDevice* render_device, EntityManager* entity_manager, MiscData* misc_data ) : window{ window } - , renderDevice{ renderDevice } - , entityManager{ entityManager } - , miscData{ miscData } + , renderDevice{ render_device } + , entityManager{ entity_manager } + , miscData{ misc_data } , sprintfBuffer{ 0 } {} -AppState* AppState_Create( GlobalMemory* memory, uint32_t const width, uint32_t const height ) +AppState* AppState::Create( GlobalMemory* memory, uint32_t width, uint32_t height ) { SDL_Window* window = - SDL_CreateWindow( "Blaze Test", static_cast( width ), static_cast( height ), SDL_WINDOW_VULKAN ); - if ( !window ) - { - SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "%s", SDL_GetError() ); - return nullptr; - } + SDL_CreateWindow( "Blaze Test", static_cast( width ), static_cast( height ), SDL_WINDOW_VULKAN ); + ASSERT( window ); - RenderDevice* renderDevice = RenderDevice_Create( memory, { .window = window } ); - if ( !renderDevice or !renderDevice->isInit() ) - { - SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "RenderDevice failed to init" ); - SDL_DestroyWindow( window ); - return nullptr; - } + RenderDevice* render_device = RenderDevice::Create( memory, { .window = window } ); + ASSERT( render_device ); - EntityManager* entityManager = EntityManager_Create( memory, renderDevice, 1000 ); - if ( !entityManager ) - { - SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "EntityManager failed to init" ); - renderDevice->destroy(); - SDL_DestroyWindow( window ); - return nullptr; - } + EntityManager* entity_manager = EntityManager::Create( memory, render_device, 1000 ); + ASSERT( entity_manager ); - auto* miscDataAllocation = memory->allocate( sizeof( MiscData ) ); + byte* misc_data_allocation = memory->Allocate( sizeof( MiscData ) ); - MiscData* miscData = new ( miscDataAllocation ) MiscData{}; - if ( !miscData->init( *renderDevice ) ) + MiscData* misc_data = new ( misc_data_allocation ) MiscData{}; + if ( !misc_data->Init( *render_device ) ) { SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "MiscData failed to init" ); - entityManager->destroy(); - renderDevice->destroy(); + entity_manager->Destroy(); + render_device->Destroy(); SDL_DestroyWindow( window ); + ASSERT( false ); return nullptr; } - auto* allocation = memory->allocate( sizeof( AppState ) ); - AppState* appState = new ( allocation ) AppState{ window, renderDevice, entityManager, miscData }; + byte* allocation = memory->Allocate( sizeof( AppState ) ); + AppState* app_state = new ( allocation ) AppState{ window, render_device, entity_manager, misc_data }; - return appState; + return app_state; } +#if defined( DTOR_TEST ) AppState::~AppState() { - ASSERT( not isInit() ); + ASSERT( not IsInit() ); } +#endif +} // namespace Blaze diff --git a/Blaze/Source/AppState.h b/Blaze/Source/AppState.h index 1e99e08..acff008 100644 --- a/Blaze/Source/AppState.h +++ b/Blaze/Source/AppState.h @@ -2,14 +2,16 @@ #include - +// ReSharper disable once CppInconsistentNaming struct SDL_Window; +namespace Blaze +{ + struct GlobalMemory; +struct MiscData; struct RenderDevice; struct EntityManager; -struct TextureManager; -struct MiscData; struct AppState { @@ -19,18 +21,16 @@ struct AppState MiscData* miscData; char sprintfBuffer[256]; - [[nodiscard]] bool isInit() const; - void destroy(); + [[nodiscard]] bool IsInit() const; - AppState( SDL_Window* window, RenderDevice* renderDevice, EntityManager* entityManager, MiscData* miscData ); + static AppState* Create( GlobalMemory* memory, uint32_t width, uint32_t height ); + void Destroy(); - AppState( AppState const& other ) = delete; - AppState( AppState&& other ) noexcept = delete; - - AppState& operator=( AppState const& other ) = delete; - AppState& operator=( AppState&& other ) noexcept = delete; + AppState( SDL_Window* window, RenderDevice* render_device, EntityManager* entity_manager, MiscData* misc_data ); +#if defined( DTOR_TEST ) ~AppState(); +#endif }; -AppState* AppState_Create( GlobalMemory* memory, uint32_t width, uint32_t height ); +} // namespace Blaze diff --git a/Blaze/Source/Blaze.cpp b/Blaze/Source/Blaze.cpp index ac0cb89..9c338f2 100644 --- a/Blaze/Source/Blaze.cpp +++ b/Blaze/Source/Blaze.cpp @@ -9,7 +9,6 @@ #define SDL_MAIN_USE_CALLBACKS 1 #include -#include #include #include @@ -20,7 +19,6 @@ #include "Frame.h" #include "GlobalMemory.h" #include "MacroUtils.h" -#include "MathUtil.h" #include "MiscData.h" #include "RenderDevice.h" @@ -35,189 +33,193 @@ namespace Blaze::Global GlobalMemory g_Memory; } +// ReSharper disable once CppInconsistentNaming SDL_AppResult SDL_AppInit( void** appstate, int, char** ) { SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ); - Blaze::Global::g_Memory.init( 128_MiB ); + using Blaze::operator""_MiB; - *appstate = AppState_Create( &Blaze::Global::g_Memory, WIDTH, HEIGHT ); + Blaze::Global::g_Memory.Initialize( 128_MiB ); + + *appstate = Blaze::AppState::Create( &Blaze::Global::g_Memory, WIDTH, HEIGHT ); if ( !*appstate ) return SDL_APP_FAILURE; - AppState& appState = *static_cast( *appstate ); + Blaze::AppState const& app_state = *static_cast( *appstate ); - Entity const* entity = LoadModel( appState.renderDevice, appState.entityManager, "Assets/Models/DamagedHelmet.glb" ); + Blaze::Entity const* entity = + LoadModel( app_state.renderDevice, app_state.entityManager, "Assets/Models/DamagedHelmet.glb" ); ASSERT( entity ); - std::array pointLight = { - MiscData::PointLight{ - .position = { 12.0f, 0.0f, 0.0f }, - .range = 12, - .color = { 1.0f, 0.0f, 0.0f }, - .attenuation = 1.0f, - }, - MiscData::PointLight{ - .position = { 0.0f, 3.0f, 0.0f }, - .range = 12, - .color = { 12.0f, 12.0f, 12.0f }, - .attenuation = 1.0f, - }, - MiscData::PointLight{ - .position = { 0.0f, 0.0f, -12.0f }, - .range = 6, - .color = { 0.0f, 0.0f, 1.0f }, - .attenuation = 1.0f, - }, + Blaze::MiscData::PointLight point_light[] = { + { + .position = { 12.0f, 0.0f, 0.0f }, + .range = 12, + .color = { 1.0f, 0.0f, 0.0f }, + .attenuation = 1.0f, + }, + { + .position = { 0.0f, 3.0f, 0.0f }, + .range = 12, + .color = { 12.0f, 12.0f, 12.0f }, + .attenuation = 1.0f, + }, + { + .position = { 0.0f, 0.0f, -12.0f }, + .range = 6, + .color = { 0.0f, 0.0f, 1.0f }, + .attenuation = 1.0f, + }, }; - appState.miscData->lightData.pointLightCount = static_cast( pointLight.size() ); + app_state.miscData->lightData.pointLightCount = _countof( point_light ); - appState.renderDevice->bufferManager->writeToBuffer( - appState.miscData->pointLights, std::span{ pointLight.begin(), pointLight.end() } ); + app_state.renderDevice->bufferManager->WriteToBuffer( app_state.miscData->pointLights, point_light ); memcpy( - appState.miscData->cameraUniformBufferPtr + sizeof( MiscData::CameraData ), - &appState.miscData->lightData, - sizeof appState.miscData->lightData ); + app_state.miscData->cameraUniformBufferPtr + sizeof( Blaze::MiscData::CameraData ), + &app_state.miscData->lightData, + sizeof app_state.miscData->lightData ); return SDL_APP_CONTINUE; } +// ReSharper disable once CppInconsistentNaming SDL_AppResult SDL_AppIterate( void* appstate ) { - AppState& appState = *static_cast( appstate ); - RenderDevice& renderDevice = *appState.renderDevice; - EntityManager& entityManager = *appState.entityManager; - MiscData& misc = *appState.miscData; - Frame& currentFrame = renderDevice.frames[renderDevice.frameIndex]; + Blaze::AppState& app_state = *static_cast( appstate ); + Blaze::RenderDevice& render_device = *app_state.renderDevice; + Blaze::EntityManager& entity_manager = *app_state.entityManager; + Blaze::MiscData& misc = *app_state.miscData; + Blaze::Frame& current_frame = render_device.frames[render_device.frameIndex]; - VK_CHECK( vkWaitForFences( renderDevice.device, 1, ¤tFrame.frameReadyToReuse, VK_TRUE, UINT32_MAX ) ); + VK_CHECK( vkWaitForFences( render_device.device, 1, ¤t_frame.frameReadyToReuse, VK_TRUE, UINT32_MAX ) ); // All resources of frame 'frameIndex' are free. // time calc - uint64_t const previousCounter = misc.previousCounter; - uint64_t const currentCounter = SDL_GetPerformanceCounter(); - uint64_t const deltaCount = currentCounter - previousCounter; - uint64_t const perfFreq = SDL_GetPerformanceFrequency(); - double const deltaTime = static_cast( deltaCount ) / static_cast( perfFreq ); - misc.previousCounter = currentCounter; + uint64_t const previous_counter = misc.previousCounter; + uint64_t const current_counter = SDL_GetPerformanceCounter(); + uint64_t const delta_count = current_counter - previous_counter; + uint64_t const perf_freq = SDL_GetPerformanceFrequency(); + double const delta_time = static_cast( delta_count ) / static_cast( perf_freq ); + misc.previousCounter = current_counter; { misc.frameTimeSum -= misc.frameTime[misc.frameTimeWriteHead]; - misc.frameTime[misc.frameTimeWriteHead] = deltaTime; - misc.frameTimeSum += deltaTime; + misc.frameTime[misc.frameTimeWriteHead] = delta_time; + misc.frameTimeSum += delta_time; misc.frameTimeWriteHead = ( misc.frameTimeWriteHead + 1 ) % misc.frameTimeEntryCount; - double avgDeltaTime = ( misc.frameTimeSum / misc.frameTimeEntryCount ); - double fps = 1.0 / avgDeltaTime; - double avgDeltaTimeMs = 1000.0 * avgDeltaTime; - ( void )sprintf_s<256>( appState.sprintfBuffer, "%.2f fps %.2f ms", fps, avgDeltaTimeMs ); - SDL_SetWindowTitle( appState.window, appState.sprintfBuffer ); + double avg_delta_time = ( misc.frameTimeSum / misc.frameTimeEntryCount ); + double fps = 1.0 / avg_delta_time; + double avg_delta_time_ms = 1000.0 * avg_delta_time; + ( void )sprintf_s<256>( app_state.sprintfBuffer, "%.2f fps %.2f ms", fps, avg_delta_time_ms ); + SDL_SetWindowTitle( app_state.window, app_state.sprintfBuffer ); } - for ( Entity& entity : entityManager.iter() ) + for ( Blaze::Entity& entity : entity_manager.Iterate() ) { - if ( not entity.isRoot() ) continue; + if ( not entity.IsRoot() ) continue; entity.transform.rotation = DirectX::XMQuaternionMultiply( - DirectX::XMQuaternionRotationAxis( - DirectX::XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ), - DirectX::XMConvertToRadians( 60.0f ) * static_cast( deltaTime ) ), - entity.transform.rotation ); + DirectX::XMQuaternionRotationAxis( + DirectX::XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ), + DirectX::XMConvertToRadians( 60.0f ) * static_cast( delta_time ) ), + entity.transform.rotation ); } - uint32_t currentImageIndex; + uint32_t current_image_index; VK_CHECK( vkAcquireNextImageKHR( - renderDevice.device, - renderDevice.swapchain, - std::numeric_limits::max(), - currentFrame.imageAcquiredSemaphore, - nullptr, - ¤tImageIndex ) ); + render_device.device, + render_device.swapchain, + std::numeric_limits::max(), + current_frame.imageAcquiredSemaphore, + nullptr, + ¤t_image_index ) ); // TODO: Resize Swapchain if required. - VK_CHECK( vkResetFences( renderDevice.device, 1, ¤tFrame.frameReadyToReuse ) ); - VK_CHECK( vkResetCommandPool( renderDevice.device, currentFrame.commandPool, 0 ) ); + VK_CHECK( vkResetFences( render_device.device, 1, ¤t_frame.frameReadyToReuse ) ); + VK_CHECK( vkResetCommandPool( render_device.device, current_frame.commandPool, 0 ) ); - misc.acquireToRenderBarrier.image = renderDevice.swapchainImages[currentImageIndex]; - misc.renderToPresentBarrier.image = renderDevice.swapchainImages[currentImageIndex]; + misc.acquireToRenderBarrier.image = render_device.swapchainImages[current_image_index]; + misc.renderToPresentBarrier.image = render_device.swapchainImages[current_image_index]; - VkCommandBuffer cmd = currentFrame.commandBuffer; + VkCommandBuffer cmd = current_frame.commandBuffer; - VkCommandBufferBeginInfo constexpr beginInfo = { + VkCommandBufferBeginInfo constexpr begin_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .pNext = nullptr, .flags = 0, .pInheritanceInfo = nullptr, }; - VkClearColorValue constexpr static BLACK_CLEAR = { + VkClearColorValue constexpr static kBlackClear = { .float32 = { 0.0f, 0.0f, 0.0f, 1.0f }, }; - VkClearDepthStencilValue constexpr static DEPTH_STENCIL_CLEAR = { + VkClearDepthStencilValue constexpr static kDepthStencilClear = { .depth = 1.0f, .stencil = 0, }; - VK_CHECK( vkBeginCommandBuffer( cmd, &beginInfo ) ); + VK_CHECK( vkBeginCommandBuffer( cmd, &begin_info ) ); { - VkRenderingAttachmentInfo const depthAttachmentInfo = { + VkRenderingAttachmentInfo const depth_attachment_info = { .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, .pNext = nullptr, - .imageView = currentFrame.depthView, + .imageView = current_frame.depthView, .imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, .resolveMode = VK_RESOLVE_MODE_NONE, .resolveImageView = nullptr, .resolveImageLayout = VK_IMAGE_LAYOUT_UNDEFINED, .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .clearValue = { .depthStencil = DEPTH_STENCIL_CLEAR }, + .clearValue = { .depthStencil = kDepthStencilClear }, }; - VkRenderingAttachmentInfo const attachmentInfo = { + VkRenderingAttachmentInfo const attachment_info = { .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, .pNext = nullptr, - .imageView = renderDevice.swapchainViews[currentImageIndex], + .imageView = render_device.swapchainViews[current_image_index], .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, .resolveMode = VK_RESOLVE_MODE_NONE, .resolveImageView = nullptr, .resolveImageLayout = VK_IMAGE_LAYOUT_UNDEFINED, .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .clearValue = { .color = BLACK_CLEAR }, + .clearValue = { .color = kBlackClear }, }; - VkRenderingInfo renderingInfo = { + VkRenderingInfo rendering_info = { .sType = VK_STRUCTURE_TYPE_RENDERING_INFO, .pNext = nullptr, .flags = 0, - .renderArea = { .offset = { 0, 0 }, .extent = renderDevice.swapchainExtent }, + .renderArea = { .offset = { 0, 0 }, .extent = render_device.swapchainExtent }, .layerCount = 1, .viewMask = 0, .colorAttachmentCount = 1, - .pColorAttachments = &attachmentInfo, - .pDepthAttachment = &depthAttachmentInfo, + .pColorAttachments = &attachment_info, + .pDepthAttachment = &depth_attachment_info, .pStencilAttachment = nullptr, }; vkCmdPipelineBarrier2( cmd, &misc.acquireToRenderDependency ); - vkCmdBeginRendering( cmd, &renderingInfo ); + vkCmdBeginRendering( cmd, &rendering_info ); { VkViewport viewport = { .x = 0, - .y = static_cast( renderDevice.swapchainExtent.height ), - .width = static_cast( renderDevice.swapchainExtent.width ), - .height = -static_cast( renderDevice.swapchainExtent.height ), + .y = static_cast( render_device.swapchainExtent.height ), + .width = static_cast( render_device.swapchainExtent.width ), + .height = -static_cast( render_device.swapchainExtent.height ), .minDepth = 0.0f, .maxDepth = 1.0f, }; vkCmdSetViewport( cmd, 0, 1, &viewport ); VkRect2D scissor = { .offset = { 0, 0 }, - .extent = renderDevice.swapchainExtent, + .extent = render_device.swapchainExtent, }; vkCmdSetScissor( cmd, 0, 1, &scissor ); @@ -225,98 +227,98 @@ SDL_AppResult SDL_AppIterate( void* appstate ) vkCmdBindPipeline( cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.meshPipeline ); vkCmdBindDescriptorSets( - cmd, - VK_PIPELINE_BIND_POINT_GRAPHICS, - misc.pipelineLayout, - 0, - 1, - &renderDevice.textureManager->descriptorSet(), - 0, - nullptr ); + cmd, + VK_PIPELINE_BIND_POINT_GRAPHICS, + misc.pipelineLayout, + 0, + 1, + &render_device.textureManager->DescriptorSet(), + 0, + nullptr ); vkCmdBindDescriptorSets( - cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.pipelineLayout, 1, 1, &misc.descriptorSet, 0, nullptr ); + cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.pipelineLayout, 1, 1, &misc.descriptorSet, 0, nullptr ); - std::function drawEntity = - [&]( Entity const& entity, DirectX::XMMATRIX const& parent, Model const* current ) + std::function draw_entity = + [&]( Blaze::Entity const& entity, DirectX::XMMATRIX const& parent, Blaze::Model const* current ) { - Transform const& localTransform = entity.transform; - DirectX::XMMATRIX worldTransform; + Blaze::Transform const& local_transform = entity.transform; + DirectX::XMMATRIX world_transform; { - worldTransform = - DirectX::XMMatrixAffineTransformation( - localTransform.scale, DirectX::XMVectorZero(), localTransform.rotation, localTransform.translation ) * - parent; + world_transform = + DirectX::XMMatrixAffineTransformation( + local_transform.scale, DirectX::XMVectorZero(), local_transform.rotation, local_transform.translation ) * + parent; } - if ( not entity.model.isNull() ) + if ( not entity.model.IsNull() ) { - VkBuffer const vertexBuffer = renderDevice.bufferManager->fetchBuffer( entity.model.vertexBuffer ).value(); + VkBuffer const vertex_buffer = render_device.bufferManager->FetchBuffer( entity.model.vertexBuffer ).value(); - VkBuffer const indexBuffer = renderDevice.bufferManager->fetchBuffer( entity.model.indexBuffer ).value(); + VkBuffer const index_buffer = render_device.bufferManager->FetchBuffer( entity.model.indexBuffer ).value(); VkDeviceSize constexpr offset = 0; - vkCmdBindVertexBuffers( cmd, 0, 1, &vertexBuffer, &offset ); - vkCmdBindIndexBuffer( cmd, indexBuffer, offset, VK_INDEX_TYPE_UINT32 ); + vkCmdBindVertexBuffers( cmd, 0, 1, &vertex_buffer, &offset ); + vkCmdBindIndexBuffer( cmd, index_buffer, offset, VK_INDEX_TYPE_UINT32 ); } vkCmdPushConstants( - cmd, misc.pipelineLayout, VK_SHADER_STAGE_ALL_GRAPHICS, 0, sizeof worldTransform, &worldTransform ); + cmd, misc.pipelineLayout, VK_SHADER_STAGE_ALL_GRAPHICS, 0, sizeof world_transform, &world_transform ); - DirectX::XMMATRIX const inverseTransform = XMMatrixInverse( nullptr, worldTransform ); + DirectX::XMMATRIX const inverse_transform = XMMatrixInverse( nullptr, world_transform ); vkCmdPushConstants( - cmd, - misc.pipelineLayout, - VK_SHADER_STAGE_ALL_GRAPHICS, - sizeof worldTransform, - sizeof inverseTransform, - &inverseTransform ); + cmd, + misc.pipelineLayout, + VK_SHADER_STAGE_ALL_GRAPHICS, + sizeof world_transform, + sizeof inverse_transform, + &inverse_transform ); - if ( not entity.modelMesh.isNull() ) + if ( not entity.modelMesh.IsNull() ) { ASSERT( current ); - for ( Primitive const& primitive : std::span{ current->primitives.data() + entity.modelMesh.primitiveStart, - entity.modelMesh.primitiveCount } ) + for ( Blaze::Primitive const& primitive : std::span{ + current->primitives.data() + entity.modelMesh.primitiveStart, entity.modelMesh.primitiveCount } ) { - byte const* materialData = nullptr; + Blaze::byte const* material_data; if ( primitive.material != UINT32_MAX ) { - Material const* mat = ¤t->materials[primitive.material]; - materialData = reinterpret_cast( mat ); - materialData += Material::GPU_DATA_OFFSET; + Blaze::Material const* mat = ¤t->materials[primitive.material]; + material_data = reinterpret_cast( mat ); + material_data += Blaze::Material::kGPUDataOffset; } else { - materialData = reinterpret_cast( &DEFAULT_MATERIAL ); - materialData += Material::GPU_DATA_OFFSET; + material_data = reinterpret_cast( &Blaze::DEFAULT_MATERIAL ); + material_data += Blaze::Material::kGPUDataOffset; } vkCmdPushConstants( - cmd, - misc.pipelineLayout, - VK_SHADER_STAGE_ALL_GRAPHICS, - 2 * sizeof worldTransform, - Material::GPU_DATA_SIZE, - materialData ); + cmd, + misc.pipelineLayout, + VK_SHADER_STAGE_ALL_GRAPHICS, + 2 * sizeof world_transform, + Blaze::Material::kGPUDataSize, + material_data ); vkCmdDrawIndexed( cmd, primitive.indexCount, 1, primitive.indexStart, primitive.vertexOffset, 0 ); } } - for ( Entity& child : entity.children() ) + for ( Blaze::Entity& child : entity.IterChildren() ) { - drawEntity( child, worldTransform, entity.model.isNull() ? current : &entity.model ); + draw_entity( child, world_transform, entity.model.IsNull() ? current : &entity.model ); } }; - for ( Entity const& entity : entityManager.iter() ) + for ( Blaze::Entity const& entity : entity_manager.Iterate() ) { - if ( not entity.isRoot() ) + if ( not entity.IsRoot() ) { continue; } - drawEntity( entity, DirectX::XMMatrixIdentity(), nullptr ); + draw_entity( entity, DirectX::XMMatrixIdentity(), nullptr ); } } vkCmdEndRendering( cmd ); @@ -324,38 +326,39 @@ SDL_AppResult SDL_AppIterate( void* appstate ) } VK_CHECK( vkEndCommandBuffer( cmd ) ); - VkPipelineStageFlags stageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - VkSubmitInfo const submitInfo = { + VkPipelineStageFlags stage_mask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + VkSubmitInfo const submit_info = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .pNext = nullptr, .waitSemaphoreCount = 1, - .pWaitSemaphores = ¤tFrame.imageAcquiredSemaphore, - .pWaitDstStageMask = &stageMask, + .pWaitSemaphores = ¤t_frame.imageAcquiredSemaphore, + .pWaitDstStageMask = &stage_mask, .commandBufferCount = 1, .pCommandBuffers = &cmd, .signalSemaphoreCount = 1, - .pSignalSemaphores = ¤tFrame.renderFinishedSemaphore, + .pSignalSemaphores = ¤t_frame.renderFinishedSemaphore, }; - VK_CHECK( vkQueueSubmit( renderDevice.directQueue, 1, &submitInfo, currentFrame.frameReadyToReuse ) ); + VK_CHECK( vkQueueSubmit( render_device.directQueue, 1, &submit_info, current_frame.frameReadyToReuse ) ); - VkPresentInfoKHR const presentInfo = { + VkPresentInfoKHR const present_info = { .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .pNext = nullptr, .waitSemaphoreCount = 1, - .pWaitSemaphores = ¤tFrame.renderFinishedSemaphore, + .pWaitSemaphores = ¤t_frame.renderFinishedSemaphore, .swapchainCount = 1, - .pSwapchains = &renderDevice.swapchain, - .pImageIndices = ¤tImageIndex, + .pSwapchains = &render_device.swapchain, + .pImageIndices = ¤t_image_index, .pResults = nullptr, }; - VK_CHECK( vkQueuePresentKHR( renderDevice.directQueue, &presentInfo ) ); + VK_CHECK( vkQueuePresentKHR( render_device.directQueue, &present_info ) ); - renderDevice.frameIndex = ( renderDevice.frameIndex + 1 ) % NUM_FRAMES; + render_device.frameIndex = ( render_device.frameIndex + 1 ) % NUM_FRAMES; return SDL_APP_CONTINUE; } +// ReSharper disable once CppInconsistentNaming SDL_AppResult SDL_AppEvent( void*, SDL_Event* event ) { if ( event->type == SDL_EVENT_QUIT ) @@ -366,11 +369,12 @@ SDL_AppResult SDL_AppEvent( void*, SDL_Event* event ) return SDL_APP_CONTINUE; } +// ReSharper disable once CppInconsistentNaming void SDL_AppQuit( void* appstate, SDL_AppResult ) { - AppState* appState = static_cast( appstate ); + auto* app_state = static_cast( appstate ); - if ( appState ) appState->destroy(); + if ( app_state ) app_state->Destroy(); - Blaze::Global::g_Memory.destroy(); + Blaze::Global::g_Memory.Destroy(); } diff --git a/Blaze/Source/BufferManager.cpp b/Blaze/Source/BufferManager.cpp index 400ddec..f23b2f4 100644 --- a/Blaze/Source/BufferManager.cpp +++ b/Blaze/Source/BufferManager.cpp @@ -3,75 +3,75 @@ #include "GlobalMemory.h" -template struct RID; +using Blaze::BufferManager; -void BufferManager::destroyBuffer( Buffer& buf ) +void BufferManager::DestroyBuffer( Buffer& buf ) { if ( not buf.buffer ) return; - ASSERT( m_pRenderDevice ); + ASSERT( m_renderDevice ); - uint32_t const index = buf.index; - uint32_t const innerIndex = index & INDEX_MASK; - uint32_t const generation = ( index & GENERATION_MASK ) >> GENERATION_OFFSET; + uint32_t const index = buf.index; + uint32_t const inner_index = index & kIndexMask; + uint32_t const generation = ( index & kGenerationMask ) >> kGenerationOffset; - RenderDevice const& renderDevice = *m_pRenderDevice; + RenderDevice const& render_device = *m_renderDevice; - vmaDestroyBuffer( renderDevice.gpuAllocator, Take( buf.buffer ), Take( buf.allocation ) ); + vmaDestroyBuffer( render_device.gpuAllocator, Take( buf.buffer ), Take( buf.allocation ) ); buf.size = 0; buf.mappedData = nullptr; - buf.index = innerIndex | ( generation + 1 ) << GENERATION_OFFSET; + buf.index = inner_index | ( generation + 1 ) << kGenerationOffset; // NOTE: DO NOT EDIT INNER INDEX. - ASSERT( innerIndex == ( buf.index & INDEX_MASK ) and "Index should not be modified" ); + ASSERT( inner_index == ( buf.index & kIndexMask ) and "Index should not be modified" ); ASSERT( buf.index > index and "Generation should increase." ); - m_freeList.pushBack( reinterpret_cast( &buf ) ); + m_freeList.PushBack( reinterpret_cast( &buf ) ); --m_count; } -Buffer& BufferManager::fetchBufferUnchecked( BufferID const& rid ) +Blaze::Buffer& BufferManager::FetchBufferUnchecked( BufferID const& rid ) { - uint32_t const index = *reinterpret_cast( &rid ); - uint32_t const innerIndex = index & INDEX_MASK; + uint32_t const index = *reinterpret_cast( &rid ); + uint32_t const inner_index = index & kIndexMask; - return m_aBuffers[innerIndex]; + return m_buffers[inner_index]; } -void BufferManager::writeToBufferImpl( BufferID const& rid, void const* data, size_t const size ) +void BufferManager::WriteToBufferImpl( BufferID const& rid, void const* data, size_t const size ) { - ASSERT( isValidID( rid ) ); + ASSERT( IsValidID( rid ) ); - Buffer const& buffer = fetchBufferUnchecked( rid ); + Buffer const& buffer = FetchBufferUnchecked( rid ); ASSERT( size <= buffer.size ); memcpy( buffer.mappedData, data, size ); } -bool BufferManager::isValidID( BufferID const& rid ) const +bool BufferManager::IsValidID( BufferID const& rid ) const { - uint32_t const index = *reinterpret_cast( &rid ); - uint32_t const innerIndex = index & INDEX_MASK; + uint32_t const index = *reinterpret_cast( &rid ); + uint32_t const inner_index = index & kIndexMask; - if ( innerIndex > m_capacity ) return false; + if ( inner_index > m_capacity ) return false; - return m_aBuffers[innerIndex].index == index; + return m_buffers[inner_index].index == index; } -BufferID BufferManager::createVertexBuffer( size_t const size ) +Blaze::BufferID BufferManager::CreateVertexBuffer( size_t const size ) { - ASSERT( not m_freeList.empty() ); + ASSERT( not m_freeList.Empty() ); - Buffer* bufferSlot = reinterpret_cast( m_freeList.popFront() ); + Buffer* buffer_slot = reinterpret_cast( m_freeList.PopFront() ); ++m_count; - ASSERT( m_pRenderDevice ); - RenderDevice const& renderDevice = *m_pRenderDevice; + ASSERT( m_renderDevice ); + RenderDevice const& render_device = *m_renderDevice; - VkBufferCreateInfo const bufferCreateInfo = { + VkBufferCreateInfo const buffer_create_info = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -82,7 +82,7 @@ BufferID BufferManager::createVertexBuffer( size_t const size ) .pQueueFamilyIndices = nullptr, }; - VmaAllocationCreateInfo constexpr allocationCreateInfo = { + VmaAllocationCreateInfo constexpr allocation_create_info = { .flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, .usage = VMA_MEMORY_USAGE_AUTO, .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, @@ -93,24 +93,24 @@ BufferID BufferManager::createVertexBuffer( size_t const size ) .priority = 1.0f, }; - VmaAllocationInfo allocationInfo; - VkBuffer vertexBuffer; - VmaAllocation vertexBufferAllocation; + VmaAllocationInfo allocation_info; + VkBuffer vertex_buffer; + VmaAllocation vertex_buffer_allocation; VK_CHECK( vmaCreateBuffer( - renderDevice.gpuAllocator, - &bufferCreateInfo, - &allocationCreateInfo, - &vertexBuffer, - &vertexBufferAllocation, - &allocationInfo ) ); + render_device.gpuAllocator, + &buffer_create_info, + &allocation_create_info, + &vertex_buffer, + &vertex_buffer_allocation, + &allocation_info ) ); // NOTE: textureSlot preserves index between uses. - uint32_t index = bufferSlot->index; - new ( bufferSlot ) Buffer{ - .buffer = vertexBuffer, - .allocation = vertexBufferAllocation, - .mappedData = static_cast( allocationInfo.pMappedData ), + uint32_t index = buffer_slot->index; + new ( buffer_slot ) Buffer{ + .buffer = vertex_buffer, + .allocation = vertex_buffer_allocation, + .mappedData = static_cast( allocation_info.pMappedData ), .deviceAddress = 0, .size = size, .index = index, @@ -120,18 +120,18 @@ BufferID BufferManager::createVertexBuffer( size_t const size ) return *reinterpret_cast( &index ); } -BufferID BufferManager::createIndexBuffer( size_t const size ) +Blaze::BufferID BufferManager::CreateIndexBuffer( size_t const size ) { - ASSERT( not m_freeList.empty() ); + ASSERT( not m_freeList.Empty() ); - Buffer* bufferSlot = reinterpret_cast( m_freeList.popFront() ); + Buffer* buffer_slot = reinterpret_cast( m_freeList.PopFront() ); ++m_count; - ASSERT( m_pRenderDevice ); - RenderDevice const& renderDevice = *m_pRenderDevice; + ASSERT( m_renderDevice ); + RenderDevice const& render_device = *m_renderDevice; - VkBufferCreateInfo const bufferCreateInfo = { + VkBufferCreateInfo const buffer_create_info = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -142,7 +142,7 @@ BufferID BufferManager::createIndexBuffer( size_t const size ) .pQueueFamilyIndices = nullptr, }; - VmaAllocationCreateInfo constexpr allocationCreateInfo = { + VmaAllocationCreateInfo constexpr allocation_create_info = { .flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, .usage = VMA_MEMORY_USAGE_AUTO, .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, @@ -153,24 +153,24 @@ BufferID BufferManager::createIndexBuffer( size_t const size ) .priority = 1.0f, }; - VmaAllocationInfo allocationInfo; - VkBuffer indexBuffer; - VmaAllocation indexBufferAllocation; + VmaAllocationInfo allocation_info; + VkBuffer index_buffer; + VmaAllocation index_buffer_allocation; VK_CHECK( vmaCreateBuffer( - renderDevice.gpuAllocator, - &bufferCreateInfo, - &allocationCreateInfo, - &indexBuffer, - &indexBufferAllocation, - &allocationInfo ) ); + render_device.gpuAllocator, + &buffer_create_info, + &allocation_create_info, + &index_buffer, + &index_buffer_allocation, + &allocation_info ) ); // NOTE: bufferSlot preserves index between uses. - uint32_t index = bufferSlot->index; - new ( bufferSlot ) Buffer{ - .buffer = indexBuffer, - .allocation = indexBufferAllocation, - .mappedData = static_cast( allocationInfo.pMappedData ), + uint32_t index = buffer_slot->index; + new ( buffer_slot ) Buffer{ + .buffer = index_buffer, + .allocation = index_buffer_allocation, + .mappedData = static_cast( allocation_info.pMappedData ), .deviceAddress = 0, .size = size, .index = index, @@ -180,18 +180,18 @@ BufferID BufferManager::createIndexBuffer( size_t const size ) return *reinterpret_cast( &index ); } -BufferID BufferManager::createStorageBuffer( size_t const size ) +Blaze::BufferID BufferManager::CreateStorageBuffer( size_t const size ) { - ASSERT( not m_freeList.empty() ); + ASSERT( not m_freeList.Empty() ); - Buffer* bufferSlot = reinterpret_cast( m_freeList.popFront() ); + Buffer* buffer_slot = reinterpret_cast( m_freeList.PopFront() ); ++m_count; - ASSERT( m_pRenderDevice ); - RenderDevice const& renderDevice = *m_pRenderDevice; + ASSERT( m_renderDevice ); + RenderDevice const& render_device = *m_renderDevice; - VkBufferCreateInfo const bufferCreateInfo = { + VkBufferCreateInfo const buffer_create_info = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -202,7 +202,7 @@ BufferID BufferManager::createStorageBuffer( size_t const size ) .pQueueFamilyIndices = nullptr, }; - VmaAllocationCreateInfo constexpr allocationCreateInfo = { + VmaAllocationCreateInfo constexpr allocation_create_info = { .flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, .usage = VMA_MEMORY_USAGE_AUTO, .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, @@ -213,33 +213,33 @@ BufferID BufferManager::createStorageBuffer( size_t const size ) .priority = 1.0f, }; - VmaAllocationInfo allocationInfo; - VkBuffer storageBuffer; - VmaAllocation storageBufferAllocation; + VmaAllocationInfo allocation_info; + VkBuffer storage_buffer; + VmaAllocation storage_buffer_allocation; VK_CHECK( vmaCreateBuffer( - renderDevice.gpuAllocator, - &bufferCreateInfo, - &allocationCreateInfo, - &storageBuffer, - &storageBufferAllocation, - &allocationInfo ) ); + render_device.gpuAllocator, + &buffer_create_info, + &allocation_create_info, + &storage_buffer, + &storage_buffer_allocation, + &allocation_info ) ); - VkBufferDeviceAddressInfo const deviceAddressInfo = { + VkBufferDeviceAddressInfo const device_address_info = { .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, .pNext = nullptr, - .buffer = storageBuffer, + .buffer = storage_buffer, }; - VkDeviceAddress const deviceAddress = vkGetBufferDeviceAddress( renderDevice.device, &deviceAddressInfo ); + VkDeviceAddress const device_address = vkGetBufferDeviceAddress( render_device.device, &device_address_info ); // NOTE: bufferSlot preserves index between uses. - uint32_t index = bufferSlot->index; - new ( bufferSlot ) Buffer{ - .buffer = storageBuffer, - .allocation = storageBufferAllocation, - .mappedData = static_cast( allocationInfo.pMappedData ), - .deviceAddress = deviceAddress, + uint32_t index = buffer_slot->index; + new ( buffer_slot ) Buffer{ + .buffer = storage_buffer, + .allocation = storage_buffer_allocation, + .mappedData = static_cast( allocation_info.pMappedData ), + .deviceAddress = device_address, .size = size, .index = index, }; @@ -248,47 +248,50 @@ BufferID BufferManager::createStorageBuffer( size_t const size ) return *reinterpret_cast( &index ); } -void BufferManager::freeBuffer( BufferID* rid ) +void BufferManager::FreeBuffer( BufferID* rid ) { - if ( not isValidID( *rid ) ) return; + if ( not IsValidID( *rid ) ) return; - Buffer& buffer = fetchBufferUnchecked( *rid ); + Buffer& buffer = FetchBufferUnchecked( *rid ); - destroyBuffer( buffer ); + DestroyBuffer( buffer ); *rid = {}; } -std::optional BufferManager::fetchBuffer( BufferID const& rid ) +std::optional BufferManager::FetchBuffer( BufferID const& rid ) { - if ( not isValidID( rid ) ) return std::nullopt; + if ( not IsValidID( rid ) ) return std::nullopt; - return fetchBufferUnchecked( rid ).buffer; + return FetchBufferUnchecked( rid ).buffer; } -std::optional BufferManager::fetchDeviceAddress( BufferID const& rid ) +std::optional BufferManager::FetchDeviceAddress( BufferID const& rid ) { - if ( not isValidID( rid ) ) return std::nullopt; - Buffer const& buffer = fetchBufferUnchecked( rid ); + if ( not IsValidID( rid ) ) return std::nullopt; + Buffer const& buffer = FetchBufferUnchecked( rid ); if ( buffer.deviceAddress == 0 ) return std::nullopt; return buffer.deviceAddress; } -BufferManager::BufferManager( RenderDevice* pRenderDevice, Buffer* aBuffers, uint32_t const capacity ) - : m_pRenderDevice{ pRenderDevice }, m_aBuffers{ aBuffers }, m_count{ 0 }, m_capacity{ capacity } +BufferManager::BufferManager( RenderDevice* render_device, Buffer* buffers, uint32_t const capacity ) + : m_renderDevice{ render_device } + , m_buffers{ buffers } + , m_count{ 0 } + , m_capacity{ capacity } { uint32_t i = 0; - for ( Buffer& tex : std::span{ m_aBuffers, m_capacity } ) + for ( Buffer& tex : std::span{ m_buffers, m_capacity } ) { // Default Generation is 1 - tex.index = i++ | ( 1 << GENERATION_OFFSET ); - m_freeList.pushFront( reinterpret_cast( &tex ) ); + tex.index = i++ | ( 1 << kGenerationOffset ); + m_freeList.PushFront( reinterpret_cast( &tex ) ); } } -void BufferManager::destroy() +void BufferManager::Destroy() { #if defined( _DEBUG ) @@ -298,30 +301,31 @@ void BufferManager::destroy() } #endif - while ( not m_freeList.empty() ) + while ( not m_freeList.Empty() ) { - Buffer* buf = reinterpret_cast( m_freeList.popFront() ); + Buffer* buf = reinterpret_cast( m_freeList.PopFront() ); memset( buf, 0, sizeof *buf ); } - for ( Buffer& buf : std::span{ m_aBuffers, m_count } ) + for ( Buffer& buf : std::span{ m_buffers, m_count } ) { - destroyBuffer( buf ); + DestroyBuffer( buf ); } } BufferManager::~BufferManager() { - ASSERT( not m_aBuffers ); + ASSERT( not m_buffers ); } -BufferManager* BufferManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t maxCount ) + +BufferManager* BufferManager::Create( GlobalMemory* mem, RenderDevice* render_device, uint32_t const max_count ) { - Buffer* buffers = reinterpret_cast( mem->allocate( maxCount * sizeof( Buffer ), alignof( Buffer ) ) ); + Buffer* buffers = reinterpret_cast( mem->Allocate( max_count * sizeof( Buffer ), alignof( Buffer ) ) ); if ( not buffers ) return nullptr; - std::byte* allocation = mem->allocate( sizeof( BufferManager ), alignof( BufferManager ) ); + std::byte* allocation = mem->Allocate( sizeof( BufferManager ), alignof( BufferManager ) ); if ( not allocation ) return nullptr; - return new ( allocation ) BufferManager{ renderDevice, buffers, maxCount }; + return new ( allocation ) BufferManager{ render_device, buffers, max_count }; } diff --git a/Blaze/Source/BufferManager.h b/Blaze/Source/BufferManager.h index 79e92fe..694d812 100644 --- a/Blaze/Source/BufferManager.h +++ b/Blaze/Source/BufferManager.h @@ -9,6 +9,8 @@ #include "RenderDevice.h" #include "VulkanHeader.h" +namespace Blaze +{ struct GlobalMemory; struct RenderDevice; @@ -22,60 +24,62 @@ struct Buffer uint32_t index; }; -static_assert( sizeof( Buffer ) > sizeof( FreeList::Node ) and "Buffer is used intrusively by FreeList" ); +static_assert( sizeof( Buffer ) > sizeof( Util::FreeList::Node ) and "Buffer is used intrusively by FreeList" ); static_assert( - offsetof( Buffer, index ) >= sizeof( FreeList::Node ) and "Index should not be overwritten even in invalid state" ); + offsetof( Buffer, index ) >= sizeof( Util::FreeList::Node ) and + "Index should not be overwritten even in invalid state" ); -extern template struct RID; using BufferID = RID; struct BufferManager { private: - constexpr static uint32_t INDEX_MASK = 0x0007FFFF; - constexpr static uint32_t GENERATION_MASK = ~INDEX_MASK; - constexpr static uint32_t GENERATION_OFFSET = 19; + constexpr static uint32_t kIndexMask = 0x0007FFFF; + constexpr static uint32_t kGenerationMask = ~kIndexMask; + constexpr static uint32_t kGenerationOffset = 19; static_assert( - ( ( GENERATION_MASK >> GENERATION_OFFSET & 0x1 ) == 0x1 ) and - ( ( GENERATION_MASK >> ( GENERATION_OFFSET - 1 ) & 0x1 ) != 0x1 ) and "Checks boundary" ); + ( ( kGenerationMask >> kGenerationOffset & 0x1 ) == 0x1 ) and + ( ( kGenerationMask >> ( kGenerationOffset - 1 ) & 0x1 ) != 0x1 ) and "Checks boundary" ); - RenderDevice* m_pRenderDevice; + RenderDevice* m_renderDevice; // Buffer Manager - Buffer* m_aBuffers; - uint32_t m_count; - uint32_t m_capacity; - FreeList m_freeList; + Buffer* m_buffers; + uint32_t m_count; + uint32_t m_capacity; + Util::FreeList m_freeList; - void destroyBuffer( Buffer& buf ); + void DestroyBuffer( Buffer& buf ); - Buffer& fetchBufferUnchecked( BufferID const& rid ); - void writeToBufferImpl( BufferID const& rid, void const* data, size_t size ); + Buffer& FetchBufferUnchecked( BufferID const& rid ); + void WriteToBufferImpl( BufferID const& rid, void const* data, size_t size ); public: - [[nodiscard]] bool isValidID( BufferID const& rid ) const; + [[nodiscard]] bool IsValidID( BufferID const& rid ) const; - BufferID createVertexBuffer( size_t size ); - BufferID createIndexBuffer( size_t size ); - BufferID createStorageBuffer( size_t size ); + BufferID CreateVertexBuffer( size_t size ); + BufferID CreateIndexBuffer( size_t size ); + BufferID CreateStorageBuffer( size_t size ); - void freeBuffer( BufferID* rid ); + void FreeBuffer( BufferID* rid ); DEPRECATE_JULY_2025 - std::optional fetchBuffer( BufferID const& rid ); - std::optional fetchDeviceAddress( BufferID const& rid ); + std::optional FetchBuffer( BufferID const& rid ); + std::optional FetchDeviceAddress( BufferID const& rid ); - void writeToBuffer( BufferID const& rid, std::ranges::contiguous_range auto const& data ) + // Utility to directly muck the data + void WriteToBuffer( BufferID const& rid, std::ranges::contiguous_range auto const& data ) { - writeToBufferImpl( - rid, - std::ranges::data( data ), - std::ranges::size( data ) * sizeof( std::ranges::range_value_t ) ); + WriteToBufferImpl( + rid, + std::ranges::data( data ), + std::ranges::size( data ) * sizeof( std::ranges::range_value_t ) ); } - // - BufferManager( RenderDevice* pRenderDevice, Buffer* aBuffers, uint32_t capacity ); - void destroy(); + static BufferManager* Create( GlobalMemory* mem, RenderDevice* render_device, uint32_t max_count ); + void Destroy(); + + BufferManager( RenderDevice* render_device, Buffer* buffers, uint32_t capacity ); BufferManager( BufferManager const& other ) = delete; BufferManager( BufferManager&& other ) noexcept = delete; @@ -84,4 +88,5 @@ public: ~BufferManager(); }; -BufferManager* BufferManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t maxCount ); + +} // namespace Blaze diff --git a/Blaze/Source/CgltfImpl.cpp b/Blaze/Source/CgltfImpl.cpp index b0cf325..1709c50 100644 --- a/Blaze/Source/CgltfImpl.cpp +++ b/Blaze/Source/CgltfImpl.cpp @@ -1,3 +1,3 @@ #define CGLTF_IMPLEMENTATION -#include \ No newline at end of file +#include diff --git a/Blaze/Source/EntityManager.cpp b/Blaze/Source/EntityManager.cpp index 6e78079..4de4e55 100644 --- a/Blaze/Source/EntityManager.cpp +++ b/Blaze/Source/EntityManager.cpp @@ -8,9 +8,12 @@ #include "Frame.h" #include "TextureManager.h" +namespace Blaze +{ + Entity& EntitySiblingIterable::Iterator::operator++() { - current = current->nextSibling(); + current = current->NextSibling(); return *current; } @@ -34,43 +37,42 @@ EntitySiblingIterable::Iterator EntitySiblingIterable::end() return {}; } - -void Entity::setParent( Entity* parent ) +void Entity::SetParent( Entity* parent ) { ASSERT( parent ); if ( m_parent == parent ) return; - removeParent(); + RemoveParent(); - // Insert self into parent. - m_parent = parent; + // Insert self into GetParent. + m_parent = parent; - Entity* oldHead = parent->m_firstChild; + Entity* old_head = parent->m_firstChild; - if ( oldHead ) + if ( old_head ) { // Old head is next after this - this->m_nextSibling = oldHead; + this->m_nextSibling = old_head; // This is prev to old head - oldHead->m_prevSibling = this; + old_head->m_prevSibling = this; } // We are the head now. m_parent->m_firstChild = this; } -void Entity::addChild( Entity* child ) +void Entity::AddChild( Entity* child ) { - child->setParent( this ); + child->SetParent( this ); } -void Entity::removeChild( Entity* child ) +void Entity::RemoveChild( Entity* child ) { ASSERT( child ); - child->removeParent(); + child->RemoveParent(); } -void Entity::removeParent() +void Entity::RemoveParent() { if ( m_parent ) { @@ -95,7 +97,7 @@ void Entity::removeParent() } } -EntitySiblingIterable Entity::children() const +EntitySiblingIterable Entity::IterChildren() const { return { m_firstChild }; } @@ -111,35 +113,47 @@ Entity::Entity( Transform const& transform ) , m_flags{ 0 } {} -Entity* EntityManager::createEntity( Transform const& transform ) -{ - ASSERT( count < capacity ); +EntityManager::EntityManager( RenderDevice* render_device, Entity* data, uint32_t const capacity ) + : m_renderDevice{ render_device } + , m_entities{ data } + , m_count{ 0 } + , m_capacity{ capacity } +{} - Entity& entity = entities[count++]; +EntityManager::Iterable EntityManager::Iterate() const +{ + return Iterable{ m_entities, m_count }; +} + +Entity* EntityManager::CreateEntity( Transform const& transform ) +{ + ASSERT( m_count < m_capacity ); + + Entity& entity = m_entities[m_count++]; new ( &entity ) Entity{ transform }; return &entity; } -void EntityManager::destroyEntity( Entity* entity ) +void EntityManager::DestroyEntity( Entity* entity ) { ASSERT( entity ); - VkDevice const device = pRenderDevice->device; + VkDevice const device = m_renderDevice->device; - if ( not entity->model.isNull() ) + if ( not entity->model.IsNull() ) { - for ( auto& material : entity->model.materials ) + for ( Material& material : entity->model.materials ) { vkDestroySampler( device, Take( material.sampler ), nullptr ); - pRenderDevice->textureManager->freeTexture( &material.albedoTextureID ); - pRenderDevice->textureManager->freeTexture( &material.normalTextureID ); - pRenderDevice->textureManager->freeTexture( &material.metalRoughTextureID ); - pRenderDevice->textureManager->freeTexture( &material.emissiveTextureID ); + m_renderDevice->textureManager->FreeTexture( &material.albedoTextureID ); + m_renderDevice->textureManager->FreeTexture( &material.normalTextureID ); + m_renderDevice->textureManager->FreeTexture( &material.metalRoughTextureID ); + m_renderDevice->textureManager->FreeTexture( &material.emissiveTextureID ); } - pRenderDevice->bufferManager->freeBuffer( &entity->model.vertexBuffer ); - pRenderDevice->bufferManager->freeBuffer( &entity->model.indexBuffer ); + m_renderDevice->bufferManager->FreeBuffer( &entity->model.vertexBuffer ); + m_renderDevice->bufferManager->FreeBuffer( &entity->model.indexBuffer ); entity->model.primitives.clear(); entity->model.materials.clear(); } @@ -147,29 +161,32 @@ void EntityManager::destroyEntity( Entity* entity ) entity->modelMesh = { 0, 0 }; } -void EntityManager::destroy() +void EntityManager::Destroy() { - Entity const* end = entities + capacity; - for ( Entity* iter = entities; iter != end; ++iter ) + Entity const* end = m_entities + m_capacity; + for ( Entity* iter = m_entities; iter != end; ++iter ) { - destroyEntity( iter ); + DestroyEntity( iter ); } - entities = nullptr; - capacity = 0; - count = 0; + m_entities = nullptr; + m_capacity = 0; + m_count = 0; } EntityManager::~EntityManager() { - assert( !entities ); + assert( !m_entities ); } -EntityManager* EntityManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t const capacity ) + +EntityManager* EntityManager::Create( GlobalMemory* mem, RenderDevice* render_device, uint32_t const capacity ) { - Entity* data = reinterpret_cast( mem->allocate( capacity * sizeof( Entity ), alignof( Entity ) ) ); + Entity* data = reinterpret_cast( mem->Allocate( capacity * sizeof( Entity ), alignof( Entity ) ) ); memset( data, 0, capacity * sizeof( Entity ) ); - std::byte* alloc = mem->allocate( sizeof( EntityManager ), alignof( EntityManager ) ); - return new ( alloc ) EntityManager{ renderDevice, data, capacity }; + std::byte* alloc = mem->Allocate( sizeof( EntityManager ), alignof( EntityManager ) ); + return new ( alloc ) EntityManager{ render_device, data, capacity }; } + +} // namespace Blaze diff --git a/Blaze/Source/EntityManager.h b/Blaze/Source/EntityManager.h index 8da37ad..9cfce74 100644 --- a/Blaze/Source/EntityManager.h +++ b/Blaze/Source/EntityManager.h @@ -3,14 +3,15 @@ #include #include -#include -#include "VulkanHeader.h" #include "ModelLoader.h" +namespace Blaze +{ + +struct GlobalMemory; struct Entity; struct RenderDevice; -struct GlobalMemory; struct Transform { @@ -50,31 +51,31 @@ private: uint64_t m_flags; // FIXME: Wasting space. public: - [[nodiscard]] bool isRoot() const + [[nodiscard]] bool IsRoot() const { return not m_parent; } - [[nodiscard]] Entity* parent() const + [[nodiscard]] Entity* GetParent() const { return m_parent; } - [[nodiscard]] Entity* nextSibling() const + [[nodiscard]] Entity* NextSibling() const { return m_nextSibling; } - void setParent( Entity* parent ); + void SetParent( Entity* parent ); - void addChild( Entity* child ); + void AddChild( Entity* child ); - void removeChild( Entity* child ); + void RemoveChild( Entity* child ); - // Remove self from parent - void removeParent(); + // Remove self from GetParent + void RemoveParent(); - [[nodiscard]] EntitySiblingIterable children() const; + [[nodiscard]] EntitySiblingIterable IterChildren() const; explicit Entity( Transform const& transform ); }; @@ -102,28 +103,26 @@ struct EntityManager } }; - RenderDevice* pRenderDevice; - Entity* entities; - uint32_t count; - uint32_t capacity; +private: + RenderDevice* m_renderDevice; + Entity* m_entities; + uint32_t m_count; + uint32_t m_capacity; - EntityManager( RenderDevice* renderDevice, Entity* data, uint32_t const capacity ) - : pRenderDevice{ renderDevice }, entities{ data }, count{ 0 }, capacity{ capacity } - {} +public: + EntityManager( RenderDevice* render_device, Entity* data, uint32_t capacity ); - [[nodiscard]] Iterable iter() const - { - return Iterable{ entities, count }; - } + [[nodiscard]] Iterable Iterate() const; // Make Entities return ID, make it a sparse indexing system. - Entity* createEntity( Transform const& transform ); + Entity* CreateEntity( Transform const& transform ); - void destroyEntity( Entity* entity ); + void DestroyEntity( Entity* entity ); - void destroy(); + static EntityManager* Create( GlobalMemory* mem, RenderDevice* render_device, uint32_t capacity ); + void Destroy(); ~EntityManager(); }; -EntityManager* EntityManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t capacity ); +} // namespace Blaze diff --git a/Blaze/Source/Frame.cpp b/Blaze/Source/Frame.cpp index d5676ed..82cf25a 100644 --- a/Blaze/Source/Frame.cpp +++ b/Blaze/Source/Frame.cpp @@ -5,38 +5,40 @@ #include "MacroUtils.h" #include "RenderDevice.h" -bool Frame::isInit() const +using Blaze::Frame; + +bool Blaze::Frame::IsInit() const { return static_cast( commandPool ); } Frame::Frame( - VkCommandPool const commandPool, - VkCommandBuffer const commandBuffer, - VkSemaphore const imageAcquiredSemaphore, - VkSemaphore const renderFinishedSemaphore, - VkFence const frameReadyToReuse, - VkImage const depthImage, - VmaAllocation const depthAllocation, - VkImageView const depthView ) - : commandPool{ commandPool } - , commandBuffer{ commandBuffer } - , imageAcquiredSemaphore{ imageAcquiredSemaphore } - , renderFinishedSemaphore{ renderFinishedSemaphore } - , frameReadyToReuse{ frameReadyToReuse } - , depthImage{ depthImage } - , depthAllocation{ depthAllocation } - , depthView{ depthView } + VkCommandPool const command_pool, + VkCommandBuffer const command_buffer, + VkSemaphore const image_acquired_semaphore, + VkSemaphore const render_finished_semaphore, + VkFence const frame_ready_to_reuse, + VkImage const depth_image, + VmaAllocation const depth_allocation, + VkImageView const depth_view ) + : commandPool{ command_pool } + , commandBuffer{ command_buffer } + , imageAcquiredSemaphore{ image_acquired_semaphore } + , renderFinishedSemaphore{ render_finished_semaphore } + , frameReadyToReuse{ frame_ready_to_reuse } + , depthImage{ depth_image } + , depthAllocation{ depth_allocation } + , depthView{ depth_view } {} -void Frame::destroy( RenderDevice const& renderDevice ) +void Frame::Destroy( RenderDevice const& render_device ) { - if ( !isInit() ) return; + if ( !IsInit() ) return; - VkDevice const device = renderDevice.device; + VkDevice const device = render_device.device; vkDestroyImageView( device, Take( depthView ), nullptr ); - vmaDestroyImage( renderDevice.gpuAllocator, Take( depthImage ), Take( depthAllocation ) ); + vmaDestroyImage( render_device.gpuAllocator, Take( depthImage ), Take( depthAllocation ) ); vkDestroyCommandPool( device, Take( commandPool ), nullptr ); vkDestroyFence( device, Take( frameReadyToReuse ), nullptr ); @@ -44,71 +46,64 @@ void Frame::destroy( RenderDevice const& renderDevice ) vkDestroySemaphore( device, Take( renderFinishedSemaphore ), nullptr ); } -Frame::~Frame() +Frame Frame::Create( + VkDevice const device, + VmaAllocator const gpu_allocator, + uint32_t const direct_queue_family_index, + VkExtent2D const swapchain_extent ) { - // Manual Cleanup Required. - ASSERT( !isInit() ); -} + VkCommandPool command_pool; + VkCommandBuffer command_buffer; + VkSemaphore image_acquired_semaphore; + VkSemaphore render_finished_semaphore; + VkFence frame_ready_to_reuse; -void Frame_Create( - Frame* frame, - VkDevice const device, - VmaAllocator const gpuAllocator, - uint32_t const directQueueFamilyIndex, - VkExtent2D const swapchainExtent ) -{ - VkCommandPool commandPool; - VkCommandBuffer commandBuffer; - VkSemaphore imageAcquiredSemaphore; - VkSemaphore renderFinishedSemaphore; - VkFence frameReadyToReuse; - - VkImage depthImage; - VmaAllocation depthAllocation; - VkImageView depthView; + VkImage depth_image; + VmaAllocation depth_allocation; + VkImageView depth_view; { - VkCommandPoolCreateInfo const commandPoolCreateInfo = { + VkCommandPoolCreateInfo const command_pool_create_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, .pNext = nullptr, .flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, - .queueFamilyIndex = directQueueFamilyIndex, + .queueFamilyIndex = direct_queue_family_index, }; - VK_CHECK( vkCreateCommandPool( device, &commandPoolCreateInfo, nullptr, &commandPool ) ); + VK_CHECK( vkCreateCommandPool( device, &command_pool_create_info, nullptr, &command_pool ) ); - VkCommandBufferAllocateInfo const commandBufferAllocateInfo = { + VkCommandBufferAllocateInfo const command_buffer_allocate_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .pNext = nullptr, - .commandPool = commandPool, + .commandPool = command_pool, .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = 1, }; - VK_CHECK( vkAllocateCommandBuffers( device, &commandBufferAllocateInfo, &commandBuffer ) ); + VK_CHECK( vkAllocateCommandBuffers( device, &command_buffer_allocate_info, &command_buffer ) ); - VkSemaphoreCreateInfo constexpr semaphoreCreateInfo = { + VkSemaphoreCreateInfo constexpr semaphore_create_info = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, .pNext = nullptr, .flags = 0, }; - VK_CHECK( vkCreateSemaphore( device, &semaphoreCreateInfo, nullptr, &imageAcquiredSemaphore ) ); - VK_CHECK( vkCreateSemaphore( device, &semaphoreCreateInfo, nullptr, &renderFinishedSemaphore ) ); + VK_CHECK( vkCreateSemaphore( device, &semaphore_create_info, nullptr, &image_acquired_semaphore ) ); + VK_CHECK( vkCreateSemaphore( device, &semaphore_create_info, nullptr, &render_finished_semaphore ) ); - VkFenceCreateInfo constexpr fenceCreateInfo = { + VkFenceCreateInfo constexpr fence_create_info = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = nullptr, .flags = VK_FENCE_CREATE_SIGNALED_BIT, }; - VK_CHECK( vkCreateFence( device, &fenceCreateInfo, nullptr, &frameReadyToReuse ) ); + VK_CHECK( vkCreateFence( device, &fence_create_info, nullptr, &frame_ready_to_reuse ) ); } { - VkImageCreateInfo const depthImageCreateInfo = { + VkImageCreateInfo const depth_image_create_info = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = nullptr, .flags = 0, .imageType = VK_IMAGE_TYPE_2D, .format = VK_FORMAT_D32_SFLOAT, - .extent = { swapchainExtent.width, swapchainExtent.height, 1 }, + .extent = { swapchain_extent.width, swapchain_extent.height, 1 }, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, @@ -120,7 +115,7 @@ void Frame_Create( .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED }; - VmaAllocationCreateInfo constexpr depthAllocationCreateInfo = { + VmaAllocationCreateInfo constexpr depth_allocation_create_info = { .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, .usage = VMA_MEMORY_USAGE_GPU_ONLY, .requiredFlags = 0, @@ -132,9 +127,14 @@ void Frame_Create( }; VK_CHECK( vmaCreateImage( - gpuAllocator, &depthImageCreateInfo, &depthAllocationCreateInfo, &depthImage, &depthAllocation, nullptr ) ); + gpu_allocator, + &depth_image_create_info, + &depth_allocation_create_info, + &depth_image, + &depth_allocation, + nullptr ) ); - VkImageSubresourceRange constexpr subresourceRange = { + VkImageSubresourceRange constexpr subresource_range = { .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, @@ -142,33 +142,35 @@ void Frame_Create( .layerCount = 1, }; - VkComponentMapping constexpr componentMapping = { + VkComponentMapping constexpr component_mapping = { .r = VK_COMPONENT_SWIZZLE_IDENTITY, .g = VK_COMPONENT_SWIZZLE_IDENTITY, .b = VK_COMPONENT_SWIZZLE_IDENTITY, .a = VK_COMPONENT_SWIZZLE_IDENTITY, }; - VkImageViewCreateInfo const imageViewCreateInfo = { + VkImageViewCreateInfo const image_view_create_info = { .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .pNext = nullptr, .flags = 0, - .image = depthImage, + .image = depth_image, .viewType = VK_IMAGE_VIEW_TYPE_2D, - .format = depthImageCreateInfo.format, - .components = componentMapping, - .subresourceRange = subresourceRange, + .format = depth_image_create_info.format, + .components = component_mapping, + .subresourceRange = subresource_range, }; - VK_CHECK( vkCreateImageView( device, &imageViewCreateInfo, nullptr, &depthView ) ); + VK_CHECK( vkCreateImageView( device, &image_view_create_info, nullptr, &depth_view ) ); } - frame->commandPool = commandPool; - frame->commandBuffer = commandBuffer; - frame->imageAcquiredSemaphore = imageAcquiredSemaphore; - frame->renderFinishedSemaphore = renderFinishedSemaphore; - frame->frameReadyToReuse = frameReadyToReuse; - frame->depthImage = depthImage; - frame->depthView = depthView; - frame->depthAllocation = depthAllocation; + return Frame{ + command_pool, + command_buffer, + image_acquired_semaphore, + render_finished_semaphore, + frame_ready_to_reuse, + depth_image, + depth_allocation, + depth_view, + }; } diff --git a/Blaze/Source/Frame.h b/Blaze/Source/Frame.h index 38cebd4..4a4d518 100644 --- a/Blaze/Source/Frame.h +++ b/Blaze/Source/Frame.h @@ -1,9 +1,9 @@ #pragma once -#include - #include "VulkanHeader.h" +namespace Blaze +{ struct RenderDevice; struct Frame @@ -18,31 +18,22 @@ struct Frame VmaAllocation depthAllocation; VkImageView depthView; - [[nodiscard]] bool isInit() const; + [[nodiscard]] bool IsInit() const; Frame( - VkCommandPool commandPool, - VkCommandBuffer commandBuffer, - VkSemaphore imageAcquiredSemaphore, - VkSemaphore renderFinishedSemaphore, - VkFence frameReadyToReuse, - VkImage depthImage, - VmaAllocation depthAllocation, - VkImageView depthView ); + VkCommandPool command_pool, + VkCommandBuffer command_buffer, + VkSemaphore image_acquired_semaphore, + VkSemaphore render_finished_semaphore, + VkFence frame_ready_to_reuse, + VkImage depth_image, + VmaAllocation depth_allocation, + VkImageView depth_view ); - void destroy( RenderDevice const& renderDevice ); + static Frame Create( + VkDevice device, VmaAllocator gpu_allocator, uint32_t direct_queue_family_index, VkExtent2D swapchain_extent ); - Frame( Frame const& other ) = delete; - Frame( Frame&& other ) noexcept = delete; - Frame& operator=( Frame const& other ) = delete; - Frame& operator=( Frame&& other ) noexcept = delete; - - ~Frame(); + void Destroy( RenderDevice const& render_device ); }; -void Frame_Create( - Frame* frame, - VkDevice device, - VmaAllocator gpuAllocator, - uint32_t directQueueFamilyIndex, - VkExtent2D swapchainExtent ); +} // namespace Blaze diff --git a/Blaze/Source/FreeList.cpp b/Blaze/Source/FreeList.cpp index 4cea0a3..2633c51 100644 --- a/Blaze/Source/FreeList.cpp +++ b/Blaze/Source/FreeList.cpp @@ -1,72 +1,79 @@ #include "FreeList.h" +#include "MacroUtils.h" + +namespace Blaze::Util +{ + FreeList::Iterator& FreeList::Iterator::operator++() { - pIter = pIter->pNext; + iter = iter->next; return *this; } bool FreeList::Iterator::operator==( Iterator const& other ) const { - return this->pIter == other.pIter; + return this->iter == other.iter; } -FreeList::Node& FreeList::Iterator::operator*() +FreeList::Node& FreeList::Iterator::operator*() const { - return *pIter; + return *iter; } -FreeList::FreeList() : m_head{ .pNext = &m_tail, .pPrev = nullptr }, m_tail{ .pNext = nullptr, .pPrev = &m_head } +FreeList::FreeList() : m_head{ .next = &m_tail, .prev = nullptr }, m_tail{ .next = nullptr, .prev = &m_head } {} -void FreeList::pushBack( Node* pNode ) +void FreeList::PushBack( Node* node ) { - Node* prev = m_tail.pPrev; + Node* prev = m_tail.prev; - // Set prev as previous of pNode - prev->pNext = pNode; - pNode->pPrev = prev; + // Set prev as previous of node + prev->next = node; + node->prev = prev; - // Set tail as next of pNode - pNode->pNext = &m_tail; - m_tail.pPrev = pNode; + // Set tail as next of node + node->next = &m_tail; + m_tail.prev = node; } -void FreeList::pushFront( Node* pNode ) +void FreeList::PushFront( Node* node ) { - Node* next = m_head.pNext; + Node* next = m_head.next; - // Set next as next of pNode - next->pPrev = pNode; - pNode->pNext = next; + // Set next as next of node + next->prev = node; + node->next = next; - // Set head as prev of pNode - pNode->pPrev = &m_head; - m_head.pNext = pNode; + // Set head as prev of node + node->prev = &m_head; + m_head.next = node; } -FreeList::Node* FreeList::popFront() +FreeList::Node* FreeList::PopFront() { - ASSERT( not empty() ); + ASSERT( not Empty() ); - Node* element = m_head.pNext; - element->pPrev->pNext = element->pNext; - element->pNext->pPrev = element->pPrev; + Node* element = m_head.next; + m_head.next = element->next; + element->next->prev = &m_head; return element; } -bool FreeList::empty() const +bool FreeList::Empty() const { - return m_head.pNext == &m_tail; + return m_head.next == &m_tail; } FreeList::Iterator FreeList::begin() { - return { m_head.pNext }; + return { m_head.next }; } FreeList::Iterator FreeList::end() { return { &m_tail }; } + +} // namespace Blaze::Util diff --git a/Blaze/Source/FreeList.h b/Blaze/Source/FreeList.h index e7cd2e9..070427c 100644 --- a/Blaze/Source/FreeList.h +++ b/Blaze/Source/FreeList.h @@ -1,21 +1,23 @@ #pragma once -#include "MacroUtils.h" + +namespace Blaze::Util +{ struct FreeList { struct Node { - Node* pNext; - Node* pPrev; + Node* next; + Node* prev; }; struct Iterator { - Node* pIter; + Node* iter; Iterator& operator++(); bool operator==( Iterator const& other ) const; - Node& operator*(); + Node& operator*() const; }; private: @@ -25,10 +27,10 @@ private: public: FreeList(); - void pushBack( Node* pNode ); - void pushFront( Node* pNode ); - Node* popFront(); - [[nodiscard]] bool empty() const; + void PushBack( Node* node ); + void PushFront( Node* node ); + Node* PopFront(); + [[nodiscard]] bool Empty() const; Iterator begin(); Iterator end(); @@ -40,3 +42,5 @@ public: ~FreeList() = default; }; + +} // namespace Blaze::Util diff --git a/Blaze/Source/GlobalMemory.cpp b/Blaze/Source/GlobalMemory.cpp index bd13e10..96eb6c4 100644 --- a/Blaze/Source/GlobalMemory.cpp +++ b/Blaze/Source/GlobalMemory.cpp @@ -2,59 +2,62 @@ #include -void GlobalMemory::init( size_t const size ) +namespace Blaze +{ + +void GlobalMemory::Initialize( size_t const size ) { memory = new std::byte[size]; capacity = size; available = size; } -void GlobalMemory::destroy() +void GlobalMemory::Destroy() { - std::byte const* originalMemory = memory - ( capacity - available ); - delete[] originalMemory; + std::byte const* original_memory = memory - ( capacity - available ); + delete[] original_memory; memory = nullptr; available = 0; capacity = 0; } -std::byte* GlobalMemory::allocate( size_t const size ) +std::byte* GlobalMemory::Allocate( size_t const size ) { assert( size <= available && "No enough space available" ); - std::byte* retVal = memory; - memset( retVal, 0, size ); + std::byte* ret_val = memory; + memset( ret_val, 0, size ); memory += size; available -= size; SDL_LogInfo( - SDL_LOG_CATEGORY_SYSTEM, - "ALLOC: %p -> %p (%llu) (avail: %llu)", - reinterpret_cast( retVal ), - reinterpret_cast( memory ), - size, - available ); + SDL_LOG_CATEGORY_SYSTEM, + "ALLOC: %p -> %p (%llu) (avail: %llu)", + reinterpret_cast( ret_val ), + reinterpret_cast( memory ), + size, + available ); - return retVal; + return ret_val; } -std::byte* GlobalMemory::allocate( size_t const size, size_t const alignment ) +std::byte* GlobalMemory::Allocate( size_t const size, size_t const alignment ) { - uintptr_t const addr = reinterpret_cast( memory ); - uintptr_t const foundOffset = addr % alignment; + uintptr_t const addr = reinterpret_cast( memory ); + uintptr_t const found_offset = addr % alignment; - if ( foundOffset == 0 ) + if ( found_offset == 0 ) { - return allocate( size ); + return Allocate( size ); } - uintptr_t const offset = alignment - foundOffset; - size_t const allocationSize = size + offset; + uintptr_t const offset = alignment - found_offset; + size_t const allocation_size = size + offset; - return offset + allocate( allocationSize ); + return offset + Allocate( allocation_size ); } -GlobalMemory::State GlobalMemory::getState() const +GlobalMemory::State GlobalMemory::GetState() const { SDL_LogInfo( SDL_LOG_CATEGORY_SYSTEM, "TEMP: %p %llu", reinterpret_cast( memory ), available ); return { @@ -63,7 +66,7 @@ GlobalMemory::State GlobalMemory::getState() const }; } -void GlobalMemory::restoreState( State const& state ) +void GlobalMemory::RestoreState( State const& state ) { ASSERT( memory >= state.memory ); //< Behind top of allocator ASSERT( memory - ( capacity - available ) <= state.memory ); //< Ahead of start of allocator @@ -71,3 +74,5 @@ void GlobalMemory::restoreState( State const& state ) memory = state.memory; available = state.available; } + +} // namespace Blaze diff --git a/Blaze/Source/GlobalMemory.h b/Blaze/Source/GlobalMemory.h index 59871cb..7e0d438 100644 --- a/Blaze/Source/GlobalMemory.h +++ b/Blaze/Source/GlobalMemory.h @@ -1,9 +1,9 @@ #pragma once -#include - #include "MacroUtils.h" +namespace Blaze +{ consteval size_t operator""_KiB( size_t const value ) { return value * 1024; @@ -19,27 +19,30 @@ consteval size_t operator""_GiB( size_t const value ) return value * 1024_MiB; } +using byte = std::byte; + struct GlobalMemory { struct State { - std::byte* memory; - size_t available; + byte* memory; + size_t available; }; - std::byte* memory; - size_t available; - size_t capacity; + byte* memory; + size_t available; + size_t capacity; - void init( size_t size ); - void destroy(); + void Initialize( size_t size ); + void Destroy(); [[nodiscard]] - std::byte* allocate( size_t size ); + byte* Allocate( size_t size ); [[nodiscard]] - std::byte* allocate( size_t size, size_t alignment ); + byte* Allocate( size_t size, size_t alignment ); [[nodiscard]] - State getState() const; //< Do not do any permanent allocations after calling this. - void restoreState( State const& state ); //< Call this before permanent allocations. + State GetState() const; //< Do not do any permanent allocations after calling this. + void RestoreState( State const& state ); //< Call this before permanent allocations. }; +} // namespace Blaze diff --git a/Blaze/Source/MathUtil.h b/Blaze/Source/MathUtil.h deleted file mode 100644 index 4606f8d..0000000 --- a/Blaze/Source/MathUtil.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include - -using byte = std::byte; - -template -T Clamp( T const val, T const minVal, T const maxVal ) -{ - return std::min( maxVal, std::max( val, minVal ) ); -} diff --git a/Blaze/Source/MiscData.cpp b/Blaze/Source/MiscData.cpp index b176a92..f0203de 100644 --- a/Blaze/Source/MiscData.cpp +++ b/Blaze/Source/MiscData.cpp @@ -1,7 +1,6 @@ #include "MiscData.h" #include -#include #include @@ -9,38 +8,41 @@ #include "MacroUtils.h" #include "RenderDevice.h" -bool MiscData::init( RenderDevice const& renderDevice ) +namespace Blaze { - VkDevice const device = renderDevice.device; + +bool MiscData::Init( RenderDevice const& render_device ) +{ + VkDevice const device = render_device.device; previousCounter = 0; // Pipeline Creation { - size_t dataSize; - void* rawData = SDL_LoadFile( "Mesh.spv", &dataSize ); - ASSERT( dataSize % 4 == 0 ); + size_t data_size; + void* raw_data = SDL_LoadFile( "Mesh.spv", &data_size ); + ASSERT( data_size % 4 == 0 ); - if ( !rawData ) + if ( !raw_data ) { SDL_LogError( SDL_LOG_CATEGORY_SYSTEM, "%s", SDL_GetError() ); return false; } - uint32_t const* data = static_cast( rawData ); + uint32_t const* data = static_cast( raw_data ); // Create Shader Module - VkShaderModuleCreateInfo const shaderModuleCreateInfo = { + VkShaderModuleCreateInfo const shader_module_create_info = { .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .pNext = nullptr, .flags = 0, - .codeSize = dataSize, + .codeSize = data_size, .pCode = data, }; - VkShaderModule shaderModule; - VK_CHECK( vkCreateShaderModule( device, &shaderModuleCreateInfo, nullptr, &shaderModule ) ); + VkShaderModule shader_module; + VK_CHECK( vkCreateShaderModule( device, &shader_module_create_info, nullptr, &shader_module ) ); - VkDescriptorSetLayoutBinding constexpr perFrameDescriptorBinding{ + VkDescriptorSetLayoutBinding constexpr per_frame_descriptor_binding{ .binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .descriptorCount = 1, @@ -48,116 +50,86 @@ bool MiscData::init( RenderDevice const& renderDevice ) .pImmutableSamplers = nullptr, }; - VkDescriptorSetLayoutCreateInfo perFrameDescriptorSetLayoutCreateInfo = { + VkDescriptorSetLayoutCreateInfo per_frame_descriptor_set_layout_create_info{ .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .pNext = nullptr, .flags = 0, .bindingCount = 1, - .pBindings = &perFrameDescriptorBinding, + .pBindings = &per_frame_descriptor_binding, }; - VK_CHECK( - vkCreateDescriptorSetLayout( device, &perFrameDescriptorSetLayoutCreateInfo, nullptr, &descriptorSetLayout ) ); + VK_CHECK( vkCreateDescriptorSetLayout( + device, &per_frame_descriptor_set_layout_create_info, nullptr, &descriptorSetLayout ) ); - VkPushConstantRange const pushConstantRange = { + VkPushConstantRange constexpr push_constant_range{ .stageFlags = VK_SHADER_STAGE_ALL_GRAPHICS, .offset = 0, - .size = 2 * sizeof( DirectX::XMMATRIX ) + Material::GPU_DATA_SIZE, + .size = 2 * sizeof( DirectX::XMMATRIX ) + Material::kGPUDataSize, }; - std::array const descriptorSetLayouts = { - renderDevice.textureManager->descriptorLayout(), + VkDescriptorSetLayout const descriptor_set_layouts[] = { + render_device.textureManager->DescriptorLayout(), descriptorSetLayout, }; - VkPipelineLayoutCreateInfo const pipelineLayoutCreateInfo = { + VkPipelineLayoutCreateInfo const pipeline_layout_create_info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .pNext = nullptr, .flags = 0, - .setLayoutCount = static_cast( descriptorSetLayouts.size() ), - .pSetLayouts = descriptorSetLayouts.data(), + .setLayoutCount = _countof( descriptor_set_layouts ), + .pSetLayouts = descriptor_set_layouts, .pushConstantRangeCount = 1, - .pPushConstantRanges = &pushConstantRange, + .pPushConstantRanges = &push_constant_range, }; - VK_CHECK( vkCreatePipelineLayout( device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout ) ); + VK_CHECK( vkCreatePipelineLayout( device, &pipeline_layout_create_info, nullptr, &pipelineLayout ) ); - std::array stages = { - VkPipelineShaderStageCreateInfo{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .stage = VK_SHADER_STAGE_VERTEX_BIT, - .module = shaderModule, - .pName = "VertexMain", - .pSpecializationInfo = nullptr, - }, - VkPipelineShaderStageCreateInfo{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .stage = VK_SHADER_STAGE_FRAGMENT_BIT, - .module = shaderModule, - .pName = "FragmentMain", - .pSpecializationInfo = nullptr, - } + VkPipelineShaderStageCreateInfo stages[] = { + { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .stage = VK_SHADER_STAGE_VERTEX_BIT, + .module = shader_module, + .pName = "VertexMain", + .pSpecializationInfo = nullptr, + }, + { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .module = shader_module, + .pName = "FragmentMain", + .pSpecializationInfo = nullptr, + } }; // Bindings - VkVertexInputBindingDescription constexpr bindingDescription = { + VkVertexInputBindingDescription constexpr binding_description = { .binding = 0, .stride = sizeof( Vertex ), .inputRate = VK_VERTEX_INPUT_RATE_VERTEX, }; - std::array attributeDescriptions = { - VkVertexInputAttributeDescription{ - .location = 0, - .binding = 0, - .format = VK_FORMAT_R32G32B32_SFLOAT, - .offset = offsetof( Vertex, position ), - }, - VkVertexInputAttributeDescription{ - .location = 1, - .binding = 0, - .format = VK_FORMAT_R32G32B32_SFLOAT, - .offset = offsetof( Vertex, normal ), - }, - VkVertexInputAttributeDescription{ - .location = 2, - .binding = 0, - .format = VK_FORMAT_R32G32B32A32_SFLOAT, - .offset = offsetof( Vertex, tangent ), - }, - VkVertexInputAttributeDescription{ - .location = 3, - .binding = 0, - .format = VK_FORMAT_R32G32_SFLOAT, - .offset = offsetof( Vertex, texCoord0 ), - }, - VkVertexInputAttributeDescription{ - .location = 4, - .binding = 0, - .format = VK_FORMAT_R32G32_SFLOAT, - .offset = offsetof( Vertex, texCoord1 ), - }, - VkVertexInputAttributeDescription{ - .location = 5, - .binding = 0, - .format = VK_FORMAT_R32G32B32A32_SFLOAT, - .offset = offsetof( Vertex, color0 ), - }, + VkVertexInputAttributeDescription attribute_descriptions[] = { + {.location = 0, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof( Vertex, position ) }, + {.location = 1, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof( Vertex, normal ) }, + {.location = 2, .binding = 0, .format = VK_FORMAT_R32G32B32A32_SFLOAT, .offset = offsetof( Vertex, tangent ) }, + {.location = 3, .binding = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof( Vertex, texCoord0 )}, + {.location = 4, .binding = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof( Vertex, texCoord1 )}, + {.location = 5, .binding = 0, .format = VK_FORMAT_R32G32B32A32_SFLOAT, .offset = offsetof( Vertex, color0 ) }, }; - VkPipelineVertexInputStateCreateInfo const vertexInputState = { + VkPipelineVertexInputStateCreateInfo const vertex_input_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, .vertexBindingDescriptionCount = 1, - .pVertexBindingDescriptions = &bindingDescription, - .vertexAttributeDescriptionCount = static_cast( attributeDescriptions.size() ), - .pVertexAttributeDescriptions = attributeDescriptions.data(), + .pVertexBindingDescriptions = &binding_description, + .vertexAttributeDescriptionCount = _countof( attribute_descriptions ), + .pVertexAttributeDescriptions = attribute_descriptions, }; - VkPipelineInputAssemblyStateCreateInfo constexpr inputAssembly = { + VkPipelineInputAssemblyStateCreateInfo const input_assembly = { .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -165,14 +137,14 @@ bool MiscData::init( RenderDevice const& renderDevice ) .primitiveRestartEnable = VK_FALSE, }; - VkPipelineTessellationStateCreateInfo constexpr tessellationState = { + VkPipelineTessellationStateCreateInfo constexpr tessellation_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, .patchControlPoints = 0, }; - VkPipelineViewportStateCreateInfo constexpr viewportState = { + VkPipelineViewportStateCreateInfo constexpr viewport_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -182,7 +154,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) .pScissors = nullptr, }; - VkPipelineRasterizationStateCreateInfo constexpr rasterizationState = { + VkPipelineRasterizationStateCreateInfo constexpr rasterization_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -198,7 +170,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) .lineWidth = 1.0f, }; - VkPipelineMultisampleStateCreateInfo constexpr multisampleState = { + VkPipelineMultisampleStateCreateInfo constexpr multisample_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -210,7 +182,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) .alphaToOneEnable = VK_FALSE, }; - VkPipelineDepthStencilStateCreateInfo constexpr depthStencilState = { + VkPipelineDepthStencilStateCreateInfo constexpr depth_stencil_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -225,7 +197,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) .maxDepthBounds = 1.0f, }; - VkPipelineColorBlendAttachmentState constexpr colorBlendAttachmentState = { + VkPipelineColorBlendAttachmentState constexpr color_blend_attachment_state = { .blendEnable = VK_FALSE, .srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA, .dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, @@ -234,52 +206,52 @@ bool MiscData::init( RenderDevice const& renderDevice ) .dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO, .alphaBlendOp = VK_BLEND_OP_ADD, .colorWriteMask = - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, }; - VkPipelineColorBlendStateCreateInfo const colorBlendState = { + VkPipelineColorBlendStateCreateInfo const color_blend_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, .logicOpEnable = VK_FALSE, .logicOp = VK_LOGIC_OP_COPY, .attachmentCount = 1, - .pAttachments = &colorBlendAttachmentState, + .pAttachments = &color_blend_attachment_state, .blendConstants = { 0.0f, 0.0f, 0.0f, 0.0f }, }; - std::array constexpr dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; + VkDynamicState constexpr dynamic_states[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; - VkPipelineDynamicStateCreateInfo const dynamicStateCreateInfo = { + VkPipelineDynamicStateCreateInfo const dynamic_state_create_info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, .pNext = nullptr, .flags = 0, - .dynamicStateCount = static_cast( dynamicStates.size() ), - .pDynamicStates = dynamicStates.data() + .dynamicStateCount = _countof( dynamic_states ), + .pDynamicStates = dynamic_states, }; - VkPipelineRenderingCreateInfoKHR const renderingCreateInfo = { + VkPipelineRenderingCreateInfoKHR const rendering_create_info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO_KHR, .colorAttachmentCount = 1, - .pColorAttachmentFormats = &renderDevice.swapchainFormat, + .pColorAttachmentFormats = &render_device.swapchainFormat, .depthAttachmentFormat = VK_FORMAT_D32_SFLOAT, }; - VkGraphicsPipelineCreateInfo const graphicsPipelineCreateInfo = { + VkGraphicsPipelineCreateInfo const graphics_pipeline_create_info = { .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, - .pNext = &renderingCreateInfo, + .pNext = &rendering_create_info, .flags = 0, - .stageCount = static_cast( stages.size() ), - .pStages = stages.data(), - .pVertexInputState = &vertexInputState, - .pInputAssemblyState = &inputAssembly, - .pTessellationState = &tessellationState, - .pViewportState = &viewportState, - .pRasterizationState = &rasterizationState, - .pMultisampleState = &multisampleState, - .pDepthStencilState = &depthStencilState, - .pColorBlendState = &colorBlendState, - .pDynamicState = &dynamicStateCreateInfo, + .stageCount = _countof( stages ), + .pStages = stages, + .pVertexInputState = &vertex_input_state, + .pInputAssemblyState = &input_assembly, + .pTessellationState = &tessellation_state, + .pViewportState = &viewport_state, + .pRasterizationState = &rasterization_state, + .pMultisampleState = &multisample_state, + .pDepthStencilState = &depth_stencil_state, + .pColorBlendState = &color_blend_state, + .pDynamicState = &dynamic_state_create_info, .layout = pipelineLayout, .renderPass = nullptr, .subpass = 0, @@ -287,11 +259,11 @@ bool MiscData::init( RenderDevice const& renderDevice ) .basePipelineIndex = 0, }; - VK_CHECK( vkCreateGraphicsPipelines( device, nullptr, 1, &graphicsPipelineCreateInfo, nullptr, &meshPipeline ) ); + VK_CHECK( vkCreateGraphicsPipelines( device, nullptr, 1, &graphics_pipeline_create_info, nullptr, &meshPipeline ) ); - vkDestroyShaderModule( device, shaderModule, nullptr ); + vkDestroyShaderModule( device, shader_module, nullptr ); - SDL_free( rawData ); + SDL_free( raw_data ); } // Camera @@ -301,7 +273,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) cameraUp = DirectX::XMVectorSet( 0.0f, 1.0f, 0.0f, 1.0f ); cameraData.viewMatrix = DirectX::XMMatrixLookAtLH( cameraData.cameraPosition, cameraTarget, cameraUp ); cameraData.projectionMatrix = - DirectX::XMMatrixPerspectiveFovLH( DirectX::XMConvertToRadians( 70.0f ), 16.0f / 9.0f, 0.1f, 1000.0f ); + DirectX::XMMatrixPerspectiveFovLH( DirectX::XMConvertToRadians( 70.0f ), 16.0f / 9.0f, 0.1f, 1000.0f ); cameraUniformBufferSize = sizeof( CameraData ) + sizeof( LightData ); } @@ -309,14 +281,14 @@ bool MiscData::init( RenderDevice const& renderDevice ) // Lights { - pointLights = renderDevice.bufferManager->createStorageBuffer( 10 * sizeof( PointLight ) ); + pointLights = render_device.bufferManager->CreateStorageBuffer( 10 * sizeof( PointLight ) ); if ( not pointLights ) return false; - directionalLights = renderDevice.bufferManager->createStorageBuffer( 10 * sizeof( DirectionalLight ) ); + directionalLights = render_device.bufferManager->CreateStorageBuffer( 10 * sizeof( DirectionalLight ) ); if ( not directionalLights ) return false; - lightData.pointLights = renderDevice.bufferManager->fetchDeviceAddress( pointLights ).value(); - lightData.directionalLights = renderDevice.bufferManager->fetchDeviceAddress( directionalLights ).value(); + lightData.pointLights = render_device.bufferManager->FetchDeviceAddress( pointLights ).value(); + lightData.directionalLights = render_device.bufferManager->FetchDeviceAddress( directionalLights ).value(); lightData.dirLightCount = 0; lightData.pointLightCount = 0; } @@ -324,7 +296,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) // Uniform Buffer { - VkBufferCreateInfo const bufferCreateInfo = { + VkBufferCreateInfo const buffer_create_info = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -335,7 +307,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) .pQueueFamilyIndices = nullptr, }; - VmaAllocationCreateInfo constexpr allocationCreateInfo = { + VmaAllocationCreateInfo constexpr allocation_create_info = { .flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, .usage = VMA_MEMORY_USAGE_AUTO, .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, @@ -346,19 +318,19 @@ bool MiscData::init( RenderDevice const& renderDevice ) .priority = 1.0f, }; - VmaAllocationInfo allocationInfo; + VmaAllocationInfo allocation_info; VK_CHECK( vmaCreateBuffer( - renderDevice.gpuAllocator, - &bufferCreateInfo, - &allocationCreateInfo, - &cameraUniformBuffer, - &cameraUniformBufferAllocation, - &allocationInfo ) ); + render_device.gpuAllocator, + &buffer_create_info, + &allocation_create_info, + &cameraUniformBuffer, + &cameraUniformBufferAllocation, + &allocation_info ) ); - if ( allocationInfo.pMappedData ) + if ( allocation_info.pMappedData ) { - cameraUniformBufferPtr = static_cast( allocationInfo.pMappedData ); + cameraUniformBufferPtr = static_cast( allocation_info.pMappedData ); memcpy( cameraUniformBufferPtr, &cameraData, sizeof cameraData ); memcpy( cameraUniformBufferPtr + sizeof cameraData, &lightData, sizeof lightData ); } @@ -366,28 +338,22 @@ bool MiscData::init( RenderDevice const& renderDevice ) // Descriptors { - std::array poolSizes = { - VkDescriptorPoolSize{ - .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - .descriptorCount = 3, - }, - VkDescriptorPoolSize{ - .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - .descriptorCount = 100, - }, + VkDescriptorPoolSize pool_sizes[] = { + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3 }, + {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 100}, }; - VkDescriptorPoolCreateInfo const descriptorPoolCreateInfo = { + VkDescriptorPoolCreateInfo const descriptor_pool_create_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .pNext = nullptr, .flags = 0, .maxSets = 101, - .poolSizeCount = static_cast( poolSizes.size() ), - .pPoolSizes = poolSizes.data(), + .poolSizeCount = _countof( pool_sizes ), + .pPoolSizes = pool_sizes, }; - VK_CHECK( vkCreateDescriptorPool( device, &descriptorPoolCreateInfo, nullptr, &descriptorPool ) ); + VK_CHECK( vkCreateDescriptorPool( device, &descriptor_pool_create_info, nullptr, &descriptorPool ) ); - VkDescriptorSetAllocateInfo const descriptorSetAllocateInfo = { + VkDescriptorSetAllocateInfo const descriptor_set_allocate_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .pNext = nullptr, .descriptorPool = descriptorPool, @@ -395,36 +361,35 @@ bool MiscData::init( RenderDevice const& renderDevice ) .pSetLayouts = &descriptorSetLayout, }; - VK_CHECK( vkAllocateDescriptorSets( device, &descriptorSetAllocateInfo, &descriptorSet ) ); + VK_CHECK( vkAllocateDescriptorSets( device, &descriptor_set_allocate_info, &descriptorSet ) ); - VkDescriptorBufferInfo const descriptorBufferInfo = { + VkDescriptorBufferInfo const descriptor_buffer_info = { .buffer = cameraUniformBuffer, .offset = 0, .range = cameraUniformBufferSize, }; - std::array writeDescriptorSets = { - VkWriteDescriptorSet{ - .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, - .pNext = nullptr, - .dstSet = descriptorSet, - .dstBinding = 0, - .dstArrayElement = 0, - .descriptorCount = 1, - .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - .pImageInfo = nullptr, - .pBufferInfo = &descriptorBufferInfo, - .pTexelBufferView = nullptr, - }, + VkWriteDescriptorSet write_descriptor_sets[] = { + { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .pNext = nullptr, + .dstSet = descriptorSet, + .dstBinding = 0, + .dstArrayElement = 0, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + .pImageInfo = nullptr, + .pBufferInfo = &descriptor_buffer_info, + .pTexelBufferView = nullptr, + }, }; - vkUpdateDescriptorSets( - device, static_cast( writeDescriptorSets.size() ), writeDescriptorSets.data(), 0, nullptr ); + vkUpdateDescriptorSets( device, _countof( write_descriptor_sets ), write_descriptor_sets, 0, nullptr ); } // Barrier Creation { - VkImageSubresourceRange subresourceRange = { + VkImageSubresourceRange subresource_range = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, @@ -443,7 +408,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) .newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .subresourceRange = subresourceRange, + .subresourceRange = subresource_range, }; acquireToRenderDependency = { @@ -469,7 +434,7 @@ bool MiscData::init( RenderDevice const& renderDevice ) .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .subresourceRange = subresourceRange, + .subresourceRange = subresource_range, }; renderToPresentDependency = { @@ -494,17 +459,18 @@ bool MiscData::init( RenderDevice const& renderDevice ) return true; } -void MiscData::destroy( RenderDevice const& renderDevice ) +void MiscData::Destroy( Blaze::RenderDevice const& render_device ) { - VkDevice const device = renderDevice.device; + VkDevice const device = render_device.device; vkDestroyDescriptorPool( device, Take( descriptorPool ), nullptr ); - vmaDestroyBuffer( renderDevice.gpuAllocator, Take( cameraUniformBuffer ), Take( cameraUniformBufferAllocation ) ); + vmaDestroyBuffer( render_device.gpuAllocator, Take( cameraUniformBuffer ), Take( cameraUniformBufferAllocation ) ); - renderDevice.bufferManager->freeBuffer( &pointLights ); - renderDevice.bufferManager->freeBuffer( &directionalLights ); + render_device.bufferManager->FreeBuffer( &pointLights ); + render_device.bufferManager->FreeBuffer( &directionalLights ); vkDestroyPipeline( device, Take( meshPipeline ), nullptr ); vkDestroyPipelineLayout( device, Take( pipelineLayout ), nullptr ); vkDestroyDescriptorSetLayout( device, Take( descriptorSetLayout ), nullptr ); } +} // namespace Blaze diff --git a/Blaze/Source/MiscData.h b/Blaze/Source/MiscData.h index 4eed027..beff216 100644 --- a/Blaze/Source/MiscData.h +++ b/Blaze/Source/MiscData.h @@ -1,13 +1,13 @@ #pragma once -#include - #include "VulkanHeader.h" #include #include "BufferManager.h" +namespace Blaze +{ struct GlobalMemory; struct RenderDevice; @@ -31,9 +31,9 @@ struct MiscData struct DirectionalLight { DirectX::XMFLOAT3 direction; - float _padding0; + float padding0; DirectX::XMFLOAT3 color; - float _padding1; + float padding1; }; struct LightData @@ -75,6 +75,7 @@ struct MiscData uint8_t frameTimeWriteHead; uint8_t frameTimeEntryCount; - bool init( RenderDevice const& renderDevice ); - void destroy( RenderDevice const& renderDevice ); + bool Init( RenderDevice const& render_device ); + void Destroy( RenderDevice const& render_device ); }; +} // namespace Blaze diff --git a/Blaze/Source/ModelLoader.cpp b/Blaze/Source/ModelLoader.cpp index 16b5a1d..7600266 100644 --- a/Blaze/Source/ModelLoader.cpp +++ b/Blaze/Source/ModelLoader.cpp @@ -1,7 +1,6 @@ #include "ModelLoader.h" #include -#include #include #include @@ -14,37 +13,39 @@ #include "Frame.h" #include "GlobalMemory.h" #include "MacroUtils.h" -#include "MathUtil.h" + +namespace Blaze +{ std::optional LoadTexture( - RenderDevice* renderDevice, VkSampler sampler, cgltf_image const& baseColorImage, bool const linear ) + RenderDevice* render_device, VkSampler sampler, cgltf_image const& image, bool const linear ) { byte* data; - if ( baseColorImage.buffer_view->data ) + if ( image.buffer_view->data ) { - data = static_cast( baseColorImage.buffer_view->data ); + data = static_cast( image.buffer_view->data ); } else { - data = static_cast( baseColorImage.buffer_view->buffer->data ) + baseColorImage.buffer_view->offset; + data = static_cast( image.buffer_view->buffer->data ) + image.buffer_view->offset; } - size_t size = baseColorImage.buffer_view->size; + size_t size = image.buffer_view->size; uint32_t width; uint32_t height; - uint32_t numChannels = 4; - stbi_uc* textureData; + uint32_t num_channels = 4; + stbi_uc* texture_data; { int w; int h; int nc; - int requestedChannels = static_cast( numChannels ); + int n_req_channels = static_cast( num_channels ); - textureData = stbi_load_from_memory( - reinterpret_cast( data ), static_cast( size ), &w, &h, &nc, requestedChannels ); - ASSERT( nc <= requestedChannels ); + texture_data = stbi_load_from_memory( + reinterpret_cast( data ), static_cast( size ), &w, &h, &nc, n_req_channels ); + ASSERT( nc <= n_req_channels ); - if ( not textureData ) + if ( not texture_data ) { return std::nullopt; } @@ -53,31 +54,31 @@ std::optional LoadTexture( height = static_cast( h ); } - TextureID texture = renderDevice->textureManager->createTexture( - { width, height, 1 }, sampler, linear ? VK_FORMAT_R8G8B8A8_UNORM : VK_FORMAT_R8G8B8A8_SRGB ); + TextureID texture = render_device->textureManager->CreateTexture( + { width, height, 1 }, sampler, linear ? VK_FORMAT_R8G8B8A8_UNORM : VK_FORMAT_R8G8B8A8_SRGB ); if ( not texture ) { return std::nullopt; } - VkImage textureImage = renderDevice->textureManager->fetchImage( texture ).value(); + VkImage texture_image = render_device->textureManager->FetchImage( texture ).value(); // Staging Buffer Create - VkBuffer stagingBuffer; - VmaAllocation stagingAllocation; + VkBuffer staging_buffer; + VmaAllocation staging_allocation; { - VkBufferCreateInfo const stagingBufferCreateInfo = { + VkBufferCreateInfo const staging_buffer_create_info = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .pNext = nullptr, .flags = 0, - .size = static_cast( width ) * height * numChannels * sizeof( textureData[0] ), + .size = static_cast( width ) * height * num_channels * sizeof( texture_data[0] ), .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .queueFamilyIndexCount = 0, .pQueueFamilyIndices = nullptr, }; - VmaAllocationCreateInfo constexpr stagingAllocationCreateInfo = { + VmaAllocationCreateInfo constexpr staging_allocation_create_info = { .flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, .usage = VMA_MEMORY_USAGE_AUTO, .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, @@ -88,54 +89,54 @@ std::optional LoadTexture( .priority = 1.0f, }; - VmaAllocationInfo allocationInfo; + VmaAllocationInfo allocation_info; VK_CHECK( vmaCreateBuffer( - renderDevice->gpuAllocator, - &stagingBufferCreateInfo, - &stagingAllocationCreateInfo, - &stagingBuffer, - &stagingAllocation, - &allocationInfo ) ); + render_device->gpuAllocator, + &staging_buffer_create_info, + &staging_allocation_create_info, + &staging_buffer, + &staging_allocation, + &allocation_info ) ); - if ( allocationInfo.pMappedData ) + if ( allocation_info.pMappedData ) { - memcpy( allocationInfo.pMappedData, textureData, stagingBufferCreateInfo.size ); + memcpy( allocation_info.pMappedData, texture_data, staging_buffer_create_info.size ); } } // All data is copied to stagingBuffer, don't need this. - stbi_image_free( textureData ); + stbi_image_free( texture_data ); // Staging -> Texture transfer { - Frame& frameInUse = renderDevice->frames[renderDevice->frameIndex]; + Frame& frame_in_use = render_device->frames[render_device->frameIndex]; // This should just pass. - VK_CHECK( vkWaitForFences( renderDevice->device, 1, &frameInUse.frameReadyToReuse, VK_TRUE, INT64_MAX ) ); + VK_CHECK( vkWaitForFences( render_device->device, 1, &frame_in_use.frameReadyToReuse, VK_TRUE, INT64_MAX ) ); // Reset Frame - VK_CHECK( vkResetFences( renderDevice->device, 1, &frameInUse.frameReadyToReuse ) ); - VK_CHECK( vkResetCommandPool( renderDevice->device, frameInUse.commandPool, 0 ) ); + VK_CHECK( vkResetFences( render_device->device, 1, &frame_in_use.frameReadyToReuse ) ); + VK_CHECK( vkResetCommandPool( render_device->device, frame_in_use.commandPool, 0 ) ); - VkCommandBufferBeginInfo constexpr beginInfo = { + VkCommandBufferBeginInfo constexpr begin_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .pNext = nullptr, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, .pInheritanceInfo = nullptr, }; - uint32_t mipLevels = TextureManager::calculateRequiredMipLevels( width, height, 1 ); + uint32_t mip_levels = TextureManager::CalculateRequiredMipLevels( width, height, 1 ); - VkImageSubresourceRange const subresourceRange = { + VkImageSubresourceRange const subresource_range = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, - .levelCount = mipLevels, + .levelCount = mip_levels, .baseArrayLayer = 0, .layerCount = 1, }; - VkImageMemoryBarrier2 const creationToTransferImageBarrier = { + VkImageMemoryBarrier2 const creation_to_transfer_image_barrier = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, .pNext = nullptr, .srcStageMask = VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT, @@ -146,11 +147,11 @@ std::optional LoadTexture( .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = renderDevice->textureManager->fetchImage( texture ).value(), - .subresourceRange = subresourceRange, + .image = render_device->textureManager->FetchImage( texture ).value(), + .subresourceRange = subresource_range, }; - VkDependencyInfo const creationToTransferDependency = { + VkDependencyInfo const creation_to_transfer_dependency = { .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .pNext = nullptr, .dependencyFlags = 0, @@ -159,54 +160,57 @@ std::optional LoadTexture( .bufferMemoryBarrierCount = 0, .pBufferMemoryBarriers = nullptr, .imageMemoryBarrierCount = 1, - .pImageMemoryBarriers = &creationToTransferImageBarrier, + .pImageMemoryBarriers = &creation_to_transfer_image_barrier, }; - std::array transferToReadyImageBarriers{ - // transferToReadyImageBarrier - VkImageMemoryBarrier2{ - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, - .pNext = nullptr, - .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, - .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, - .dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, - .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, - .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = textureImage, - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = mipLevels-1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }, - VkImageMemoryBarrier2{ - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, - .pNext = nullptr, - .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, - .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, - .dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, - .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, - .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = textureImage, - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = mipLevels-1, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - } - }; + VkImageSubresourceRange all_but_last_mip_subresource = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = mip_levels - 1, + .baseArrayLayer = 0, + .layerCount = 1, + }; - VkDependencyInfo const transferToReadyDependency = { + VkImageSubresourceRange last_mip_subresource = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = mip_levels - 1, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }; + + VkImageMemoryBarrier2 transfer_to_ready_image_barriers[] = { + { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .pNext = nullptr, + .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, + .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = texture_image, + .subresourceRange = all_but_last_mip_subresource, + }, + { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .pNext = nullptr, + .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, + .dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = texture_image, + .subresourceRange = last_mip_subresource, + } + }; + + VkDependencyInfo const transfer_to_ready_dependency = { .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .pNext = nullptr, .dependencyFlags = 0, @@ -214,11 +218,11 @@ std::optional LoadTexture( .pMemoryBarriers = nullptr, .bufferMemoryBarrierCount = 0, .pBufferMemoryBarriers = nullptr, - .imageMemoryBarrierCount = static_cast( transferToReadyImageBarriers.size() ), - .pImageMemoryBarriers = transferToReadyImageBarriers.data(), + .imageMemoryBarrierCount = _countof( transfer_to_ready_image_barriers ), + .pImageMemoryBarriers = transfer_to_ready_image_barriers, }; - VkImageSubresourceRange const mipLevelSubresource = { + constexpr VkImageSubresourceRange mip_level_subresource = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, @@ -226,40 +230,40 @@ std::optional LoadTexture( .layerCount = 1, }; - std::array prepareNextMipLevelBarriers{ + VkImageMemoryBarrier2 prepare_next_mip_level_barriers[] = { // prepareNextMipLevelSrcImageBarrier - VkImageMemoryBarrier2{ - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, - .pNext = nullptr, - .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, - .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, - .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, - .dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT, - .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = textureImage, - .subresourceRange = mipLevelSubresource, - }, + { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .pNext = nullptr, + .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT, + .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = texture_image, + .subresourceRange = mip_level_subresource, + }, // prepareNextMipLevelDstImageBarrier - VkImageMemoryBarrier2{ - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, - .pNext = nullptr, - .srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT, - .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, - .dstStageMask = VK_PIPELINE_STAGE_2_BLIT_BIT, - .dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, - .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = textureImage, - .subresourceRange = mipLevelSubresource, - } + { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + .pNext = nullptr, + .srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_BLIT_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .newLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = texture_image, + .subresourceRange = mip_level_subresource, + }, }; - VkDependencyInfo const prepareNextMipLevelDependency = { + VkDependencyInfo const prepare_next_mip_level_dependency = { .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .pNext = nullptr, .dependencyFlags = 0, @@ -267,14 +271,13 @@ std::optional LoadTexture( .pMemoryBarriers = nullptr, .bufferMemoryBarrierCount = 0, .pBufferMemoryBarriers = nullptr, - .imageMemoryBarrierCount = static_cast( prepareNextMipLevelBarriers.size() ), - .pImageMemoryBarriers = prepareNextMipLevelBarriers.data(), + .imageMemoryBarrierCount = _countof( prepare_next_mip_level_barriers ), + .pImageMemoryBarriers = prepare_next_mip_level_barriers, }; - - vkBeginCommandBuffer( frameInUse.commandBuffer, &beginInfo ); + vkBeginCommandBuffer( frame_in_use.commandBuffer, &begin_info ); { - VkImageSubresourceLayers imageSubresourceLayers = { + VkImageSubresourceLayers image_subresource_layers = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .mipLevel = 0, .baseArrayLayer = 0, @@ -282,125 +285,130 @@ std::optional LoadTexture( }; // TODO: Ensure `bufferRowLength` and `bufferImageHeight` are not required. - VkBufferImageCopy copyRegion = { + VkBufferImageCopy copy_region = { .bufferOffset = 0, .bufferRowLength = 0, .bufferImageHeight = 0, - .imageSubresource = imageSubresourceLayers, - .imageOffset = { 0, 0, 0 }, - .imageExtent = { width, height, 1 } + .imageSubresource = image_subresource_layers, + .imageOffset = {0, 0, 0}, + .imageExtent = {width, height, 1} }; // Start - vkCmdPipelineBarrier2( frameInUse.commandBuffer, &creationToTransferDependency ); + vkCmdPipelineBarrier2( frame_in_use.commandBuffer, &creation_to_transfer_dependency ); // Staging -> Image L0 vkCmdCopyBufferToImage( - frameInUse.commandBuffer, stagingBuffer, textureImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Region ); + frame_in_use.commandBuffer, + staging_buffer, + texture_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + 1, + ©_region ); - prepareNextMipLevelBarriers[0].subresourceRange.baseMipLevel = 0; - prepareNextMipLevelBarriers[1].subresourceRange.baseMipLevel = 1; + prepare_next_mip_level_barriers[0].subresourceRange.baseMipLevel = 0; + prepare_next_mip_level_barriers[1].subresourceRange.baseMipLevel = 1; - int32_t mipSrcWidth = static_cast( width ); - int32_t mipSrcHeight = static_cast( height ); - int32_t mipDstWidth = std::max( mipSrcWidth / 2, 1 ); - int32_t mipDstHeight = std::max( mipSrcHeight / 2, 1 ); + int32_t mip_src_width = static_cast( width ); + int32_t mip_src_height = static_cast( height ); + int32_t mip_dst_width = std::max( mip_src_width / 2, 1 ); + int32_t mip_dst_height = std::max( mip_src_height / 2, 1 ); - VkImageSubresourceLayers constexpr mipSubresourceLayers = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .mipLevel = 0, - .baseArrayLayer = 0, - .layerCount = 1, + VkImageSubresourceLayers constexpr mip_subresource_layers = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .mipLevel = 0, + .baseArrayLayer = 0, + .layerCount = 1, }; - VkImageBlit2 imageBlit = { + VkImageBlit2 image_blit = { .sType = VK_STRUCTURE_TYPE_IMAGE_BLIT_2, .pNext = nullptr, - .srcSubresource = mipSubresourceLayers, - .srcOffsets = { { 0, 0, 0 }, { mipSrcWidth, mipSrcHeight, 1 } }, - .dstSubresource = mipSubresourceLayers, - .dstOffsets = { { 0, 0, 0 }, { mipDstWidth, mipDstHeight, 1 } }, + .srcSubresource = mip_subresource_layers, + .srcOffsets = {{ 0, 0, 0 }, { mip_src_width, mip_src_height, 1 }}, + .dstSubresource = mip_subresource_layers, + .dstOffsets = {{ 0, 0, 0 }, { mip_dst_width, mip_dst_height, 1 }}, }; - imageBlit.srcSubresource.mipLevel = 0; - imageBlit.dstSubresource.mipLevel = 1; - imageBlit.srcOffsets[1].x = mipSrcWidth; - imageBlit.srcOffsets[1].y = mipSrcHeight; - imageBlit.dstOffsets[1].x = mipDstWidth; - imageBlit.dstOffsets[1].y = mipDstHeight; + image_blit.srcSubresource.mipLevel = 0; + image_blit.dstSubresource.mipLevel = 1; + image_blit.srcOffsets[1].x = mip_src_width; + image_blit.srcOffsets[1].y = mip_src_height; + image_blit.dstOffsets[1].x = mip_dst_width; + image_blit.dstOffsets[1].y = mip_dst_height; - VkBlitImageInfo2 blitInfo = { + VkBlitImageInfo2 blit_info = { .sType = VK_STRUCTURE_TYPE_BLIT_IMAGE_INFO_2, .pNext = nullptr, - .srcImage = textureImage, + .srcImage = texture_image, .srcImageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - .dstImage = textureImage, + .dstImage = texture_image, .dstImageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .regionCount = 1, - .pRegions = &imageBlit, + .pRegions = &image_blit, .filter = VK_FILTER_LINEAR, }; // MipMapping - for ( uint32_t dstMipLevel = 1; dstMipLevel < mipLevels; ++dstMipLevel ) + for ( uint32_t dst_mip_level = 1; dst_mip_level < mip_levels; ++dst_mip_level ) { - vkCmdPipelineBarrier2( frameInUse.commandBuffer, &prepareNextMipLevelDependency ); - vkCmdBlitImage2( frameInUse.commandBuffer, &blitInfo ); + vkCmdPipelineBarrier2( frame_in_use.commandBuffer, &prepare_next_mip_level_dependency ); + vkCmdBlitImage2( frame_in_use.commandBuffer, &blit_info ); // Prep for NEXT iteration - mipSrcWidth = mipDstWidth; - mipSrcHeight = mipDstHeight; - mipDstWidth = std::max( mipSrcWidth / 2, 1 ); - mipDstHeight = std::max( mipSrcHeight / 2, 1 ); + mip_src_width = mip_dst_width; + mip_src_height = mip_dst_height; + mip_dst_width = std::max( mip_src_width / 2, 1 ); + mip_dst_height = std::max( mip_src_height / 2, 1 ); - imageBlit.srcSubresource.mipLevel = dstMipLevel; - imageBlit.dstSubresource.mipLevel = dstMipLevel + 1; - imageBlit.srcOffsets[1].x = mipSrcWidth; - imageBlit.srcOffsets[1].y = mipSrcHeight; - imageBlit.dstOffsets[1].x = mipDstWidth; - imageBlit.dstOffsets[1].y = mipDstHeight; + image_blit.srcSubresource.mipLevel = dst_mip_level; + image_blit.dstSubresource.mipLevel = dst_mip_level + 1; + image_blit.srcOffsets[1].x = mip_src_width; + image_blit.srcOffsets[1].y = mip_src_height; + image_blit.dstOffsets[1].x = mip_dst_width; + image_blit.dstOffsets[1].y = mip_dst_height; // Prep current mip level as source - prepareNextMipLevelBarriers[0].subresourceRange.baseMipLevel = dstMipLevel; - prepareNextMipLevelBarriers[1].subresourceRange.baseMipLevel = dstMipLevel + 1; + prepare_next_mip_level_barriers[0].subresourceRange.baseMipLevel = dst_mip_level; + prepare_next_mip_level_barriers[1].subresourceRange.baseMipLevel = dst_mip_level + 1; } // End - vkCmdPipelineBarrier2( frameInUse.commandBuffer, &transferToReadyDependency ); + vkCmdPipelineBarrier2( frame_in_use.commandBuffer, &transfer_to_ready_dependency ); } - vkEndCommandBuffer( frameInUse.commandBuffer ); + vkEndCommandBuffer( frame_in_use.commandBuffer ); - VkSubmitInfo submitInfo = { + VkSubmitInfo submit_info = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .pNext = nullptr, .waitSemaphoreCount = 0, .pWaitSemaphores = nullptr, .pWaitDstStageMask = nullptr, .commandBufferCount = 1, - .pCommandBuffers = &frameInUse.commandBuffer, + .pCommandBuffers = &frame_in_use.commandBuffer, .signalSemaphoreCount = 0, .pSignalSemaphores = nullptr, }; - VK_CHECK( vkQueueSubmit( renderDevice->directQueue, 1, &submitInfo, frameInUse.frameReadyToReuse ) ); + VK_CHECK( vkQueueSubmit( render_device->directQueue, 1, &submit_info, frame_in_use.frameReadyToReuse ) ); // Do not reset this. Else, the frame will never be available to the main loop. - VK_CHECK( vkWaitForFences( renderDevice->device, 1, &frameInUse.frameReadyToReuse, VK_TRUE, UINT64_MAX ) ); + VK_CHECK( vkWaitForFences( render_device->device, 1, &frame_in_use.frameReadyToReuse, VK_TRUE, UINT64_MAX ) ); - renderDevice->frameIndex = ( renderDevice->frameIndex + 1 ) % renderDevice->getNumFrames(); + render_device->frameIndex = ( render_device->frameIndex + 1 ) % render_device->GetNumFrames(); } - vmaDestroyBuffer( renderDevice->gpuAllocator, stagingBuffer, stagingAllocation ); + vmaDestroyBuffer( render_device->gpuAllocator, staging_buffer, staging_allocation ); return texture; } // TODO: Cache materials while loading. -uint32_t ProcessMaterial( RenderDevice* renderDevice, Model* model, cgltf_material const& material ) +uint32_t ProcessMaterial( RenderDevice* render_device, Model* model, cgltf_material const& material ) { ASSERT( material.has_pbr_metallic_roughness ); - auto const baseColorFactor = DirectX::XMFLOAT4{ material.pbr_metallic_roughness.base_color_factor }; - auto const emissiveFactor = DirectX::XMFLOAT4{ + auto const base_color_factor = DirectX::XMFLOAT4{ material.pbr_metallic_roughness.base_color_factor }; + auto const emissive_factor = DirectX::XMFLOAT4{ material.emissive_factor[0], material.emissive_factor[1], material.emissive_factor[2], @@ -408,12 +416,12 @@ uint32_t ProcessMaterial( RenderDevice* renderDevice, Model* model, cgltf_materi }; VkSampler sampler = nullptr; - TextureID baseColorTexture; - TextureID normalTexture; - TextureID metalRoughTexture; - TextureID emissiveTexture; + TextureID base_color_texture; + TextureID normal_texture; + TextureID metal_rough_texture; + TextureID emissive_texture; - VkSamplerCreateInfo constexpr samplerCreateInfo = { + VkSamplerCreateInfo constexpr sampler_create_info = { .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .pNext = nullptr, .flags = 0, @@ -434,234 +442,234 @@ uint32_t ProcessMaterial( RenderDevice* renderDevice, Model* model, cgltf_materi .unnormalizedCoordinates = false, }; - VK_CHECK( vkCreateSampler( renderDevice->device, &samplerCreateInfo, nullptr, &sampler ) ); + VK_CHECK( vkCreateSampler( render_device->device, &sampler_create_info, nullptr, &sampler ) ); if ( material.pbr_metallic_roughness.base_color_texture.texture ) { - cgltf_image const* baseColorImage = material.pbr_metallic_roughness.base_color_texture.texture->image; + cgltf_image const* base_color_image = material.pbr_metallic_roughness.base_color_texture.texture->image; - auto const baseColorTextureOpt = LoadTexture( renderDevice, sampler, *baseColorImage, false ); - if ( not baseColorTextureOpt ) + auto const base_color_texture_opt = LoadTexture( render_device, sampler, *base_color_image, false ); + if ( not base_color_texture_opt ) { - vkDestroySampler( renderDevice->device, Take( sampler ), nullptr ); + vkDestroySampler( render_device->device, Take( sampler ), nullptr ); return UINT32_MAX; } - baseColorTexture = baseColorTextureOpt.value(); + base_color_texture = base_color_texture_opt.value(); } if ( material.pbr_metallic_roughness.metallic_roughness_texture.texture ) { - cgltf_image const* metalRoughImage = material.pbr_metallic_roughness.metallic_roughness_texture.texture->image; + cgltf_image const* metal_rough_image = material.pbr_metallic_roughness.metallic_roughness_texture.texture->image; - auto const metalRoughTextureOpt = LoadTexture( renderDevice, sampler, *metalRoughImage, true ); - if ( not metalRoughTextureOpt ) + auto const metal_rough_texture_opt = LoadTexture( render_device, sampler, *metal_rough_image, true ); + if ( not metal_rough_texture_opt ) { - vkDestroySampler( renderDevice->device, Take( sampler ), nullptr ); - renderDevice->textureManager->freeTexture( &baseColorTexture ); + vkDestroySampler( render_device->device, Take( sampler ), nullptr ); + render_device->textureManager->FreeTexture( &base_color_texture ); return UINT32_MAX; } - metalRoughTexture = metalRoughTextureOpt.value(); + metal_rough_texture = metal_rough_texture_opt.value(); } if ( material.normal_texture.texture ) { - cgltf_image const* normalImage = material.normal_texture.texture->image; + cgltf_image const* normal_image = material.normal_texture.texture->image; - auto const normalTextureOpt = LoadTexture( renderDevice, sampler, *normalImage, true ); - if ( not normalTextureOpt ) + auto const normal_texture_opt = LoadTexture( render_device, sampler, *normal_image, true ); + if ( not normal_texture_opt ) { - vkDestroySampler( renderDevice->device, Take( sampler ), nullptr ); - renderDevice->textureManager->freeTexture( &metalRoughTexture ); - renderDevice->textureManager->freeTexture( &baseColorTexture ); + vkDestroySampler( render_device->device, Take( sampler ), nullptr ); + render_device->textureManager->FreeTexture( &metal_rough_texture ); + render_device->textureManager->FreeTexture( &base_color_texture ); return UINT32_MAX; } - normalTexture = normalTextureOpt.value(); + normal_texture = normal_texture_opt.value(); } if ( material.emissive_texture.texture ) { - cgltf_image const* emissiveImage = material.emissive_texture.texture->image; + cgltf_image const* emissive_image = material.emissive_texture.texture->image; - auto const emissiveTextureOpt = LoadTexture( renderDevice, sampler, *emissiveImage, true ); - if ( not emissiveTextureOpt ) + auto const emissive_texture_opt = LoadTexture( render_device, sampler, *emissive_image, true ); + if ( not emissive_texture_opt ) { - vkDestroySampler( renderDevice->device, Take( sampler ), nullptr ); - renderDevice->textureManager->freeTexture( &baseColorTexture ); - renderDevice->textureManager->freeTexture( &normalTexture ); - renderDevice->textureManager->freeTexture( &metalRoughTexture ); + vkDestroySampler( render_device->device, Take( sampler ), nullptr ); + render_device->textureManager->FreeTexture( &base_color_texture ); + render_device->textureManager->FreeTexture( &normal_texture ); + render_device->textureManager->FreeTexture( &metal_rough_texture ); return UINT32_MAX; } - emissiveTexture = emissiveTextureOpt.value(); + emissive_texture = emissive_texture_opt.value(); } - float const metallic = material.pbr_metallic_roughness.metallic_factor; - float const roughness = material.pbr_metallic_roughness.roughness_factor; + float const metallic = material.pbr_metallic_roughness.metallic_factor; + float const roughness = material.pbr_metallic_roughness.roughness_factor; - uint32_t const materialIdx = static_cast( model->materials.size() ); + uint32_t const material_idx = static_cast( model->materials.size() ); model->materials.push_back( { - sampler, - baseColorFactor, - emissiveFactor, - baseColorTexture, - normalTexture, - metalRoughTexture, - emissiveTexture, - roughness, - metallic, + sampler, + base_color_factor, + emissive_factor, + base_color_texture, + normal_texture, + metal_rough_texture, + emissive_texture, + roughness, + metallic, } ); - return materialIdx; + return material_idx; } void LoadAttribute( - std::vector* pVertices, - int32_t const vertexStart, - std::vector* scratch, - cgltf_attribute const& positionAttr, - size_t const stride, - size_t const offset, - size_t const components ) + std::vector* vertices, + int32_t const vertex_start, + std::vector* scratch, + cgltf_attribute const& position_attr, + size_t const stride, + size_t const offset, + size_t const components ) { - size_t const floatCount = cgltf_accessor_unpack_floats( positionAttr.data, nullptr, 0 ); - ASSERT( floatCount % components == 0 ); - scratch->resize( floatCount ); - cgltf_accessor_unpack_floats( positionAttr.data, scratch->data(), scratch->size() ); + size_t const float_count = cgltf_accessor_unpack_floats( position_attr.data, nullptr, 0 ); + ASSERT( float_count % components == 0 ); + scratch->resize( float_count ); + cgltf_accessor_unpack_floats( position_attr.data, scratch->data(), scratch->size() ); // Guaranteed to have space for these vertices. - pVertices->resize( vertexStart + floatCount / components ); + vertices->resize( vertex_start + float_count / components ); - byte* writePtr = reinterpret_cast( pVertices->data() + vertexStart ) + offset; - float const* readPtr = scratch->data(); - for ( size_t i = vertexStart; i < pVertices->size(); ++i ) + byte* write_ptr = reinterpret_cast( vertices->data() + vertex_start ) + offset; + float const* read_ptr = scratch->data(); + for ( size_t i = vertex_start; i < vertices->size(); ++i ) { - memcpy( writePtr, readPtr, components * sizeof( float ) ); + memcpy( write_ptr, read_ptr, components * sizeof( float ) ); - readPtr += components; - writePtr += stride; + read_ptr += components; + write_ptr += stride; } scratch->clear(); } ModelMesh ProcessMesh( - RenderDevice* renderDevice, - Model* model, - std::vector* pVertices, - std::vector* pIndices, - cgltf_mesh const& mesh ) + RenderDevice* render_device, + Model* model, + std::vector* vertices, + std::vector* indices, + cgltf_mesh const& mesh ) { using namespace std::string_view_literals; - uint32_t const primitiveStart = static_cast( model->primitives.size() ); - uint32_t const primitiveCount = static_cast( mesh.primitives_count ); + uint32_t const primitive_start = static_cast( model->primitives.size() ); + uint32_t const primitive_count = static_cast( mesh.primitives_count ); - cgltf_primitive const* primitives = mesh.primitives; - for ( uint32_t primitiveIndex = 0; primitiveIndex < mesh.primitives_count; ++primitiveIndex ) + cgltf_primitive const* primitives = mesh.primitives; + for ( uint32_t primitive_index = 0; primitive_index < mesh.primitives_count; ++primitive_index ) { // VertexStart is per-primitive - int32_t const vertexStart = static_cast( pVertices->size() ); + int32_t const vertex_start = static_cast( vertices->size() ); - cgltf_primitive const& primitive = primitives[primitiveIndex]; + cgltf_primitive const& primitive = primitives[primitive_index]; ASSERT( primitive.type == cgltf_primitive_type_triangles ); // Index Buffer - size_t const indexStart = pIndices->size(); - size_t const indexCount = cgltf_accessor_unpack_indices( primitive.indices, nullptr, sizeof pIndices->at( 0 ), 0 ); - ASSERT( indexCount > 0 ); - pIndices->resize( indexStart + indexCount ); + size_t const index_start = indices->size(); + size_t const index_count = cgltf_accessor_unpack_indices( primitive.indices, nullptr, sizeof indices->at( 0 ), 0 ); + ASSERT( index_count > 0 ); + indices->resize( index_start + index_count ); cgltf_accessor_unpack_indices( - primitive.indices, pIndices->data() + indexStart, sizeof pIndices->at( 0 ), indexCount ); + primitive.indices, indices->data() + index_start, sizeof indices->at( 0 ), index_count ); // Material - uint32_t materialIdx = UINT32_MAX; + uint32_t material_idx = UINT32_MAX; if ( primitive.material ) { - materialIdx = ProcessMaterial( renderDevice, model, *primitive.material ); + material_idx = ProcessMaterial( render_device, model, *primitive.material ); } model->primitives.push_back( Primitive{ - .indexStart = static_cast( indexStart ), - .indexCount = static_cast( indexCount ), - .material = materialIdx, - .vertexOffset = vertexStart, + .indexStart = static_cast( index_start ), + .indexCount = static_cast( index_count ), + .material = material_idx, + .vertexOffset = vertex_start, } ); std::vector scratch; cgltf_attribute const* attributes = primitive.attributes; - for ( uint32_t attribIndex = 0; attribIndex < primitive.attributes_count; ++attribIndex ) + for ( uint32_t attrib_index = 0; attrib_index < primitive.attributes_count; ++attrib_index ) { - if ( "POSITION"sv == attributes[attribIndex].name ) + if ( "POSITION"sv == attributes[attrib_index].name ) { - cgltf_attribute const& positionAttr = attributes[attribIndex]; - ASSERT( positionAttr.data->component_type == cgltf_component_type_r_32f ); - ASSERT( positionAttr.data->type == cgltf_type_vec3 ); + cgltf_attribute const& position_attr = attributes[attrib_index]; + ASSERT( position_attr.data->component_type == cgltf_component_type_r_32f ); + ASSERT( position_attr.data->type == cgltf_type_vec3 ); size_t constexpr stride = sizeof( Vertex ); size_t constexpr offset = offsetof( Vertex, position ); size_t constexpr components = 3; - LoadAttribute( pVertices, vertexStart, &scratch, positionAttr, stride, offset, components ); + LoadAttribute( vertices, vertex_start, &scratch, position_attr, stride, offset, components ); } - if ( "NORMAL"sv == attributes[attribIndex].name ) + if ( "NORMAL"sv == attributes[attrib_index].name ) { - cgltf_attribute const& normalAttr = attributes[attribIndex]; - ASSERT( normalAttr.data->component_type == cgltf_component_type_r_32f ); - ASSERT( normalAttr.data->type == cgltf_type_vec3 ); + cgltf_attribute const& normal_attr = attributes[attrib_index]; + ASSERT( normal_attr.data->component_type == cgltf_component_type_r_32f ); + ASSERT( normal_attr.data->type == cgltf_type_vec3 ); size_t constexpr stride = sizeof( Vertex ); size_t constexpr offset = offsetof( Vertex, normal ); size_t constexpr components = 3; - LoadAttribute( pVertices, vertexStart, &scratch, normalAttr, stride, offset, components ); + LoadAttribute( vertices, vertex_start, &scratch, normal_attr, stride, offset, components ); } - if ( "TANGENT"sv == attributes[attribIndex].name ) + if ( "TANGENT"sv == attributes[attrib_index].name ) { - cgltf_attribute const& tangentAttr = attributes[attribIndex]; - ASSERT( tangentAttr.data->component_type == cgltf_component_type_r_32f ); - ASSERT( tangentAttr.data->type == cgltf_type_vec4 ); + cgltf_attribute const& tangent_attr = attributes[attrib_index]; + ASSERT( tangent_attr.data->component_type == cgltf_component_type_r_32f ); + ASSERT( tangent_attr.data->type == cgltf_type_vec4 ); size_t constexpr stride = sizeof( Vertex ); size_t constexpr offset = offsetof( Vertex, tangent ); size_t constexpr components = 4; - LoadAttribute( pVertices, vertexStart, &scratch, tangentAttr, stride, offset, components ); + LoadAttribute( vertices, vertex_start, &scratch, tangent_attr, stride, offset, components ); } - if ( "TEXCOORD_0"sv == attributes[attribIndex].name ) + if ( "TEXCOORD_0"sv == attributes[attrib_index].name ) { - cgltf_attribute const& texCoordAttr = attributes[attribIndex]; - ASSERT( texCoordAttr.data->component_type == cgltf_component_type_r_32f ); - ASSERT( texCoordAttr.data->type == cgltf_type_vec2 ); + cgltf_attribute const& tex_coord_attr = attributes[attrib_index]; + ASSERT( tex_coord_attr.data->component_type == cgltf_component_type_r_32f ); + ASSERT( tex_coord_attr.data->type == cgltf_type_vec2 ); size_t constexpr stride = sizeof( Vertex ); size_t constexpr offset = offsetof( Vertex, texCoord0 ); size_t constexpr components = 2; - LoadAttribute( pVertices, vertexStart, &scratch, texCoordAttr, stride, offset, components ); + LoadAttribute( vertices, vertex_start, &scratch, tex_coord_attr, stride, offset, components ); } - if ( "TEXCOORD_1"sv == attributes[attribIndex].name ) + if ( "TEXCOORD_1"sv == attributes[attrib_index].name ) { - cgltf_attribute const& texCoordAttr = attributes[attribIndex]; - ASSERT( texCoordAttr.data->component_type == cgltf_component_type_r_32f ); - ASSERT( texCoordAttr.data->type == cgltf_type_vec2 ); + cgltf_attribute const& tex_coord_attr = attributes[attrib_index]; + ASSERT( tex_coord_attr.data->component_type == cgltf_component_type_r_32f ); + ASSERT( tex_coord_attr.data->type == cgltf_type_vec2 ); size_t constexpr stride = sizeof( Vertex ); size_t constexpr offset = offsetof( Vertex, texCoord1 ); size_t constexpr components = 2; - LoadAttribute( pVertices, vertexStart, &scratch, texCoordAttr, stride, offset, components ); + LoadAttribute( vertices, vertex_start, &scratch, tex_coord_attr, stride, offset, components ); } - if ( "COLOR_0"sv == attributes[attribIndex].name ) + if ( "COLOR_0"sv == attributes[attrib_index].name ) { - cgltf_attribute const& colorAttr = attributes[attribIndex]; - ASSERT( colorAttr.data->component_type == cgltf_component_type_r_32f ); + cgltf_attribute const& color_attr = attributes[attrib_index]; + ASSERT( color_attr.data->component_type == cgltf_component_type_r_32f ); size_t constexpr stride = sizeof( Vertex ); size_t constexpr offset = offsetof( Vertex, texCoord1 ); size_t components = 3; - switch ( colorAttr.data->type ) + switch ( color_attr.data->type ) { case cgltf_type_vec3: components = 3; @@ -673,125 +681,127 @@ ModelMesh ProcessMesh( UNREACHABLE; } - LoadAttribute( pVertices, vertexStart, &scratch, colorAttr, stride, offset, components ); + LoadAttribute( vertices, vertex_start, &scratch, color_attr, stride, offset, components ); } // TODO: Grab other attributes. } } - return { primitiveStart, primitiveCount }; + return { primitive_start, primitive_count }; } Entity* ProcessNode( - RenderDevice* renderDevice, - EntityManager* entityManager, - Model* model, - std::vector* vertices, - std::vector* indices, - cgltf_node const& node ) + RenderDevice* render_device, + EntityManager* entity_manager, + Model* model, + std::vector* vertices, + std::vector* indices, + cgltf_node const& node ) { - DirectX::XMVECTOR vTranslation; - DirectX::XMVECTOR qRotation; - DirectX::XMVECTOR vScale; + DirectX::XMVECTOR translation; + DirectX::XMVECTOR rotation; + DirectX::XMVECTOR scale; if ( node.has_matrix ) { - DirectX::XMMATRIX const mat = DirectX::XMMATRIX{ node.matrix }; - ASSERT( DirectX::XMMatrixDecompose( &vScale, &qRotation, &vTranslation, mat ) ); + auto const mat = DirectX::XMMATRIX{ node.matrix }; + ASSERT( DirectX::XMMatrixDecompose( &scale, &rotation, &translation, mat ) ); } else { - vTranslation = node.has_translation - ? DirectX::XMVectorSet( node.translation[0], node.translation[1], node.translation[2], 1.0f ) - : DirectX::XMVectorZero(); - qRotation = node.has_rotation - ? DirectX::XMVectorSet( node.rotation[0], node.rotation[1], node.rotation[2], node.rotation[3] ) - : DirectX::XMQuaternionIdentity(); - vScale = node.has_scale ? DirectX::XMVectorSet( node.scale[0], node.scale[1], node.scale[2], 1.0f ) - : DirectX::XMVectorSplatOne(); + translation = node.has_translation + ? DirectX::XMVectorSet( node.translation[0], node.translation[1], node.translation[2], 1.0f ) + : DirectX::XMVectorZero(); + rotation = node.has_rotation + ? DirectX::XMVectorSet( node.rotation[0], node.rotation[1], node.rotation[2], node.rotation[3] ) + : DirectX::XMQuaternionIdentity(); + scale = node.has_scale ? DirectX::XMVectorSet( node.scale[0], node.scale[1], node.scale[2], 1.0f ) + : DirectX::XMVectorSplatOne(); } - auto tx = Transform{ - .translation = vTranslation, - .rotation = qRotation, - .scale = vScale, - }; - Entity* entity = entityManager->createEntity( tx ); + Entity* entity = entity_manager->CreateEntity( { + .translation = translation, + .rotation = rotation, + .scale = scale, + } ); if ( node.mesh ) { - entity->modelMesh = ProcessMesh( renderDevice, model, vertices, indices, *node.mesh ); + entity->modelMesh = ProcessMesh( render_device, model, vertices, indices, *node.mesh ); } - for ( uint32_t childIdx = 0; childIdx < node.children_count; ++childIdx ) + for ( uint32_t child_idx = 0; child_idx < node.children_count; ++child_idx ) { - entity->addChild( ProcessNode( renderDevice, entityManager, model, vertices, indices, *node.children[childIdx] ) ); + entity->AddChild( + ProcessNode( render_device, entity_manager, model, vertices, indices, *node.children[child_idx] ) ); } return entity; } -Entity* LoadModel( RenderDevice* renderDevice, EntityManager* entityManager, const char* filename ) +Entity* LoadModel( Blaze::RenderDevice* render_device, EntityManager* entity_manager, char const* filename ) { - cgltf_data* gltfModel = nullptr; - cgltf_options options = {}; - cgltf_result result = cgltf_parse_file( &options, filename, &gltfModel ); + cgltf_data* gltf_model = nullptr; + cgltf_options options = {}; + cgltf_result result = cgltf_parse_file( &options, filename, &gltf_model ); if ( result != cgltf_result_success ) { SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "%s failed to load", filename ); - cgltf_free( gltfModel ); + cgltf_free( gltf_model ); return nullptr; } - result = cgltf_validate( gltfModel ); + result = cgltf_validate( gltf_model ); if ( result != cgltf_result_success ) { SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "%s is invalid.", filename ); - cgltf_free( gltfModel ); + cgltf_free( gltf_model ); return nullptr; } - result = cgltf_load_buffers( &options, gltfModel, filename ); + result = cgltf_load_buffers( &options, gltf_model, filename ); if ( result != cgltf_result_success ) { SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "%s buffers failed to load.", filename ); - cgltf_free( gltfModel ); + cgltf_free( gltf_model ); return nullptr; } - Entity* entity = entityManager->createEntity( { - .translation = DirectX::XMVectorZero(), - .rotation = DirectX::XMQuaternionIdentity(), - .scale = DirectX::XMVectorSplatOne(), + Entity* entity = entity_manager->CreateEntity( { + .translation = DirectX::XMVectorZero(), + .rotation = DirectX::XMQuaternionIdentity(), + .scale = DirectX::XMVectorSplatOne(), } ); // Output data std::vector vertices; std::vector indices; - cgltf_scene const* currentScene = gltfModel->scene; - for ( uint32_t nodeIdx = 0; nodeIdx < currentScene->nodes_count; ++nodeIdx ) + cgltf_scene const* current_scene = gltf_model->scene; + for ( uint32_t node_idx = 0; node_idx < current_scene->nodes_count; ++node_idx ) { - entity->addChild( ProcessNode( - renderDevice, entityManager, &entity->model, &vertices, &indices, *currentScene->nodes[nodeIdx] ) ); + entity->AddChild( ProcessNode( + render_device, entity_manager, &entity->model, &vertices, &indices, *current_scene->nodes[node_idx] ) ); } - entity->model.vertexBuffer = renderDevice->bufferManager->createVertexBuffer( vertices.size() * sizeof vertices[0] ); + entity->model.vertexBuffer = render_device->bufferManager->CreateVertexBuffer( vertices.size() * sizeof vertices[0] ); if ( not entity->model.vertexBuffer ) return nullptr; - renderDevice->bufferManager->writeToBuffer( entity->model.vertexBuffer, vertices ); + render_device->bufferManager->WriteToBuffer( entity->model.vertexBuffer, vertices ); - entity->model.indexBuffer = renderDevice->bufferManager->createIndexBuffer( indices.size() * sizeof indices[0] ); + entity->model.indexBuffer = render_device->bufferManager->CreateIndexBuffer( indices.size() * sizeof indices[0] ); if ( not entity->model.indexBuffer ) return nullptr; - renderDevice->bufferManager->writeToBuffer( entity->model.indexBuffer, std::span{ indices } ); + render_device->bufferManager->WriteToBuffer( entity->model.indexBuffer, std::span{ indices } ); - cgltf_free( gltfModel ); + cgltf_free( gltf_model ); return entity; } + +} // namespace Blaze diff --git a/Blaze/Source/ModelLoader.h b/Blaze/Source/ModelLoader.h index 8cee515..20f83ce 100644 --- a/Blaze/Source/ModelLoader.h +++ b/Blaze/Source/ModelLoader.h @@ -7,10 +7,13 @@ #include "BufferManager.h" #include "TextureManager.h" + +namespace Blaze +{ +struct GlobalMemory; struct RenderDevice; struct EntityManager; struct Entity; -struct GlobalMemory; struct Vertex { @@ -35,7 +38,7 @@ struct ModelMesh uint32_t primitiveStart = 0; uint32_t primitiveCount = 0; - [[nodiscard]] bool isNull() const + [[nodiscard]] bool IsNull() const { return primitiveCount == 0; } @@ -43,8 +46,8 @@ struct ModelMesh struct Material { - size_t constexpr static GPU_DATA_OFFSET = sizeof( VkSampler ); - size_t constexpr static GPU_DATA_SIZE = 56; + size_t constexpr static kGPUDataOffset = sizeof( VkSampler ); + size_t constexpr static kGPUDataSize = 56; VkSampler sampler; // TODO: Reuse // To copy directly. @@ -57,29 +60,29 @@ struct Material float roughness = 1.0f; float metallic = 1.0f; - [[nodiscard]] bool isNull() const + [[nodiscard]] bool IsNull() const { return not( albedoTextureID and normalTextureID and metalRoughTextureID and emissiveTextureID and sampler ); } }; -static_assert( sizeof( Material ) == Material::GPU_DATA_OFFSET + Material::GPU_DATA_SIZE ); +static_assert( sizeof( Material ) == Material::kGPUDataOffset + Material::kGPUDataSize ); static constexpr Material DEFAULT_MATERIAL = {}; struct Model { - std::pmr::monotonic_buffer_resource mem; + BufferID vertexBuffer; + BufferID indexBuffer; + std::vector materials; + std::vector primitives; - BufferID vertexBuffer; - BufferID indexBuffer; - std::pmr::vector materials; - std::pmr::vector primitives; - - [[nodiscard]] bool isNull() const + [[nodiscard]] bool IsNull() const { - return vertexBuffer.isNull(); + return vertexBuffer.IsNull(); } }; -Entity* LoadModel( RenderDevice* renderDevice, EntityManager* entityManager, const char* filename ); +Entity* LoadModel( RenderDevice* render_device, EntityManager* entity_manager, const char* filename ); + +} // namespace Blaze diff --git a/Blaze/Source/RID.cpp b/Blaze/Source/RID.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Blaze/Source/RID.h b/Blaze/Source/RID.h index 3a15220..c76b21f 100644 --- a/Blaze/Source/RID.h +++ b/Blaze/Source/RID.h @@ -2,6 +2,9 @@ #include +namespace Blaze +{ + template struct RID { @@ -14,7 +17,7 @@ private: public: RID() = default; - [[nodiscard]] bool isNull() const + [[nodiscard]] bool IsNull() const { return m_index == 0; } @@ -29,3 +32,5 @@ public: return m_index != 0; } }; + +} // namespace Blaze diff --git a/Blaze/Source/RenderDevice.cpp b/Blaze/Source/RenderDevice.cpp index 1ee8f81..3ca273b 100644 --- a/Blaze/Source/RenderDevice.cpp +++ b/Blaze/Source/RenderDevice.cpp @@ -1,5 +1,7 @@ #include "RenderDevice.h" +#include + #include "MacroUtils.h" #include @@ -11,26 +13,28 @@ #include "BufferManager.h" #include "Frame.h" #include "GlobalMemory.h" -#include "MathUtil.h" #include "TextureManager.h" +using Blaze::RenderDevice; + +#if defined( DTOR_TEST ) RenderDevice::~RenderDevice() { - ASSERT( !isInit() ); + ASSERT( !IsInit() ); } +#endif -// TODO: Failure Handling -RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo const& createInfo ) +RenderDevice* RenderDevice::Create( GlobalMemory* mem, CreateInfo const& create_info ) { ASSERT( mem ); - ASSERT( createInfo.window ); + ASSERT( create_info.window ); volkInitialize(); VkInstance instance; // Create Instance { - VkApplicationInfo constexpr applicationInfo = { + VkApplicationInfo constexpr application_info = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pNext = nullptr, .pApplicationName = "Test", @@ -40,63 +44,63 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c .apiVersion = VK_API_VERSION_1_3, }; - uint32_t instanceExtensionCount; - char const* const* instanceExtensions = SDL_Vulkan_GetInstanceExtensions( &instanceExtensionCount ); + uint32_t instance_extension_count; + char const* const* instance_extensions = SDL_Vulkan_GetInstanceExtensions( &instance_extension_count ); - VkInstanceCreateInfo const instanceCreateInfo = { + VkInstanceCreateInfo const instance_create_info = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = nullptr, .flags = 0, - .pApplicationInfo = &applicationInfo, + .pApplicationInfo = &application_info, .enabledLayerCount = 0, .ppEnabledLayerNames = nullptr, - .enabledExtensionCount = instanceExtensionCount, - .ppEnabledExtensionNames = instanceExtensions, + .enabledExtensionCount = instance_extension_count, + .ppEnabledExtensionNames = instance_extensions, }; - VK_CHECK( vkCreateInstance( &instanceCreateInfo, nullptr, &instance ) ); + VK_CHECK( vkCreateInstance( &instance_create_info, nullptr, &instance ) ); volkLoadInstance( instance ); } VkSurfaceKHR surface; // Create Surface - ASSERT( SDL_Vulkan_CreateSurface( createInfo.window, instance, nullptr, &surface ) ); + ASSERT( SDL_Vulkan_CreateSurface( create_info.window, instance, nullptr, &surface ) ); - VkPhysicalDevice physicalDeviceInUse = nullptr; - VkDevice device = nullptr; - VmaAllocator gpuAllocator = nullptr; - std::optional directQueueFamilyIndex = std::nullopt; - VkQueue directQueue = nullptr; + VkPhysicalDevice physical_device_in_use = nullptr; + VkDevice device = nullptr; + VmaAllocator allocator = nullptr; + std::optional direct_queue_family_index = std::nullopt; + VkQueue direct_queue = nullptr; // Create Device and Queue { - auto tempAllocStart = mem->getState(); + auto temp_alloc_start = mem->GetState(); - uint32_t physicalDeviceCount; - VK_CHECK( vkEnumeratePhysicalDevices( instance, &physicalDeviceCount, nullptr ) ); - SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "Found %u GPUs", physicalDeviceCount ); + uint32_t physical_device_count; + VK_CHECK( vkEnumeratePhysicalDevices( instance, &physical_device_count, nullptr ) ); + SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "Found %u GPUs", physical_device_count ); - VkPhysicalDevice* physicalDevices = - reinterpret_cast( mem->allocate( sizeof( VkPhysicalDevice ) * physicalDeviceCount ) ); - VK_CHECK( vkEnumeratePhysicalDevices( instance, &physicalDeviceCount, physicalDevices ) ); + VkPhysicalDevice* physical_devices = + reinterpret_cast( mem->Allocate( sizeof( VkPhysicalDevice ) * physical_device_count ) ); + VK_CHECK( vkEnumeratePhysicalDevices( instance, &physical_device_count, physical_devices ) ); - for ( VkPhysicalDevice const physicalDevice : std::span{ physicalDevices, physicalDeviceCount } ) + for ( VkPhysicalDevice const physical_device : std::span{ physical_devices, physical_device_count } ) { - auto tempAllocQueueProperties = mem->getState(); + auto temp_alloc_queue_properties = mem->GetState(); VkPhysicalDeviceProperties properties; - vkGetPhysicalDeviceProperties( physicalDevice, &properties ); + vkGetPhysicalDeviceProperties( physical_device, &properties ); SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "GPU: %s", properties.deviceName ); SDL_LogInfo( - SDL_LOG_CATEGORY_GPU, - "- API Version %d.%d.%d", - VK_API_VERSION_MAJOR( properties.apiVersion ), - VK_API_VERSION_MINOR( properties.apiVersion ), - VK_API_VERSION_PATCH( properties.apiVersion ) ); + SDL_LOG_CATEGORY_GPU, + "- API Version %d.%d.%d", + VK_API_VERSION_MAJOR( properties.apiVersion ), + VK_API_VERSION_MINOR( properties.apiVersion ), + VK_API_VERSION_PATCH( properties.apiVersion ) ); - constexpr static uint32_t API_PATCH_BITS = 0xFFF; - if ( ( properties.apiVersion & ( ~API_PATCH_BITS ) ) < VK_API_VERSION_1_3 ) + constexpr static uint32_t kApiPatchBits = 0xFFF; + if ( ( properties.apiVersion & ( ~kApiPatchBits ) ) < VK_API_VERSION_1_3 ) { continue; } @@ -106,68 +110,68 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c continue; } - uint32_t queueFamilyCount; - vkGetPhysicalDeviceQueueFamilyProperties( physicalDevice, &queueFamilyCount, nullptr ); - VkQueueFamilyProperties* queueFamilyProperties = reinterpret_cast( - mem->allocate( sizeof( VkQueueFamilyProperties ) * queueFamilyCount ) ); - vkGetPhysicalDeviceQueueFamilyProperties( physicalDevice, &queueFamilyCount, queueFamilyProperties ); + uint32_t queue_family_count; + vkGetPhysicalDeviceQueueFamilyProperties( physical_device, &queue_family_count, nullptr ); + VkQueueFamilyProperties* queue_family_properties = reinterpret_cast( + mem->Allocate( sizeof( VkQueueFamilyProperties ) * queue_family_count ) ); + vkGetPhysicalDeviceQueueFamilyProperties( physical_device, &queue_family_count, queue_family_properties ); - for ( uint32_t queueFamilyIndex = 0; queueFamilyIndex != queueFamilyCount; ++queueFamilyIndex ) + for ( uint32_t queue_family_index = 0; queue_family_index != queue_family_count; ++queue_family_index ) { - VkQueueFamilyProperties const& qfp = queueFamilyProperties[queueFamilyIndex]; + VkQueueFamilyProperties const& qfp = queue_family_properties[queue_family_index]; - bool hasGraphicsSupport = false; - bool hasComputeSupport = false; - bool hasTransferSupport = false; - bool hasPresentSupport = false; + bool has_graphics_support = false; + bool has_compute_support = false; + bool has_transfer_support = false; + bool has_present_support = false; - SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "- Queue [%d]", queueFamilyIndex ); + SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "- Queue [%d]", queue_family_index ); if ( qfp.queueFlags & VK_QUEUE_GRAPHICS_BIT ) { - hasGraphicsSupport = true; + has_graphics_support = true; SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "-- Graphic" ); } if ( qfp.queueFlags & VK_QUEUE_COMPUTE_BIT ) { - hasComputeSupport = true; + has_compute_support = true; SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "-- Compute" ); } if ( qfp.queueFlags & VK_QUEUE_TRANSFER_BIT ) { - hasTransferSupport = true; + has_transfer_support = true; SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "-- Transfer" ); } - VkBool32 isSurfaceSupported; + VkBool32 is_surface_supported; VK_CHECK( - vkGetPhysicalDeviceSurfaceSupportKHR( physicalDevice, queueFamilyIndex, surface, &isSurfaceSupported ) ); + vkGetPhysicalDeviceSurfaceSupportKHR( physical_device, queue_family_index, surface, &is_surface_supported ) ); - if ( isSurfaceSupported ) + if ( is_surface_supported ) { - hasPresentSupport = true; + has_present_support = true; SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "-- Present" ); } - if ( hasGraphicsSupport and hasComputeSupport and hasTransferSupport and hasPresentSupport ) + if ( has_graphics_support and has_compute_support and has_transfer_support and has_present_support ) { - physicalDeviceInUse = physicalDevice; - directQueueFamilyIndex = queueFamilyIndex; + physical_device_in_use = physical_device; + direct_queue_family_index = queue_family_index; break; } } - mem->restoreState( tempAllocQueueProperties ); + mem->RestoreState( temp_alloc_queue_properties ); } - ASSERT( physicalDeviceInUse ); - ASSERT( directQueueFamilyIndex.has_value() ); + ASSERT( physical_device_in_use ); + ASSERT( direct_queue_family_index.has_value() ); - float priority = 1.0f; - VkDeviceQueueCreateInfo queueCreateInfo = { + float priority = 1.0f; + VkDeviceQueueCreateInfo queue_create_info = { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .pNext = nullptr, .flags = 0, - .queueFamilyIndex = directQueueFamilyIndex.value(), + .queueFamilyIndex = direct_queue_family_index.value(), .queueCount = 1, .pQueuePriorities = &priority, }; @@ -200,27 +204,27 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c .samplerAnisotropy = true, }; - std::array enabledDeviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; + std::array enabled_device_extensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; - VkDeviceCreateInfo const deviceCreateInfo = { + VkDeviceCreateInfo const device_create_info = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .pNext = &features12, .flags = 0, .queueCreateInfoCount = 1, - .pQueueCreateInfos = &queueCreateInfo, + .pQueueCreateInfos = &queue_create_info, .enabledLayerCount = 0, .ppEnabledLayerNames = nullptr, - .enabledExtensionCount = static_cast( enabledDeviceExtensions.size() ), - .ppEnabledExtensionNames = enabledDeviceExtensions.data(), + .enabledExtensionCount = static_cast( enabled_device_extensions.size() ), + .ppEnabledExtensionNames = enabled_device_extensions.data(), .pEnabledFeatures = &features, }; - VK_CHECK( vkCreateDevice( physicalDeviceInUse, &deviceCreateInfo, nullptr, &device ) ); + VK_CHECK( vkCreateDevice( physical_device_in_use, &device_create_info, nullptr, &device ) ); volkLoadDevice( device ); - VmaAllocatorCreateInfo allocatorCreateInfo = { + VmaAllocatorCreateInfo allocator_create_info = { .flags = VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT, - .physicalDevice = physicalDeviceInUse, + .physicalDevice = physical_device_in_use, .device = device, .preferredLargeHeapBlockSize = 0, .pAllocationCallbacks = nullptr, @@ -232,112 +236,115 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c .pTypeExternalMemoryHandleTypes = nullptr, }; - VmaVulkanFunctions vkFunctions; - VK_CHECK( vmaImportVulkanFunctionsFromVolk( &allocatorCreateInfo, &vkFunctions ) ); - allocatorCreateInfo.pVulkanFunctions = &vkFunctions; + VmaVulkanFunctions vk_functions; + VK_CHECK( vmaImportVulkanFunctionsFromVolk( &allocator_create_info, &vk_functions ) ); + allocator_create_info.pVulkanFunctions = &vk_functions; - VK_CHECK( vmaCreateAllocator( &allocatorCreateInfo, &gpuAllocator ) ); + VK_CHECK( vmaCreateAllocator( &allocator_create_info, &allocator ) ); - vkGetDeviceQueue( device, directQueueFamilyIndex.value(), 0, &directQueue ); + vkGetDeviceQueue( device, direct_queue_family_index.value(), 0, &direct_queue ); - mem->restoreState( tempAllocStart ); + mem->RestoreState( temp_alloc_start ); } // Swapchain creation - VkExtent2D swapchainExtent = { createInfo.width, createInfo.height }; - VkFormat swapchainFormat = VK_FORMAT_UNDEFINED; + VkExtent2D swapchain_extent = { create_info.width, create_info.height }; + VkFormat swapchain_format = VK_FORMAT_UNDEFINED; VkSwapchainKHR swapchain; - VkImage* swapchainImages; - VkImageView* swapchainViews; - uint32_t swapchainImageCount; + VkImage* swapchain_images; + VkImageView* swapchain_views; + uint32_t swapchain_image_count; { - auto tempAllocStart = mem->getState(); + auto temp_alloc_start = mem->GetState(); VkSurfaceCapabilitiesKHR capabilities; - VK_CHECK( vkGetPhysicalDeviceSurfaceCapabilitiesKHR( physicalDeviceInUse, surface, &capabilities ) ); + VK_CHECK( vkGetPhysicalDeviceSurfaceCapabilitiesKHR( physical_device_in_use, surface, &capabilities ) ); // Image Count Calculation - swapchainImageCount = 3; + swapchain_image_count = 3; if ( capabilities.maxImageCount > 0 ) { - swapchainImageCount = std::min( swapchainImageCount, capabilities.maxImageCount ); + swapchain_image_count = std::min( swapchain_image_count, capabilities.maxImageCount ); } - swapchainImageCount = std::max( swapchainImageCount, capabilities.minImageCount + 1 ); + swapchain_image_count = std::max( swapchain_image_count, capabilities.minImageCount + 1 ); // Image Size calculation { auto [minWidth, minHeight] = capabilities.minImageExtent; auto [maxWidth, maxHeight] = capabilities.maxImageExtent; - swapchainExtent.width = Clamp( swapchainExtent.width, minWidth, maxWidth ); - swapchainExtent.height = Clamp( swapchainExtent.height, minHeight, maxHeight ); + swapchain_extent.width = std::clamp( swapchain_extent.width, minWidth, maxWidth ); + swapchain_extent.height = std::clamp( swapchain_extent.height, minHeight, maxHeight ); } - uint32_t surfaceFormatCount; - vkGetPhysicalDeviceSurfaceFormatsKHR( physicalDeviceInUse, surface, &surfaceFormatCount, nullptr ); - VkSurfaceFormatKHR* surfaceFormats = - reinterpret_cast( mem->allocate( sizeof( VkSurfaceFormatKHR ) * surfaceFormatCount ) ); - vkGetPhysicalDeviceSurfaceFormatsKHR( physicalDeviceInUse, surface, &surfaceFormatCount, surfaceFormats ); + uint32_t surface_format_count; + vkGetPhysicalDeviceSurfaceFormatsKHR( physical_device_in_use, surface, &surface_format_count, nullptr ); + VkSurfaceFormatKHR* surface_formats = + reinterpret_cast( mem->Allocate( sizeof( VkSurfaceFormatKHR ) * surface_format_count ) ); + vkGetPhysicalDeviceSurfaceFormatsKHR( physical_device_in_use, surface, &surface_format_count, surface_formats ); VkSurfaceFormatKHR format = { .format = VK_FORMAT_UNDEFINED, .colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, }; - for ( auto& surfaceFormat : std::span{ surfaceFormats, surfaceFormatCount } ) + for ( uint32_t i = 0; i < surface_format_count; ++i ) { - if ( surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR ) + VkSurfaceFormatKHR surface_format = surface_formats[i]; + + if ( surface_format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR ) { - SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "Color Space SRGB Found %d", surfaceFormat.format ); - if ( surfaceFormat.format == VK_FORMAT_R8G8B8A8_SRGB ) + SDL_LogInfo( SDL_LOG_CATEGORY_GPU, "Color Space SRGB Found %d", surface_format.format ); + if ( surface_format.format == VK_FORMAT_R8G8B8A8_SRGB ) { - format = surfaceFormat; + format = surface_format; break; } - if ( surfaceFormat.format == VK_FORMAT_B8G8R8A8_SRGB ) + if ( surface_format.format == VK_FORMAT_B8G8R8A8_SRGB ) { - format = surfaceFormat; + format = surface_format; break; } - if ( surfaceFormat.format == VK_FORMAT_R8G8B8A8_UNORM ) + if ( surface_format.format == VK_FORMAT_R8G8B8A8_UNORM ) { - format = surfaceFormat; + format = surface_format; } } } ASSERT( format.format != VK_FORMAT_UNDEFINED ); - swapchainFormat = format.format; + swapchain_format = format.format; - uint32_t presentModeCount; - vkGetPhysicalDeviceSurfacePresentModesKHR( physicalDeviceInUse, surface, &presentModeCount, nullptr ); - VkPresentModeKHR* presentModes = - reinterpret_cast( mem->allocate( sizeof( VkPresentModeKHR ) * presentModeCount ) ); - vkGetPhysicalDeviceSurfacePresentModesKHR( physicalDeviceInUse, surface, &presentModeCount, presentModes ); + uint32_t present_mode_count; + vkGetPhysicalDeviceSurfacePresentModesKHR( physical_device_in_use, surface, &present_mode_count, nullptr ); + VkPresentModeKHR* present_modes = + reinterpret_cast( mem->Allocate( sizeof( VkPresentModeKHR ) * present_mode_count ) ); + vkGetPhysicalDeviceSurfacePresentModesKHR( physical_device_in_use, surface, &present_mode_count, present_modes ); - VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; - for ( VkPresentModeKHR presentModeIter : std::span{ presentModes, presentModeCount } ) + VkPresentModeKHR present_mode = VK_PRESENT_MODE_FIFO_KHR; + for ( uint32_t i = 0; i < present_mode_count; ++i ) { - if ( presentModeIter == VK_PRESENT_MODE_FIFO_RELAXED_KHR ) + VkPresentModeKHR present_mode_iter = present_modes[i]; + if ( present_mode_iter == VK_PRESENT_MODE_FIFO_RELAXED_KHR ) { - presentMode = presentModeIter; + present_mode = present_mode_iter; break; } - if ( presentModeIter == VK_PRESENT_MODE_MAILBOX_KHR ) + if ( present_mode_iter == VK_PRESENT_MODE_MAILBOX_KHR ) { - presentMode = presentModeIter; + present_mode = present_mode_iter; } } - mem->restoreState( tempAllocStart ); + mem->RestoreState( temp_alloc_start ); - VkSwapchainCreateInfoKHR const swapchainCreateInfo = { + VkSwapchainCreateInfoKHR const swapchain_create_info = { .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, .pNext = nullptr, .flags = 0, .surface = surface, - .minImageCount = swapchainImageCount, + .minImageCount = swapchain_image_count, .imageFormat = format.format, .imageColorSpace = format.colorSpace, - .imageExtent = swapchainExtent, + .imageExtent = swapchain_extent, .imageArrayLayers = 1, .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, @@ -345,117 +352,119 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c .pQueueFamilyIndices = nullptr, .preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, - .presentMode = presentMode, + .presentMode = present_mode, .clipped = false, .oldSwapchain = nullptr, }; - VK_CHECK( vkCreateSwapchainKHR( device, &swapchainCreateInfo, nullptr, &swapchain ) ); + VK_CHECK( vkCreateSwapchainKHR( device, &swapchain_create_info, nullptr, &swapchain ) ); - swapchainImageCount = 0; - vkGetSwapchainImagesKHR( device, swapchain, &swapchainImageCount, nullptr ); - swapchainImages = reinterpret_cast( mem->allocate( sizeof( VkImage ) * swapchainImageCount ) ); - vkGetSwapchainImagesKHR( device, swapchain, &swapchainImageCount, swapchainImages ); + swapchain_image_count = 0; + vkGetSwapchainImagesKHR( device, swapchain, &swapchain_image_count, nullptr ); + swapchain_images = reinterpret_cast( mem->Allocate( sizeof( VkImage ) * swapchain_image_count ) ); + vkGetSwapchainImagesKHR( device, swapchain, &swapchain_image_count, swapchain_images ); - swapchainViews = reinterpret_cast( mem->allocate( sizeof( VkImageView ) * swapchainImageCount ) ); - for ( uint32_t i = 0; i != swapchainImageCount; ++i ) + swapchain_views = reinterpret_cast( mem->Allocate( sizeof( VkImageView ) * swapchain_image_count ) ); + for ( uint32_t i = 0; i != swapchain_image_count; ++i ) { - VkImageViewCreateInfo const viewCreateInfo = { - .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - .image = swapchainImages[i], - .viewType = VK_IMAGE_VIEW_TYPE_2D, - .format = format.format, - .components = { - VK_COMPONENT_SWIZZLE_IDENTITY, - VK_COMPONENT_SWIZZLE_IDENTITY, - VK_COMPONENT_SWIZZLE_IDENTITY, - VK_COMPONENT_SWIZZLE_IDENTITY - }, - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - } + VkComponentMapping constexpr component_mapping = { + VK_COMPONENT_SWIZZLE_IDENTITY, + VK_COMPONENT_SWIZZLE_IDENTITY, + VK_COMPONENT_SWIZZLE_IDENTITY, + VK_COMPONENT_SWIZZLE_IDENTITY, + }; + VkImageSubresourceRange constexpr subresource_range = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }; + VkImageViewCreateInfo const view_create_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + .image = swapchain_images[i], + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = format.format, + .components = component_mapping, + .subresourceRange = subresource_range, }; - VK_CHECK( vkCreateImageView( device, &viewCreateInfo, nullptr, &swapchainViews[i] ) ); + VK_CHECK( vkCreateImageView( device, &view_create_info, nullptr, &swapchain_views[i] ) ); } } // Init frames. - Frame* frames = reinterpret_cast( mem->allocate( sizeof( Frame ) * swapchainImageCount ) ); - for ( uint32_t i = 0; i != swapchainImageCount; ++i ) + Frame* frames = reinterpret_cast( mem->Allocate( sizeof( Frame ) * swapchain_image_count ) ); + for ( uint32_t i = 0; i != swapchain_image_count; ++i ) { - Frame_Create( frames + i, device, gpuAllocator, directQueueFamilyIndex.value(), swapchainExtent ); + frames[i] = Frame::Create( device, allocator, direct_queue_family_index.value(), swapchain_extent ); } - std::byte* allocation = mem->allocate( sizeof( RenderDevice ), alignof( RenderDevice ) ); + std::byte* allocation = mem->Allocate( sizeof( RenderDevice ), alignof( RenderDevice ) ); if ( not allocation ) return nullptr; - RenderDevice* renderDevice = new ( allocation ) RenderDevice{ + RenderDevice* render_device = new ( allocation ) RenderDevice{ instance, surface, - physicalDeviceInUse, + physical_device_in_use, device, - gpuAllocator, - directQueue, - directQueueFamilyIndex.value(), - swapchainFormat, - swapchainExtent, + allocator, + direct_queue, + direct_queue_family_index.value(), + swapchain_format, + swapchain_extent, swapchain, - swapchainImages, - swapchainViews, + swapchain_images, + swapchain_views, frames, - swapchainImageCount, + swapchain_image_count, }; - TextureManager* textureManager = TextureManager_Create( mem, renderDevice, 10000 ); - if ( !textureManager ) + TextureManager* texture_manager = TextureManager::Create( mem, render_device, 10000 ); + if ( !texture_manager ) { SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "TextureManager failed to init" ); - renderDevice->destroy(); + render_device->Destroy(); return nullptr; } - renderDevice->textureManager = textureManager; + render_device->textureManager = texture_manager; - ASSERT( renderDevice->textureManager ); + ASSERT( render_device->textureManager ); - BufferManager* bufferManager = BufferManager_Create( mem, renderDevice, 10000 ); - if ( !bufferManager ) + BufferManager* buffer_manager = BufferManager::Create( mem, render_device, 10000 ); + if ( !buffer_manager ) { SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "BufferManager failed to init" ); - renderDevice->destroy(); + render_device->Destroy(); return nullptr; } - renderDevice->bufferManager = bufferManager; + render_device->bufferManager = buffer_manager; - ASSERT( renderDevice->bufferManager ); + ASSERT( render_device->bufferManager ); - return renderDevice; + return render_device; } -inline bool RenderDevice::isInit() const +inline bool RenderDevice::IsInit() const { return instance and device and textureManager; } -void RenderDevice::destroy() +void RenderDevice::Destroy() { - if ( not isInit() ) return; + if ( not IsInit() ) return; - Take( bufferManager )->destroy(); - Take( textureManager )->destroy(); + Take( bufferManager )->Destroy(); + Take( textureManager )->Destroy(); - for ( Frame& frame : std::span{ Take( frames ), swapchainImageCount } ) + for ( size_t i = 0; i < swapchainImageCount; ++i ) { - frame.destroy( *this ); + frames[i].Destroy( *this ); } for ( auto const& view : std::span{ Take( swapchainViews ), swapchainImageCount } ) @@ -475,44 +484,45 @@ void RenderDevice::destroy() volkFinalize(); } -void RenderDevice::waitIdle() const +void RenderDevice::WaitIdle() const { VK_CHECK( vkDeviceWaitIdle( device ) ); } -uint32_t RenderDevice::getNumFrames() const +uint32_t RenderDevice::GetNumFrames() const { return swapchainImageCount; } RenderDevice::RenderDevice( - VkInstance const instance, - VkSurfaceKHR const surface, - VkPhysicalDevice const physicalDeviceInUse, - VkDevice const device, - VmaAllocator const gpuAllocator, - VkQueue const directQueue, - uint32_t const directQueueFamilyIndex, - VkFormat const swapchainFormat, - VkExtent2D const swapchainExtent, - VkSwapchainKHR const swapchain, - VkImage* swapchainImages, - VkImageView* swapchainViews, - Frame* frames, - uint32_t const swapchainImageCount ) + VkInstance const instance, + VkSurfaceKHR const surface, + VkPhysicalDevice const physical_device_in_use, + VkDevice const device, + VmaAllocator const allocator, + VkQueue const direct_queue, + uint32_t const direct_queue_family_index, + VkFormat const swapchain_format, + VkExtent2D const swapchain_extent, + VkSwapchainKHR const swapchain, + VkImage* swapchain_images, + VkImageView* swapchain_views, + Frame* frames, + uint32_t const swapchain_image_count ) : instance{ instance } , surface{ surface } - , physicalDeviceInUse{ physicalDeviceInUse } + , physicalDeviceInUse{ physical_device_in_use } , device{ device } - , gpuAllocator{ gpuAllocator } - , directQueue{ directQueue } - , directQueueFamilyIndex{ directQueueFamilyIndex } - , swapchainFormat{ swapchainFormat } - , swapchainExtent{ swapchainExtent } + , gpuAllocator{ allocator } + , directQueue{ direct_queue } + , directQueueFamilyIndex{ direct_queue_family_index } + , swapchainFormat{ swapchain_format } + , swapchainExtent{ swapchain_extent } , swapchain{ swapchain } - , swapchainImages{ swapchainImages } - , swapchainViews{ swapchainViews } + , swapchainImages{ swapchain_images } + , swapchainViews{ swapchain_views } , frames{ frames } - , swapchainImageCount{ swapchainImageCount } + , swapchainImageCount{ swapchain_image_count } , textureManager{ nullptr } + , bufferManager{ nullptr } {} diff --git a/Blaze/Source/RenderDevice.h b/Blaze/Source/RenderDevice.h index db54843..6f097d5 100644 --- a/Blaze/Source/RenderDevice.h +++ b/Blaze/Source/RenderDevice.h @@ -5,16 +5,16 @@ #include "VulkanHeader.h" - -struct BufferManager; +namespace Blaze +{ struct GlobalMemory; struct Frame; +struct BufferManager; struct TextureManager; /// The Rendering backend abstraction /// If this fails to initialize, we crash /// -/// TODO: Fail elegantly. struct RenderDevice { struct CreateInfo @@ -45,36 +45,34 @@ struct RenderDevice TextureManager* textureManager; BufferManager* bufferManager; - [[nodiscard]] bool isInit() const; - void destroy(); - void waitIdle() const; - [[nodiscard]] uint32_t getNumFrames() const; + [[nodiscard]] bool IsInit() const; + void WaitIdle() const; + [[nodiscard]] uint32_t GetNumFrames() const; + + static RenderDevice* Create( GlobalMemory* mem, RenderDevice::CreateInfo const& create_info ); + void Destroy(); RenderDevice( - VkInstance instance, - VkSurfaceKHR surface, - VkPhysicalDevice physicalDeviceInUse, - VkDevice device, - VmaAllocator gpuAllocator, - VkQueue directQueue, - uint32_t directQueueFamilyIndex, + VkInstance instance, + VkSurfaceKHR surface, + VkPhysicalDevice physical_device_in_use, + VkDevice device, + VmaAllocator allocator, + VkQueue direct_queue, + uint32_t direct_queue_family_index, - VkFormat swapchainFormat, - VkExtent2D swapchainExtent, - VkSwapchainKHR swapchain, + VkFormat swapchain_format, + VkExtent2D swapchain_extent, + VkSwapchainKHR swapchain, - VkImage* swapchainImages, - VkImageView* swapchainViews, - Frame* frames, - uint32_t swapchainImageCount ); - - RenderDevice( RenderDevice const& ) = delete; - RenderDevice& operator=( RenderDevice const& ) = delete; - - RenderDevice( RenderDevice&& ) noexcept = delete; - RenderDevice& operator=( RenderDevice&& ) noexcept = delete; + VkImage* swapchain_images, + VkImageView* swapchain_views, + Frame* frames, + uint32_t swapchain_image_count ); +#if defined( DTOR_TEST ) ~RenderDevice(); +#endif }; -RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo const& createInfo ); +} // namespace Blaze diff --git a/Blaze/Source/TextureManager.cpp b/Blaze/Source/TextureManager.cpp index 6767628..42fa04e 100644 --- a/Blaze/Source/TextureManager.cpp +++ b/Blaze/Source/TextureManager.cpp @@ -5,32 +5,30 @@ #include "GlobalMemory.h" #include "RenderDevice.h" -template struct RID; +using Blaze::TextureManager; -TextureID TextureManager::createTexture( VkExtent3D const extent, VkSampler const sampler, VkFormat const format ) +Blaze::TextureID TextureManager::CreateTexture( + VkExtent3D const extent, VkSampler const sampler, VkFormat const format ) { - ASSERT( not m_freeList.empty() ); + ASSERT( not m_freeList.Empty() ); - Texture* textureSlot = reinterpret_cast( m_freeList.popFront() ); + Texture* texture_slot = reinterpret_cast( m_freeList.PopFront() ); ++m_count; - ASSERT( m_pRenderDevice ); - RenderDevice const& renderDevice = *m_pRenderDevice; - VkImage texture; - VmaAllocation textureAllocation; - VkImageView textureView; + VmaAllocation texture_allocation; + VkImageView texture_view; - uint32_t const mipLevels = calculateRequiredMipLevels( extent.width, extent.height, extent.depth ); + uint32_t const mip_levels = CalculateRequiredMipLevels( extent.width, extent.height, extent.depth ); - VkImageCreateInfo const imageCreateInfo = { + VkImageCreateInfo const image_create_info = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = nullptr, .flags = 0, .imageType = VK_IMAGE_TYPE_2D, .format = format, .extent = extent, - .mipLevels = mipLevels, + .mipLevels = mip_levels, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL, @@ -41,7 +39,7 @@ TextureID TextureManager::createTexture( VkExtent3D const extent, VkSampler cons .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, }; - VmaAllocationCreateInfo constexpr allocationCreateInfo = { + VmaAllocationCreateInfo constexpr allocation_create_info = { .flags = 0, .usage = VMA_MEMORY_USAGE_AUTO, .requiredFlags = 0, @@ -53,121 +51,126 @@ TextureID TextureManager::createTexture( VkExtent3D const extent, VkSampler cons }; VK_CHECK( vmaCreateImage( - renderDevice.gpuAllocator, &imageCreateInfo, &allocationCreateInfo, &texture, &textureAllocation, nullptr ) ); + m_renderDevice->gpuAllocator, + &image_create_info, + &allocation_create_info, + &texture, + &texture_allocation, + nullptr ) ); - VkImageSubresourceRange const subresourceRange = { + VkImageSubresourceRange const subresource_range = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, - .levelCount = mipLevels, + .levelCount = mip_levels, .baseArrayLayer = 0, .layerCount = 1, }; - VkComponentMapping constexpr componentMapping = { + VkComponentMapping constexpr component_mapping = { .r = VK_COMPONENT_SWIZZLE_IDENTITY, .g = VK_COMPONENT_SWIZZLE_IDENTITY, .b = VK_COMPONENT_SWIZZLE_IDENTITY, .a = VK_COMPONENT_SWIZZLE_IDENTITY, }; - VkImageViewCreateInfo const imageViewCreateInfo = { + VkImageViewCreateInfo const image_view_create_info = { .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .pNext = nullptr, .flags = 0, .image = texture, .viewType = VK_IMAGE_VIEW_TYPE_2D, - .format = imageCreateInfo.format, - .components = componentMapping, - .subresourceRange = subresourceRange, + .format = image_create_info.format, + .components = component_mapping, + .subresourceRange = subresource_range, }; - VK_CHECK( vkCreateImageView( renderDevice.device, &imageViewCreateInfo, nullptr, &textureView ) ); + VK_CHECK( vkCreateImageView( m_renderDevice->device, &image_view_create_info, nullptr, &texture_view ) ); // NOTE: textureSlot preserves index between uses. - uint32_t index = textureSlot->index; - new ( textureSlot ) Texture{ + uint32_t index = texture_slot->index; + new ( texture_slot ) Texture{ .image = texture, - .allocation = textureAllocation, - .view = textureView, + .allocation = texture_allocation, + .view = texture_view, .extent = extent, .format = format, .index = index, }; - uint32_t const innerIndex = index & INDEX_MASK; + uint32_t const inner_index = index & kIndexMask; // TODO: Batch all writes. - VkDescriptorImageInfo const descriptorImageInfo = { + VkDescriptorImageInfo const descriptor_image_info = { .sampler = sampler, - .imageView = textureView, + .imageView = texture_view, .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, }; - VkWriteDescriptorSet const descriptorWrite = { + VkWriteDescriptorSet const descriptor_write = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .pNext = nullptr, .dstSet = m_descriptorSet, .dstBinding = 0, - .dstArrayElement = innerIndex, + .dstArrayElement = inner_index, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - .pImageInfo = &descriptorImageInfo, + .pImageInfo = &descriptor_image_info, .pBufferInfo = nullptr, .pTexelBufferView = nullptr, }; - vkUpdateDescriptorSets( renderDevice.device, 1, &descriptorWrite, 0, nullptr ); + vkUpdateDescriptorSets( m_renderDevice->device, 1, &descriptor_write, 0, nullptr ); // NOTE: Memory hackery to create TextureID; return *reinterpret_cast( &index ); } -bool TextureManager::isValidID( TextureID const& rid ) const +bool TextureManager::IsValidID( TextureID const& rid ) const { - uint32_t const index = *reinterpret_cast( &rid ); - uint32_t const innerIndex = index & INDEX_MASK; + uint32_t const index = *reinterpret_cast( &rid ); + uint32_t const inner_index = index & kIndexMask; - if ( innerIndex > m_capacity ) return false; + if ( inner_index > m_capacity ) return false; - return m_aTextures[innerIndex].index == index; + return m_textures[inner_index].index == index; } -void TextureManager::freeTexture( TextureID* rid ) +void TextureManager::FreeTexture( TextureID* rid ) { - if ( not isValidID( *rid ) ) return; + if ( not IsValidID( *rid ) ) return; - Texture& texture = fetchTextureUnchecked( *rid ); + Texture& texture = FetchTextureUnchecked( *rid ); - destroyTexture( texture ); + DestroyTexture( texture ); *rid = {}; } -std::optional TextureManager::fetchImage( TextureID const& rid ) +std::optional TextureManager::FetchImage( TextureID const& rid ) { - if ( not isValidID( rid ) ) return std::nullopt; + if ( not IsValidID( rid ) ) return std::nullopt; - return fetchTextureUnchecked( rid ).image; + return FetchTextureUnchecked( rid ).image; } -std::optional TextureManager::fetchImageView( TextureID const& rid ) +std::optional TextureManager::FetchImageView( TextureID const& rid ) { - if ( not isValidID( rid ) ) return std::nullopt; + if ( not IsValidID( rid ) ) return std::nullopt; - return fetchTextureUnchecked( rid ).view; + return FetchTextureUnchecked( rid ).view; } -VkDescriptorSetLayout const& TextureManager::descriptorLayout() const +VkDescriptorSetLayout const& TextureManager::DescriptorLayout() const { return m_descriptorSetLayout; } -VkDescriptorSet const& TextureManager::descriptorSet() const +VkDescriptorSet const& TextureManager::DescriptorSet() const { return m_descriptorSet; } -void TextureManager::destroy() +void TextureManager::Destroy() { #if defined( _DEBUG ) if ( m_count > 0 ) @@ -176,106 +179,102 @@ void TextureManager::destroy() } #endif - ASSERT( m_pRenderDevice ); - RenderDevice const& renderDevice = *m_pRenderDevice; + ASSERT( m_renderDevice ); - while ( not m_freeList.empty() ) + while ( not m_freeList.Empty() ) { - Texture* tex = reinterpret_cast( m_freeList.popFront() ); + Texture* tex = reinterpret_cast( m_freeList.PopFront() ); memset( tex, 0, sizeof *tex ); } - for ( Texture& tex : std::span{ m_aTextures, m_count } ) + for ( Texture& tex : std::span{ m_textures, m_count } ) { - destroyTexture( tex ); + DestroyTexture( tex ); } m_descriptorSet = nullptr; - vkDestroyDescriptorPool( renderDevice.device, Take( m_descriptorPool ), nullptr ); - vkDestroyDescriptorSetLayout( renderDevice.device, Take( m_descriptorSetLayout ), nullptr ); + vkDestroyDescriptorPool( m_renderDevice->device, Take( m_descriptorPool ), nullptr ); + vkDestroyDescriptorSetLayout( m_renderDevice->device, Take( m_descriptorSetLayout ), nullptr ); } TextureManager::~TextureManager() { - ASSERT( not m_aTextures ); + ASSERT( not m_textures ); } -void TextureManager::destroyTexture( Texture& tex ) +void TextureManager::DestroyTexture( Texture& tex ) { if ( not tex.image ) return; - ASSERT( m_pRenderDevice ); + ASSERT( m_renderDevice ); - uint32_t const index = tex.index; - uint32_t const innerIndex = index & INDEX_MASK; - uint32_t const generation = ( index & GENERATION_MASK ) >> GENERATION_OFFSET; + uint32_t const index = tex.index; + uint32_t const inner_index = index & kIndexMask; + uint32_t const generation = ( index & kGenerationMask ) >> kGenerationOffset; - RenderDevice const& renderDevice = *m_pRenderDevice; + vkDestroyImageView( m_renderDevice->device, Take( tex.view ), nullptr ); - vkDestroyImageView( renderDevice.device, Take( tex.view ), nullptr ); - - vmaDestroyImage( renderDevice.gpuAllocator, Take( tex.image ), Take( tex.allocation ) ); + vmaDestroyImage( m_renderDevice->gpuAllocator, Take( tex.image ), Take( tex.allocation ) ); tex.extent = {}; tex.format = VK_FORMAT_UNDEFINED; - tex.index = innerIndex | ( generation + 1 ) << GENERATION_OFFSET; + tex.index = inner_index | ( generation + 1 ) << kGenerationOffset; // NOTE: DO NOT EDIT INNER INDEX. - ASSERT( innerIndex == ( tex.index & INDEX_MASK ) and "Index should not be modified" ); + ASSERT( inner_index == ( tex.index & kIndexMask ) and "Index should not be modified" ); ASSERT( tex.index > index and "Generation should increase." ); - m_freeList.pushBack( reinterpret_cast( &tex ) ); + m_freeList.PushBack( reinterpret_cast( &tex ) ); --m_count; } -uint32_t TextureManager::calculateRequiredMipLevels( uint32_t const w, uint32_t const h, uint32_t const d ) +uint32_t TextureManager::CalculateRequiredMipLevels( uint32_t const w, uint32_t const h, uint32_t const d ) { - uint32_t const maxDim = std::max( std::max( w, h ), d ); - return 1 + static_cast( floorf( log2f( static_cast( maxDim ) ) ) ); + uint32_t const max_dim = std::max( std::max( w, h ), d ); + return 1 + static_cast( floorf( log2f( static_cast( max_dim ) ) ) ); } -Texture& TextureManager::fetchTextureUnchecked( TextureID const& rid ) +Blaze::Texture& TextureManager::FetchTextureUnchecked( TextureID const& rid ) { - uint32_t const index = *reinterpret_cast( &rid ); - uint32_t const innerIndex = index & INDEX_MASK; + uint32_t const index = *reinterpret_cast( &rid ); + uint32_t const inner_index = index & kIndexMask; - return m_aTextures[innerIndex]; + return m_textures[inner_index]; } - TextureManager::TextureManager( - RenderDevice* pRenderDevice, - Texture* aTextures, - uint32_t const capacity, - VkDescriptorSetLayout const setLayout, - VkDescriptorPool const pool, - VkDescriptorSet const descriptorSet ) - : m_pRenderDevice{ pRenderDevice } - , m_aTextures{ aTextures } + Blaze::RenderDevice* render_device, + Texture* textures, + uint32_t const capacity, + VkDescriptorSetLayout const set_layout, + VkDescriptorPool const pool, + VkDescriptorSet const descriptor_set ) + : m_renderDevice{ render_device } + , m_textures{ textures } , m_count{ 0 } , m_capacity{ capacity } - , m_descriptorSetLayout{ setLayout } + , m_descriptorSetLayout{ set_layout } , m_descriptorPool{ pool } - , m_descriptorSet{ descriptorSet } + , m_descriptorSet{ descriptor_set } { uint32_t i = 0; - for ( Texture& tex : std::span{ m_aTextures, m_capacity } ) + for ( Texture& tex : std::span{ m_textures, m_capacity } ) { // Default Generation is 1 - tex.index = i++ | ( 1 << GENERATION_OFFSET ); - m_freeList.pushFront( reinterpret_cast( &tex ) ); + tex.index = i++ | ( 1 << kGenerationOffset ); + m_freeList.PushFront( reinterpret_cast( &tex ) ); } } -TextureManager* TextureManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t const maxCount ) +TextureManager* TextureManager::Create( GlobalMemory* mem, RenderDevice* render_device, uint32_t const max_count ) { - Texture* textures = reinterpret_cast( mem->allocate( maxCount * sizeof( Texture ), alignof( Texture ) ) ); + Texture* textures = reinterpret_cast( mem->Allocate( max_count * sizeof( Texture ), alignof( Texture ) ) ); if ( not textures ) return nullptr; - VkDescriptorSetLayoutBinding const descriptorSetLayoutBinding{ + VkDescriptorSetLayoutBinding const descriptor_set_layout_binding{ .binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - .descriptorCount = maxCount, + .descriptorCount = max_count, .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, .pImmutableSamplers = nullptr, }; @@ -284,56 +283,56 @@ TextureManager* TextureManager_Create( GlobalMemory* mem, RenderDevice* renderDe VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT; - VkDescriptorSetLayoutBindingFlagsCreateInfo const bindlessBinding = { + VkDescriptorSetLayoutBindingFlagsCreateInfo const bindless_binding = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO, .pNext = nullptr, .bindingCount = 1, .pBindingFlags = &flags, }; - VkDescriptorSetLayoutCreateInfo const descriptorSetLayoutCreateInfo = { + VkDescriptorSetLayoutCreateInfo const descriptor_set_layout_create_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, - .pNext = &bindlessBinding, + .pNext = &bindless_binding, .flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT, .bindingCount = 1, - .pBindings = &descriptorSetLayoutBinding, + .pBindings = &descriptor_set_layout_binding, }; - VkDescriptorSetLayout descriptorSetLayout; + VkDescriptorSetLayout descriptor_set_layout; VK_CHECK( vkCreateDescriptorSetLayout( - renderDevice->device, &descriptorSetLayoutCreateInfo, nullptr, &descriptorSetLayout ) ); + render_device->device, &descriptor_set_layout_create_info, nullptr, &descriptor_set_layout ) ); - VkDescriptorPoolSize const poolSize = { + VkDescriptorPoolSize const pool_size = { .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - .descriptorCount = maxCount, + .descriptorCount = max_count, }; - VkDescriptorPoolCreateInfo const descriptorPoolCreateInfo = { + VkDescriptorPoolCreateInfo const descriptor_pool_create_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .pNext = nullptr, .flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT, .maxSets = 1, .poolSizeCount = 1, - .pPoolSizes = &poolSize, + .pPoolSizes = &pool_size, }; - VkDescriptorPool descriptorPool; - VK_CHECK( vkCreateDescriptorPool( renderDevice->device, &descriptorPoolCreateInfo, nullptr, &descriptorPool ) ); + VkDescriptorPool descriptor_pool; + VK_CHECK( vkCreateDescriptorPool( render_device->device, &descriptor_pool_create_info, nullptr, &descriptor_pool ) ); - VkDescriptorSetAllocateInfo const descriptorSetAllocateInfo = { + VkDescriptorSetAllocateInfo const descriptor_set_allocate_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .pNext = nullptr, - .descriptorPool = descriptorPool, + .descriptorPool = descriptor_pool, .descriptorSetCount = 1, - .pSetLayouts = &descriptorSetLayout, + .pSetLayouts = &descriptor_set_layout, }; - VkDescriptorSet descriptorSet; - VK_CHECK( vkAllocateDescriptorSets( renderDevice->device, &descriptorSetAllocateInfo, &descriptorSet ) ); + VkDescriptorSet descriptor_set; + VK_CHECK( vkAllocateDescriptorSets( render_device->device, &descriptor_set_allocate_info, &descriptor_set ) ); - std::byte* allocation = mem->allocate( sizeof( TextureManager ), alignof( TextureManager ) ); + std::byte* allocation = mem->Allocate( sizeof( TextureManager ), alignof( TextureManager ) ); if ( not allocation ) return nullptr; return new ( allocation ) - TextureManager{ renderDevice, textures, maxCount, descriptorSetLayout, descriptorPool, descriptorSet }; + TextureManager{ render_device, textures, max_count, descriptor_set_layout, descriptor_pool, descriptor_set }; } diff --git a/Blaze/Source/TextureManager.h b/Blaze/Source/TextureManager.h index 7ac6ac9..fff48f8 100644 --- a/Blaze/Source/TextureManager.h +++ b/Blaze/Source/TextureManager.h @@ -9,6 +9,8 @@ #include "RenderDevice.h" #include "VulkanHeader.h" +namespace Blaze +{ struct GlobalMemory; struct RenderDevice; @@ -22,10 +24,10 @@ struct Texture uint32_t index; }; -static_assert( sizeof( Texture ) > sizeof( FreeList::Node ) and "Texture is used intrusively by FreeList" ); +static_assert( sizeof( Texture ) > sizeof( Util::FreeList::Node ) and "Texture is used intrusively by FreeList" ); static_assert( - offsetof( Texture, index ) >= sizeof( FreeList::Node ) and - "Index should not be overwritten even in invalid state" ); + offsetof( Texture, index ) >= sizeof( Util::FreeList::Node ) and + "Index should not be overwritten even in invalid state" ); extern template struct RID; using TextureID = RID; @@ -33,61 +35,63 @@ using TextureID = RID; struct TextureManager { private: - constexpr static uint32_t INDEX_MASK = 0x0007FFFF; - constexpr static uint32_t GENERATION_MASK = ~INDEX_MASK; - constexpr static uint32_t GENERATION_OFFSET = 19; + constexpr static uint32_t kIndexMask = 0x0007FFFF; + constexpr static uint32_t kGenerationMask = ~kIndexMask; + constexpr static uint32_t kGenerationOffset = 19; static_assert( - ( ( GENERATION_MASK >> GENERATION_OFFSET & 0x1 ) == 0x1 ) and - ( ( GENERATION_MASK >> ( GENERATION_OFFSET - 1 ) & 0x1 ) != 0x1 ) and "Checks boundary" ); + ( ( kGenerationMask >> kGenerationOffset & 0x1 ) == 0x1 ) and + ( ( kGenerationMask >> ( kGenerationOffset - 1 ) & 0x1 ) != 0x1 ) and "Checks boundary" ); - RenderDevice* m_pRenderDevice; + RenderDevice* m_renderDevice; // Texture Manager - Texture* m_aTextures; - uint32_t m_count; - uint32_t m_capacity; - FreeList m_freeList; + Texture* m_textures; + uint32_t m_count; + uint32_t m_capacity; + Util::FreeList m_freeList; // Bindless Descriptor Info VkDescriptorSetLayout m_descriptorSetLayout; VkDescriptorPool m_descriptorPool; VkDescriptorSet m_descriptorSet; - void destroyTexture( Texture& tex ); + void DestroyTexture( Texture& tex ); - Texture& fetchTextureUnchecked( TextureID const& rid ); + Texture& FetchTextureUnchecked( TextureID const& rid ); public: - static uint32_t calculateRequiredMipLevels( uint32_t w, uint32_t h, uint32_t d ); + static uint32_t CalculateRequiredMipLevels( uint32_t w, uint32_t h, uint32_t d ); - [[nodiscard]] bool isValidID( TextureID const& rid ) const; + [[nodiscard]] bool IsValidID( TextureID const& rid ) const; // [[nodiscard]] std::optional createTexture( VkExtent3D extent ); - void freeTexture( TextureID* rid ); + void FreeTexture( TextureID* rid ); DEPRECATE_JULY_2025 - [[nodiscard]] TextureID createTexture( - VkExtent3D extent, VkSampler sampler, VkFormat format = VK_FORMAT_R8G8B8A8_SRGB ); + [[nodiscard]] TextureID CreateTexture( + VkExtent3D extent, VkSampler sampler, VkFormat format = VK_FORMAT_R8G8B8A8_SRGB ); DEPRECATE_JULY_2025 - std::optional fetchImage( TextureID const& rid ); + std::optional FetchImage( TextureID const& rid ); DEPRECATE_JULY_2025 - std::optional fetchImageView( TextureID const& rid ); + std::optional FetchImageView( TextureID const& rid ); - [[nodiscard]] VkDescriptorSetLayout const& descriptorLayout() const; - [[nodiscard]] VkDescriptorSet const& descriptorSet() const; + [[nodiscard]] VkDescriptorSetLayout const& DescriptorLayout() const; + [[nodiscard]] VkDescriptorSet const& DescriptorSet() const; // TextureManager( - RenderDevice* pRenderDevice, - Texture* aTextures, - uint32_t capacity, - VkDescriptorSetLayout setLayout, - VkDescriptorPool pool, - VkDescriptorSet descriptorSet ); - void destroy(); + RenderDevice* render_device, + Texture* textures, + uint32_t capacity, + VkDescriptorSetLayout set_layout, + VkDescriptorPool pool, + VkDescriptorSet descriptor_set ); + + static TextureManager* Create( GlobalMemory* mem, RenderDevice* render_device, uint32_t max_count ); + void Destroy(); TextureManager( TextureManager const& other ) = delete; TextureManager( TextureManager&& other ) noexcept = delete; @@ -96,4 +100,4 @@ public: ~TextureManager(); }; -TextureManager* TextureManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t maxCount ); +} // namespace Blaze