diff --git a/.clang-format b/.clang-format index 109e0b7fb8..24d96eccb1 100644 --- a/.clang-format +++ b/.clang-format @@ -19,7 +19,7 @@ AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: true BinPackArguments: true -BinPackParameters: true +BinPackParameters: false BraceWrapping: AfterCaseLabel: true AfterClass: true @@ -45,7 +45,7 @@ BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: AfterColon BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true -ColumnLimit: 0 +ColumnLimit: 160 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: true diff --git a/app/apps/apps.h b/app/apps/apps.h index 8c2917db54..3a22c552f5 100644 --- a/app/apps/apps.h +++ b/app/apps/apps.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2024, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -44,8 +44,7 @@ using CreateFunc = std::function()>; class AppInfo { public: - AppInfo(const std::string &id, const CreateFunc &create) : - id(id), create(create) + AppInfo(const std::string &id, const CreateFunc &create) : id(id), create(create) {} std::string id; @@ -59,7 +58,13 @@ class AppInfo class SampleInfo : public AppInfo { public: - SampleInfo(const std::string &id, const CreateFunc &create, const std::string &category, const std::string &author, const std::string &name, const std::string &description, const std::vector &tags = {}) : + SampleInfo(const std::string &id, + const CreateFunc &create, + const std::string &category, + const std::string &author, + const std::string &name, + const std::string &description, + const std::vector &tags = {}) : AppInfo(id, create), category(category), author(author), name(name), description(description), tags(tags) {} diff --git a/app/plugins/batch_mode/batch_mode.cpp b/app/plugins/batch_mode/batch_mode.cpp index 98a56f291a..a4ac7c2c4e 100644 --- a/app/plugins/batch_mode/batch_mode.cpp +++ b/app/plugins/batch_mode/batch_mode.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -34,8 +34,7 @@ BatchMode::BatchMode() : {"skip", "Skip a sample by id"}, {"tag", "Filter samples by tags"}, {"wrap-to-start", "Once all configurations have run wrap to the start"}}) -{ -} +{} bool BatchMode::handle_command(std::deque &arguments) const { @@ -143,8 +142,8 @@ void BatchMode::trigger_command() std::vector filtered_list; filtered_list.reserve(sample_list.size() - skips.size()); - std::copy_if( - sample_list.begin(), sample_list.end(), std::back_inserter(filtered_list), [&](const apps::AppInfo *app) { return !skips.count(app->id); }); + std::copy_if(sample_list.begin(), sample_list.end(), std::back_inserter(filtered_list), + [&](const apps::AppInfo *app) { return !skips.count(app->id); }); if (filtered_list.size() != sample_list.size()) { diff --git a/app/plugins/batch_mode/batch_mode.h b/app/plugins/batch_mode/batch_mode.h index 3e7808b376..bc75c05607 100644 --- a/app/plugins/batch_mode/batch_mode.h +++ b/app/plugins/batch_mode/batch_mode.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -34,7 +34,8 @@ using BatchModeTags = vkb::PluginBase &arguments) { diff --git a/app/plugins/benchmark_mode/benchmark_mode.h b/app/plugins/benchmark_mode/benchmark_mode.h index 4e75d315d2..b06fbe24b5 100644 --- a/app/plugins/benchmark_mode/benchmark_mode.h +++ b/app/plugins/benchmark_mode/benchmark_mode.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -29,7 +29,8 @@ using BenchmarkModeTags = vkb::PluginBase; /** * @brief Benchmark Mode * - * When enabled frame time statistics of a samples run will be printed to the console when an application closes. The simulation frame time (delta time) is also locked to 60FPS so that statistics can be compared more accurately across different devices. + * When enabled frame time statistics of a samples run will be printed to the console when an application closes. The simulation frame time (delta time) is also + * locked to 60FPS so that statistics can be compared more accurately across different devices. * * Usage: vulkan_samples sample afbc --benchmark * diff --git a/app/plugins/data_path/data_path.cpp b/app/plugins/data_path/data_path.cpp index 5a31caac96..2e75ab3f15 100644 --- a/app/plugins/data_path/data_path.cpp +++ b/app/plugins/data_path/data_path.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, Arm Limited and Contributors +/* Copyright (c) 2022-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -28,8 +28,7 @@ DataPath::DataPath() : {vkb::Hook::OnAppStart}, {}, {{"data-path", "Folder containing data files"}}) -{ -} +{} bool DataPath::handle_option(std::deque &arguments) { diff --git a/app/plugins/file_logger/file_logger.cpp b/app/plugins/file_logger/file_logger.cpp index 0e70d8d9dc..25169f971e 100644 --- a/app/plugins/file_logger/file_logger.cpp +++ b/app/plugins/file_logger/file_logger.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2021-2025, Arm Limited and Contributors - * Copyright (c) 2021-2025, Sascha Willems +/* Copyright (c) 2021-2026, Arm Limited and Contributors + * Copyright (c) 2021-2026, Sascha Willems * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -27,10 +27,8 @@ namespace plugins { -FileLogger::FileLogger() : - FileLoggerTags("File Logger", "Enable log output to a file.", {}, {}, {{"log-file", "Write log messages to the given file name"}}) -{ -} +FileLogger::FileLogger() : FileLoggerTags("File Logger", "Enable log output to a file.", {}, {}, {{"log-file", "Write log messages to the given file name"}}) +{} bool FileLogger::handle_option(std::deque &arguments) { diff --git a/app/plugins/file_logger/file_logger.h b/app/plugins/file_logger/file_logger.h index 89bbdc9597..f39848f985 100644 --- a/app/plugins/file_logger/file_logger.h +++ b/app/plugins/file_logger/file_logger.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors - * Copyright (c) 2021-2025, Sascha Willems +/* Copyright (c) 2020-2026, Arm Limited and Contributors + * Copyright (c) 2021-2026, Sascha Willems * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -27,11 +27,11 @@ using FileLoggerTags = vkb::PluginBase; /** * @brief File Logger - * + * * Enables writing log messages to a file - * + * * Usage: vulkan_sample --log-file filename.txt - * + * */ class FileLogger : public FileLoggerTags { diff --git a/app/plugins/force_close/force_close.cpp b/app/plugins/force_close/force_close.cpp index c1cd37ca04..ec7089df45 100644 --- a/app/plugins/force_close/force_close.cpp +++ b/app/plugins/force_close/force_close.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -28,8 +28,7 @@ ForceClose::ForceClose() : {}, {}, {{"force-close", "Force the close of the application if halted before exiting"}}) -{ -} +{} bool ForceClose::handle_option(std::deque &arguments) { diff --git a/app/plugins/fps_logger/fps_logger.cpp b/app/plugins/fps_logger/fps_logger.cpp index a4a9ab3754..3b9e1f47e3 100644 --- a/app/plugins/fps_logger/fps_logger.cpp +++ b/app/plugins/fps_logger/fps_logger.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -20,10 +20,8 @@ namespace plugins { -FpsLogger::FpsLogger() : - FpsLoggerTags("FPS Logger", "Enable FPS logging.", {vkb::Hook::OnUpdate, vkb::Hook::OnAppStart}, {}, {{"log-fps", "Log FPS"}}) -{ -} +FpsLogger::FpsLogger() : FpsLoggerTags("FPS Logger", "Enable FPS logging.", {vkb::Hook::OnUpdate, vkb::Hook::OnAppStart}, {}, {{"log-fps", "Log FPS"}}) +{} bool FpsLogger::handle_option(std::deque &arguments) { diff --git a/app/plugins/gpu_selection/gpu_selection.cpp b/app/plugins/gpu_selection/gpu_selection.cpp index 02f72a6abd..baaed28c8d 100644 --- a/app/plugins/gpu_selection/gpu_selection.cpp +++ b/app/plugins/gpu_selection/gpu_selection.cpp @@ -30,8 +30,7 @@ GpuSelection::GpuSelection() : {}, {}, {{"gpu", "Zero-based index of the GPU that the sample should use"}}) -{ -} +{} bool GpuSelection::handle_option(std::deque &arguments) { diff --git a/app/plugins/screenshot/screenshot.cpp b/app/plugins/screenshot/screenshot.cpp index 0c677d2b8b..2b6b097811 100644 --- a/app/plugins/screenshot/screenshot.cpp +++ b/app/plugins/screenshot/screenshot.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -32,8 +32,7 @@ Screenshot::Screenshot() : {vkb::Hook::OnUpdate, vkb::Hook::OnAppStart, vkb::Hook::PostDraw}, {}, {{"screenshot", "Take a screenshot at a given frame"}, {"screenshot-output", "Declare an output name for the image"}}) -{ -} +{} bool Screenshot::handle_option(std::deque &arguments) { diff --git a/app/plugins/shading_language_selection/shading_language_selection.cpp b/app/plugins/shading_language_selection/shading_language_selection.cpp index d7b63fa9b9..2580945d3c 100644 --- a/app/plugins/shading_language_selection/shading_language_selection.cpp +++ b/app/plugins/shading_language_selection/shading_language_selection.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2024-2025, Sascha Willems +/* Copyright (c) 2024-2026, Sascha Willems * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -30,8 +30,7 @@ ShadingLanguageSelection::ShadingLanguageSelection() : {}, {}, {{"shading-language", "Shading language to use (glsl, hlsl or slang)"}}) -{ -} +{} bool ShadingLanguageSelection::handle_option(std::deque &arguments) { diff --git a/app/plugins/start_sample/start_sample.cpp b/app/plugins/start_sample/start_sample.cpp index 1d1d3cf7ef..9965259170 100644 --- a/app/plugins/start_sample/start_sample.cpp +++ b/app/plugins/start_sample/start_sample.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -29,8 +29,7 @@ StartSample::StartSample() : {{"sample", "Run a specific sample"}, {"samples", "List available samples with descriptions"}, {"samples-oneline", "List available samples, one per line"}}) -{ -} +{} void StartSample::launch_sample(apps::SampleInfo const *sample) const { diff --git a/app/plugins/start_test/start_test.cpp b/app/plugins/start_test/start_test.cpp index ce46568d0e..6f84b19752 100644 --- a/app/plugins/start_test/start_test.cpp +++ b/app/plugins/start_test/start_test.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -22,10 +22,8 @@ namespace plugins { -StartTest::StartTest() : - StartTestTags("Tests", "A collection of flags to run tests.", {}, {{"test", "Run a specific test"}}) -{ -} +StartTest::StartTest() : StartTestTags("Tests", "A collection of flags to run tests.", {}, {{"test", "Run a specific test"}}) +{} bool StartTest::handle_command(std::deque &arguments) const { diff --git a/app/plugins/stop_after/stop_after.cpp b/app/plugins/stop_after/stop_after.cpp index 3a17e0ddf9..7090c54210 100644 --- a/app/plugins/stop_after/stop_after.cpp +++ b/app/plugins/stop_after/stop_after.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -26,8 +26,7 @@ StopAfter::StopAfter() : {vkb::Hook::OnUpdate}, {}, {{"stop-after-frame", "Stop the application after a certain number of frames"}}) -{ -} +{} bool StopAfter::handle_option(std::deque &arguments) { diff --git a/app/plugins/user_interface_options/user_interface_options.cpp b/app/plugins/user_interface_options/user_interface_options.cpp index b450f13f94..76e7bc8165 100644 --- a/app/plugins/user_interface_options/user_interface_options.cpp +++ b/app/plugins/user_interface_options/user_interface_options.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Sascha Willems +/* Copyright (c) 2023-2026, Sascha Willems * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -30,8 +30,7 @@ UserInterfaceOptions::UserInterfaceOptions() : {}, {}, {{"hideui", "If flag is set, hides the user interface at startup"}}) -{ -} +{} bool UserInterfaceOptions::handle_option(std::deque &arguments) { diff --git a/app/plugins/window_options/window_options.cpp b/app/plugins/window_options/window_options.cpp index 75158aa263..ccd8b0fff5 100644 --- a/app/plugins/window_options/window_options.cpp +++ b/app/plugins/window_options/window_options.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -37,8 +37,7 @@ WindowOptions::WindowOptions() : {"stretch", "Stretch window to fullscreen (direct-to-display only)"}, {"vsync", "Force vsync {ON | OFF}. If not set samples decide how vsync is set"}, {"width", "Initial window width"}}) -{ -} +{} bool WindowOptions::handle_option(std::deque &arguments) { diff --git a/components/android/src/context.cpp b/components/android/src/context.cpp index fd44fa8cc1..1971c0f691 100644 --- a/components/android/src/context.cpp +++ b/components/android/src/context.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2024, Thomas Atkinson +/* Copyright (c) 2023-2026, Thomas Atkinson * * SPDX-License-Identifier: Apache-2.0 * @@ -22,8 +22,7 @@ extern "C" { // TODO: Arguments can be parsed from the bundle - JNIEXPORT void JNICALL - Java_com_khronos_vulkan_1samples_SampleLauncherActivity_sendArgumentsToPlatform(JNIEnv *env, jobject thiz, jobjectArray arg_strings) + JNIEXPORT void JNICALL Java_com_khronos_vulkan_1samples_SampleLauncherActivity_sendArgumentsToPlatform(JNIEnv *env, jobject thiz, jobjectArray arg_strings) { std::vector args; @@ -75,8 +74,7 @@ namespace vkb { std::vector AndroidPlatformContext::android_arguments = {}; -AndroidPlatformContext::AndroidPlatformContext(android_app *app) : - PlatformContext{}, app{app} +AndroidPlatformContext::AndroidPlatformContext(android_app *app) : PlatformContext{}, app{app} { _external_storage_directory = details::get_external_storage_directory(app); _temp_directory = details::get_external_cache_directory(app); diff --git a/components/filesystem/include/filesystem/legacy.h b/components/filesystem/include/filesystem/legacy.h index 25c91c0ad6..2a509b2d62 100644 --- a/components/filesystem/include/filesystem/legacy.h +++ b/components/filesystem/include/filesystem/legacy.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -137,6 +137,7 @@ void write_temp(const std::vector &data, const std::string &filename); * @param components The number of bytes per element * @param row_stride The stride in bytes of a row of pixels */ -void write_image(const uint8_t *data, const std::string &filename, const uint32_t width, const uint32_t height, const uint32_t components, const uint32_t row_stride); +void write_image( + const uint8_t *data, const std::string &filename, const uint32_t width, const uint32_t height, const uint32_t components, const uint32_t row_stride); } // namespace fs } // namespace vkb diff --git a/components/filesystem/src/filesystem.cpp b/components/filesystem/src/filesystem.cpp index ad915fc21a..3929619a08 100644 --- a/components/filesystem/src/filesystem.cpp +++ b/components/filesystem/src/filesystem.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2024, Thomas Atkinson +/* Copyright (c) 2024-2026, Thomas Atkinson * * SPDX-License-Identifier: Apache-2.0 * @@ -35,9 +35,7 @@ void init() void init_with_context(const PlatformContext &context) { - fs = std::make_shared( - context.external_storage_directory(), - context.temp_directory()); + fs = std::make_shared(context.external_storage_directory(), context.temp_directory()); } FileSystemPtr get() diff --git a/components/filesystem/src/legacy.cpp b/components/filesystem/src/legacy.cpp index 3e1c60f8ed..9754c2d220 100644 --- a/components/filesystem/src/legacy.cpp +++ b/components/filesystem/src/legacy.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -33,11 +33,7 @@ namespace fs namespace path { const std::unordered_map relative_paths = { - {Type::Assets, "assets/"}, - {Type::Shaders, "shaders/"}, - {Type::Storage, "output/"}, - {Type::Screenshots, "output/images/"}, - {Type::Logs, "output/logs/"}, + {Type::Assets, "assets/"}, {Type::Shaders, "shaders/"}, {Type::Storage, "output/"}, {Type::Screenshots, "output/images/"}, {Type::Logs, "output/logs/"}, }; const std::string get(const Type type, const std::string &file) @@ -118,7 +114,8 @@ std::vector read_shader_binary_u32(const std::string &filename) { auto buffer = vkb::filesystem::get()->read_file_binary(path::get(path::Type::Shaders) + filename); assert(buffer.size() % sizeof(uint32_t) == 0); - auto spirv = std::vector(reinterpret_cast(buffer.data()), reinterpret_cast(buffer.data()) + buffer.size() / sizeof(uint32_t)); + auto spirv = + std::vector(reinterpret_cast(buffer.data()), reinterpret_cast(buffer.data()) + buffer.size() / sizeof(uint32_t)); return spirv; } @@ -132,7 +129,8 @@ void write_temp(const std::vector &data, const std::string &filename) vkb::filesystem::get()->write_file(path::get(path::Type::Temp) + filename, data); } -void write_image(const uint8_t *data, const std::string &filename, const uint32_t width, const uint32_t height, const uint32_t components, const uint32_t row_stride) +void write_image( + const uint8_t *data, const std::string &filename, const uint32_t width, const uint32_t height, const uint32_t components, const uint32_t row_stride) { stbi_write_png((path::get(path::Type::Screenshots) + filename + ".png").c_str(), width, height, components, data, row_stride); } diff --git a/components/unix/src/context.cpp b/components/unix/src/context.cpp index 03dfe166a8..20dba0023a 100644 --- a/components/unix/src/context.cpp +++ b/components/unix/src/context.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023, Thomas Atkinson +/* Copyright (c) 2023-2026, Thomas Atkinson * * SPDX-License-Identifier: Apache-2.0 * @@ -20,8 +20,7 @@ namespace vkb { -UnixPlatformContext::UnixPlatformContext(int argc, char **argv) : - PlatformContext{} +UnixPlatformContext::UnixPlatformContext(int argc, char **argv) : PlatformContext{} { _arguments.reserve(argc); for (int i = 1; i < argc; ++i) diff --git a/components/windows/src/context.cpp b/components/windows/src/context.cpp index e3318125fc..10a46b3de9 100644 --- a/components/windows/src/context.cpp +++ b/components/windows/src/context.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023, Thomas Atkinson +/* Copyright (c) 2023-2026, Thomas Atkinson * * SPDX-License-Identifier: Apache-2.0 * @@ -80,8 +80,7 @@ inline std::vector get_args() return args; } -WindowsPlatformContext::WindowsPlatformContext(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) : - PlatformContext{} +WindowsPlatformContext::WindowsPlatformContext(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) : PlatformContext{} { _external_storage_directory = ""; _temp_directory = get_temp_path_from_environment(); diff --git a/framework/api_vulkan_sample.cpp b/framework/api_vulkan_sample.cpp index 89bc6d4041..6d81b34cb0 100644 --- a/framework/api_vulkan_sample.cpp +++ b/framework/api_vulkan_sample.cpp @@ -82,9 +82,8 @@ void ApiVulkanSample::prepare_gui() { create_gui(*window, nullptr, 15.0f, true); - std::vector shader_stages = { - load_shader("uioverlay/uioverlay.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), - load_shader("uioverlay/uioverlay.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}; + std::vector shader_stages = {load_shader("uioverlay/uioverlay.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), + load_shader("uioverlay/uioverlay.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}; if (uses_dynamic_rendering()) { @@ -412,10 +411,7 @@ void ApiVulkanSample::create_command_buffers() draw_cmd_buffers.resize(get_render_context().get_render_frames().size()); VkCommandBufferAllocateInfo allocate_info = - vkb::initializers::command_buffer_allocate_info( - cmd_pool, - VK_COMMAND_BUFFER_LEVEL_PRIMARY, - static_cast(draw_cmd_buffers.size())); + vkb::initializers::command_buffer_allocate_info(cmd_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, static_cast(draw_cmd_buffers.size())); VK_CHECK(vkAllocateCommandBuffers(get_device().get_handle(), &allocate_info, draw_cmd_buffers.data())); } @@ -430,7 +426,8 @@ void ApiVulkanSample::recreate_current_command_buffer() auto &cmd = draw_cmd_buffers[current_buffer]; assert(cmd); vkFreeCommandBuffers(get_device().get_handle(), cmd_pool, 1, &cmd); - VkCommandBufferAllocateInfo command_buffer_allocate_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, nullptr, cmd_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1}; + VkCommandBufferAllocateInfo command_buffer_allocate_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, nullptr, cmd_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, + 1}; VK_CHECK(vkAllocateCommandBuffers(get_device().get_handle(), &command_buffer_allocate_info, &cmd)); } @@ -453,7 +450,8 @@ VkPipelineShaderStageCreateInfo ApiVulkanSample::load_shader(const std::string & return shader_stage; } -VkPipelineShaderStageCreateInfo ApiVulkanSample::load_shader(const std::string &sample_folder_name, const std::string &shader_filename, VkShaderStageFlagBits stage) +VkPipelineShaderStageCreateInfo + ApiVulkanSample::load_shader(const std::string &sample_folder_name, const std::string &shader_filename, VkShaderStageFlagBits stage) { std::string full_file_name = sample_folder_name + "/" + get_shader_folder() + "/" + shader_filename; @@ -797,19 +795,23 @@ void ApiVulkanSample::setup_render_pass() // Subpass dependencies for layout transitions std::array dependencies{}; - dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; - dependencies[0].dstSubpass = 0; - dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependencies[0].srcAccessMask = VK_ACCESS_NONE_KHR; - dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; + dependencies[0].dstSubpass = 0; + dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[0].dstStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + dependencies[0].srcAccessMask = VK_ACCESS_NONE_KHR; + dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - dependencies[1].srcSubpass = 0; - dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; - dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + dependencies[1].srcSubpass = 0; + dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; + dependencies[1].srcStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; @@ -882,19 +884,23 @@ void ApiVulkanSample::update_render_pass_flags(uint32_t flags) // Subpass dependencies for layout transitions std::array dependencies{}; - dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; - dependencies[0].dstSubpass = 0; - dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependencies[0].srcAccessMask = VK_ACCESS_NONE_KHR; - dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; + dependencies[0].dstSubpass = 0; + dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[0].dstStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + dependencies[0].srcAccessMask = VK_ACCESS_NONE_KHR; + dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - dependencies[1].srcSubpass = 0; - dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; - dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + dependencies[1].srcSubpass = 0; + dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; + dependencies[1].srcStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; @@ -932,11 +938,7 @@ void ApiVulkanSample::create_swapchain_buffers() color_attachment_view.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; color_attachment_view.pNext = NULL; color_attachment_view.format = get_render_context().get_swapchain().get_format(); - color_attachment_view.components = { - VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, - VK_COMPONENT_SWIZZLE_A}; + color_attachment_view.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A}; color_attachment_view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; color_attachment_view.subresourceRange.baseMipLevel = 0; color_attachment_view.subresourceRange.levelCount = 1; @@ -979,14 +981,12 @@ void ApiVulkanSample::update_swapchain_image_usage_flags(std::setget_vk_image().get_handle(), - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + vkb::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Copy mip levels from staging buffer - vkCmdCopyBufferToImage( - command_buffer, - stage_buffer.get_handle(), - texture.image->get_vk_image().get_handle(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - static_cast(bufferCopyRegions.size()), - bufferCopyRegions.data()); + vkCmdCopyBufferToImage(command_buffer, stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(bufferCopyRegions.size()), bufferCopyRegions.data()); // Change texture image layout to shader read after all mip levels have been copied - vkb::image_layout_transition(command_buffer, - texture.image->get_vk_image().get_handle(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - subresource_range); + vkb::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); @@ -1121,7 +1110,8 @@ Texture ApiVulkanSample::load_texture(const std::string &file, vkb::sg::Image::C // Note that for simplicity, we will always be using max. available anisotropy level for the current device // This may have an impact on performance, esp. on lower-specced devices // In a real-world scenario the level of anisotropy should be a user setting or e.g. lowered for mobile devices by default - sampler_create_info.maxAnisotropy = get_device().get_gpu().get_requested_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f; + sampler_create_info.maxAnisotropy = + get_device().get_gpu().get_requested_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_requested_features().samplerAnisotropy; sampler_create_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK(vkCreateSampler(get_device().get_handle(), &sampler_create_info, nullptr, &texture.sampler)); @@ -1176,27 +1166,16 @@ Texture ApiVulkanSample::load_texture_array(const std::string &file, vkb::sg::Im // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy - vkb::image_layout_transition(command_buffer, - texture.image->get_vk_image().get_handle(), - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + vkb::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Copy mip levels from staging buffer - vkCmdCopyBufferToImage( - command_buffer, - stage_buffer.get_handle(), - texture.image->get_vk_image().get_handle(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - static_cast(buffer_copy_regions.size()), - buffer_copy_regions.data()); + vkCmdCopyBufferToImage(command_buffer, stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(buffer_copy_regions.size()), buffer_copy_regions.data()); // Change texture image layout to shader read after all mip levels have been copied - vkb::image_layout_transition(command_buffer, - texture.image->get_vk_image().get_handle(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - subresource_range); + vkb::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); @@ -1220,7 +1199,8 @@ Texture ApiVulkanSample::load_texture_array(const std::string &file, vkb::sg::Im // Max level-of-detail should match mip level count sampler_create_info.maxLod = static_cast(mipmaps.size()); // Only enable anisotropic filtering if enabled on the devicec - sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy : 1.0f; + sampler_create_info.maxAnisotropy = + get_device().get_gpu().get_features().samplerAnisotropy ? get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK(vkCreateSampler(get_device().get_handle(), &sampler_create_info, nullptr, &texture.sampler)); @@ -1275,27 +1255,16 @@ Texture ApiVulkanSample::load_texture_cubemap(const std::string &file, vkb::sg:: // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy - vkb::image_layout_transition(command_buffer, - texture.image->get_vk_image().get_handle(), - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + vkb::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Copy mip levels from staging buffer - vkCmdCopyBufferToImage( - command_buffer, - stage_buffer.get_handle(), - texture.image->get_vk_image().get_handle(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - static_cast(buffer_copy_regions.size()), - buffer_copy_regions.data()); + vkCmdCopyBufferToImage(command_buffer, stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(buffer_copy_regions.size()), buffer_copy_regions.data()); // Change texture image layout to shader read after all mip levels have been copied - vkb::image_layout_transition(command_buffer, - texture.image->get_vk_image().get_handle(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - subresource_range); + vkb::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); @@ -1319,7 +1288,8 @@ Texture ApiVulkanSample::load_texture_cubemap(const std::string &file, vkb::sg:: // Max level-of-detail should match mip level count sampler_create_info.maxLod = static_cast(mipmaps.size()); // Only enable anisotropic filtering if enabled on the devicec - sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy : 1.0f; + sampler_create_info.maxAnisotropy = + get_device().get_gpu().get_features().samplerAnisotropy ? get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK(vkCreateSampler(get_device().get_handle(), &sampler_create_info, nullptr, &texture.sampler)); @@ -1327,7 +1297,8 @@ Texture ApiVulkanSample::load_texture_cubemap(const std::string &file, vkb::sg:: return texture; } -std::unique_ptr ApiVulkanSample::load_model(const std::string &file, uint32_t index, bool storage_buffer, VkBufferUsageFlags additional_buffer_usage_flags) +std::unique_ptr + ApiVulkanSample::load_model(const std::string &file, uint32_t index, bool storage_buffer, VkBufferUsageFlags additional_buffer_usage_flags) { vkb::GLTFLoader loader{get_device()}; diff --git a/framework/api_vulkan_sample.h b/framework/api_vulkan_sample.h index 45954d1d06..b7444e56d0 100644 --- a/framework/api_vulkan_sample.h +++ b/framework/api_vulkan_sample.h @@ -243,7 +243,8 @@ class ApiVulkanSample : public vkb::VulkanSampleC * @param storage_buffer Set true to store model in SSBO * @param additional_buffer_usage_flags Additional buffer usage flags to be applied to vertex and index buffers */ - std::unique_ptr load_model(const std::string &file, uint32_t index = 0, bool storage_buffer = false, VkBufferUsageFlags additional_buffer_usage_flags = 0); + std::unique_ptr + load_model(const std::string &file, uint32_t index = 0, bool storage_buffer = false, VkBufferUsageFlags additional_buffer_usage_flags = 0); /** * @brief Records the necessary drawing commands to a command buffer diff --git a/framework/buffer_pool.h b/framework/buffer_pool.h index 89b3e0cd71..2c443822cf 100644 --- a/framework/buffer_pool.h +++ b/framework/buffer_pool.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors - * Copyright (c) 2024-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2019-2026, Arm Limited and Contributors + * Copyright (c) 2024-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -62,16 +62,12 @@ using BufferAllocationCpp = BufferAllocation; template <> inline BufferAllocation::BufferAllocation(vkb::core::BufferCpp &buffer, vk::DeviceSize size, vk::DeviceSize offset) : - buffer(&buffer), - offset(offset), - size(size) + buffer(&buffer), offset(offset), size(size) {} template <> inline BufferAllocation::BufferAllocation(vkb::core::BufferC &buffer, VkDeviceSize size, VkDeviceSize offset) : - buffer(reinterpret_cast(&buffer)), - offset(static_cast(offset)), - size(static_cast(size)) + buffer(reinterpret_cast(&buffer)), offset(static_cast(offset)), size(static_cast(size)) {} template @@ -306,19 +302,22 @@ class BufferPool using DeviceSizeType = typename std::conditional::type; public: - BufferPool( - vkb::core::Device &device, DeviceSizeType block_size, BufferUsageFlagsType usage, VmaMemoryUsage memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU); + BufferPool(vkb::core::Device &device, + DeviceSizeType block_size, + BufferUsageFlagsType usage, + VmaMemoryUsage memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU); BufferBlock &request_buffer_block(DeviceSizeType minimum_size, bool minimal = false); void reset(); private: - vkb::core::DeviceCpp &device; - std::vector> buffer_blocks; /// List of blocks requested (need to be pointers in order to keep their address constant on vector resizing) - vk::DeviceSize block_size = 0; /// Minimum size of the blocks - vk::BufferUsageFlags usage; - VmaMemoryUsage memory_usage{}; + vkb::core::DeviceCpp &device; + std::vector> + buffer_blocks; /// List of blocks requested (need to be pointers in order to keep their address constant on vector resizing) + vk::DeviceSize block_size = 0; /// Minimum size of the blocks + vk::BufferUsageFlags usage; + VmaMemoryUsage memory_usage{}; }; using BufferPoolC = BufferPool; @@ -330,17 +329,17 @@ BufferPool::BufferPool(vkb::core::Device &device, BufferUsageFlagsType usage, VmaMemoryUsage memory_usage) : device{reinterpret_cast(device)}, block_size{block_size}, usage{usage}, memory_usage{memory_usage} -{ -} +{} template BufferBlock &BufferPool::request_buffer_block(DeviceSizeType minimum_size, bool minimal) { // Find a block in the range of the blocks which can fit the minimum size auto it = minimal ? std::ranges::find_if(buffer_blocks, - [&minimum_size](auto const &buffer_block) { return (buffer_block->get_size() == minimum_size) && buffer_block->can_allocate(minimum_size); }) : - std::ranges::find_if(buffer_blocks, - [&minimum_size](auto const &buffer_block) { return buffer_block->can_allocate(minimum_size); }); + [&minimum_size](auto const &buffer_block) { + return (buffer_block->get_size() == minimum_size) && buffer_block->can_allocate(minimum_size); + }) : + std::ranges::find_if(buffer_blocks, [&minimum_size](auto const &buffer_block) { return buffer_block->can_allocate(minimum_size); }); if (it == buffer_blocks.end()) { diff --git a/framework/common/error.cpp b/framework/common/error.cpp index 1dfbb44337..f6b587db5b 100644 --- a/framework/common/error.cpp +++ b/framework/common/error.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2020, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,9 +21,7 @@ namespace vkb { -VulkanException::VulkanException(const VkResult result, const std::string &msg) : - result{result}, - std::runtime_error{msg} +VulkanException::VulkanException(const VkResult result, const std::string &msg) : result{result}, std::runtime_error{msg} { error_message = std::string(std::runtime_error::what()) + std::string{" : "} + to_string(result); } diff --git a/framework/common/helpers.h b/framework/common/helpers.h index 80705c68d2..e02a9da03a 100644 --- a/framework/common/helpers.h +++ b/framework/common/helpers.h @@ -213,8 +213,7 @@ uint32_t to_u32(T value) template inline std::vector to_bytes(const T &value) { - return std::vector{reinterpret_cast(&value), - reinterpret_cast(&value) + sizeof(T)}; + return std::vector{reinterpret_cast(&value), reinterpret_cast(&value) + sizeof(T)}; } } // namespace vkb diff --git a/framework/common/hpp_error.h b/framework/common/hpp_error.h index e0edc21516..c848885618 100644 --- a/framework/common/hpp_error.h +++ b/framework/common/hpp_error.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2024, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -33,8 +33,7 @@ namespace common class HPPVulkanException : public vkb::VulkanException { public: - HPPVulkanException(vk::Result result, std::string const &msg = "Vulkan error") : - vkb::VulkanException(static_cast(result), msg) + HPPVulkanException(vk::Result result, std::string const &msg = "Vulkan error") : vkb::VulkanException(static_cast(result), msg) {} }; } // namespace common diff --git a/framework/common/hpp_vk_common.h b/framework/common/hpp_vk_common.h index 23db9ad819..748054578a 100644 --- a/framework/common/hpp_vk_common.h +++ b/framework/common/hpp_vk_common.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -64,8 +64,8 @@ inline int32_t get_bits_per_pixel(vk::Format format) inline vk::Format get_suitable_depth_format(vk::PhysicalDevice physical_device, bool depth_only = false, - const std::vector &depth_format_priority_list = { - vk::Format::eD32Sfloat, vk::Format::eD24UnormS8Uint, vk::Format::eD16Unorm}) + const std::vector &depth_format_priority_list = {vk::Format::eD32Sfloat, vk::Format::eD24UnormS8Uint, + vk::Format::eD16Unorm}) { return static_cast( vkb::get_suitable_depth_format(physical_device, depth_only, reinterpret_cast const &>(depth_format_priority_list))); @@ -86,8 +86,7 @@ inline bool is_depth_only_format(vk::Format format) inline bool is_depth_stencil_format(vk::Format format) { assert(vkb::is_depth_stencil_format(static_cast(format)) == - ((vk::componentCount(format) == 2) && (std::string(vk::componentName(format, 0)) == "D") && - (std::string(vk::componentName(format, 1)) == "S"))); + ((vk::componentCount(format) == 2) && (std::string(vk::componentName(format, 0)) == "D") && (std::string(vk::componentName(format, 1)) == "S"))); return vkb::is_depth_stencil_format(static_cast(format)); } @@ -107,28 +106,17 @@ inline vk::ShaderModule load_shader(const std::string &filename, vk::Device devi return static_cast(vkb::load_shader(filename, device, static_cast(stage))); } -inline void image_layout_transition(vk::CommandBuffer command_buffer, - vk::Image image, - vk::ImageLayout old_layout, - vk::ImageLayout new_layout) +inline void image_layout_transition(vk::CommandBuffer command_buffer, vk::Image image, vk::ImageLayout old_layout, vk::ImageLayout new_layout) { - vkb::image_layout_transition(static_cast(command_buffer), - static_cast(image), - static_cast(old_layout), + vkb::image_layout_transition(static_cast(command_buffer), static_cast(image), static_cast(old_layout), static_cast(new_layout)); } -inline void image_layout_transition(vk::CommandBuffer command_buffer, - vk::Image image, - vk::ImageLayout old_layout, - vk::ImageLayout new_layout, - vk::ImageSubresourceRange subresource_range) +inline void image_layout_transition( + vk::CommandBuffer command_buffer, vk::Image image, vk::ImageLayout old_layout, vk::ImageLayout new_layout, vk::ImageSubresourceRange subresource_range) { - vkb::image_layout_transition(static_cast(command_buffer), - static_cast(image), - static_cast(old_layout), - static_cast(new_layout), - static_cast(subresource_range)); + vkb::image_layout_transition(static_cast(command_buffer), static_cast(image), static_cast(old_layout), + static_cast(new_layout), static_cast(subresource_range)); } inline void image_layout_transition(vk::CommandBuffer command_buffer, @@ -141,14 +129,9 @@ inline void image_layout_transition(vk::CommandBuffer command_buf vk::ImageLayout new_layout, vk::ImageSubresourceRange const &subresource_range) { - vkb::image_layout_transition(static_cast(command_buffer), - static_cast(image), - static_cast(src_stage_mask), - static_cast(dst_stage_mask), - static_cast(src_access_mask), - static_cast(dst_access_mask), - static_cast(old_layout), - static_cast(new_layout), + vkb::image_layout_transition(static_cast(command_buffer), static_cast(image), static_cast(src_stage_mask), + static_cast(dst_stage_mask), static_cast(src_access_mask), + static_cast(dst_access_mask), static_cast(old_layout), static_cast(new_layout), static_cast(subresource_range)); } @@ -174,17 +157,15 @@ inline void make_filters_valid(vk::PhysicalDevice physical_device, vk::Format fo inline vk::SurfaceFormatKHR select_surface_format(vk::PhysicalDevice gpu, vk::SurfaceKHR surface, - std::vector const &preferred_formats = { - vk::Format::eR8G8B8A8Srgb, vk::Format::eB8G8R8A8Srgb, vk::Format::eA8B8G8R8SrgbPack32}) + std::vector const &preferred_formats = {vk::Format::eR8G8B8A8Srgb, vk::Format::eB8G8R8A8Srgb, + vk::Format::eA8B8G8R8SrgbPack32}) { std::vector supported_surface_formats = gpu.getSurfaceFormatsKHR(surface); assert(!supported_surface_formats.empty()); - auto it = std::ranges::find_if(supported_surface_formats, - [&preferred_formats](vk::SurfaceFormatKHR surface_format) { - return std::ranges::any_of(preferred_formats, - [&surface_format](vk::Format format) { return format == surface_format.format; }); - }); + auto it = std::ranges::find_if(supported_surface_formats, [&preferred_formats](vk::SurfaceFormatKHR surface_format) { + return std::ranges::any_of(preferred_formats, [&surface_format](vk::Format format) { return format == surface_format.format; }); + }); // We use the first supported format as a fallback in case none of the preferred formats is available return it != supported_surface_formats.end() ? *it : supported_surface_formats[0]; @@ -205,8 +186,7 @@ inline vk::Format choose_blendable_format(vk::PhysicalDevice gpu, const std::vec inline vk::ImageCompressionPropertiesEXT query_applied_compression(vk::Device device, vk::Image image) { - vk::ImageSubresource2EXT image_subresource{ - .imageSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = 0, .arrayLayer = 0}}; + vk::ImageSubresource2EXT image_subresource{.imageSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = 0, .arrayLayer = 0}}; auto imageSubresourceLayout = device.getImageSubresourceLayout2EXT(image, image_subresource); @@ -223,9 +203,8 @@ inline vk::CommandBuffer inline vk::DescriptorSet allocate_descriptor_set(vk::Device device, vk::DescriptorPool descriptor_pool, vk::DescriptorSetLayout descriptor_set_layout) { - vk::DescriptorSetAllocateInfo descriptor_set_allocate_info{.descriptorPool = descriptor_pool, - .descriptorSetCount = 1, - .pSetLayouts = &descriptor_set_layout}; + vk::DescriptorSetAllocateInfo descriptor_set_allocate_info{ + .descriptorPool = descriptor_pool, .descriptorSetCount = 1, .pSetLayouts = &descriptor_set_layout}; return device.allocateDescriptorSets(descriptor_set_allocate_info).front(); } @@ -317,7 +296,8 @@ inline vk::ImageView create_image_view(vk::Device device, return device.createImageView(image_view_create_info); } -inline vk::QueryPool create_query_pool(vk::Device device, vk::QueryType query_type, uint32_t query_count, vk::QueryPipelineStatisticFlags pipeline_statistics = {}) +inline vk::QueryPool + create_query_pool(vk::Device device, vk::QueryType query_type, uint32_t query_count, vk::QueryPipelineStatisticFlags pipeline_statistics = {}) { vk::QueryPoolCreateInfo query_pool_create_info{.queryType = query_type, .queryCount = query_count, .pipelineStatistics = pipeline_statistics}; return device.createQueryPool(query_pool_create_info); @@ -358,13 +338,8 @@ inline vk::Sampler create_sampler(vk::PhysicalDevice gpu, bool has_linear_filter = !!(fmt_props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImageFilterLinear); - return create_sampler(device, - has_linear_filter ? filter : vk::Filter::eNearest, - has_linear_filter ? filter : vk::Filter::eNearest, - has_linear_filter ? vk::SamplerMipmapMode::eLinear : vk::SamplerMipmapMode::eNearest, - sampler_address_mode, - max_anisotropy, - max_LOD); + return create_sampler(device, has_linear_filter ? filter : vk::Filter::eNearest, has_linear_filter ? filter : vk::Filter::eNearest, + has_linear_filter ? vk::SamplerMipmapMode::eLinear : vk::SamplerMipmapMode::eNearest, sampler_address_mode, max_anisotropy, max_LOD); } inline vk::ImageAspectFlags get_image_aspect_flags(vk::ImageUsageFlagBits usage, vk::Format format) @@ -425,8 +400,9 @@ inline uint32_t get_queue_family_index(std::vector co // Try to find a queue family index that supports compute but not graphics if (queue_flag & vk::QueueFlagBits::eCompute) { - auto propertyIt = std::ranges::find_if(queue_family_properties, - [queue_flag](const vk::QueueFamilyProperties &property) { return (property.queueFlags & queue_flag) && !(property.queueFlags & vk::QueueFlagBits::eGraphics); }); + auto propertyIt = std::ranges::find_if(queue_family_properties, [queue_flag](const vk::QueueFamilyProperties &property) { + return (property.queueFlags & queue_flag) && !(property.queueFlags & vk::QueueFlagBits::eGraphics); + }); if (propertyIt != queue_family_properties.end()) { return static_cast(std::distance(queue_family_properties.begin(), propertyIt)); @@ -437,11 +413,10 @@ inline uint32_t get_queue_family_index(std::vector co // Try to find a queue family index that supports transfer but not graphics and compute if (queue_flag & vk::QueueFlagBits::eTransfer) { - auto propertyIt = std::ranges::find_if(queue_family_properties, - [queue_flag](const vk::QueueFamilyProperties &property) { - return (property.queueFlags & queue_flag) && !(property.queueFlags & vk::QueueFlagBits::eGraphics) && - !(property.queueFlags & vk::QueueFlagBits::eCompute); - }); + auto propertyIt = std::ranges::find_if(queue_family_properties, [queue_flag](const vk::QueueFamilyProperties &property) { + return (property.queueFlags & queue_flag) && !(property.queueFlags & vk::QueueFlagBits::eGraphics) && + !(property.queueFlags & vk::QueueFlagBits::eCompute); + }); if (propertyIt != queue_family_properties.end()) { return static_cast(std::distance(queue_family_properties.begin(), propertyIt)); diff --git a/framework/common/resource_caching.h b/framework/common/resource_caching.h index 67b6c9e6bc..c968760224 100644 --- a/framework/common/resource_caching.h +++ b/framework/common/resource_caching.h @@ -210,10 +210,8 @@ struct hash { std::size_t result = 0; - if (shader_resource.type == vkb::ShaderResourceType::Input || - shader_resource.type == vkb::ShaderResourceType::Output || - shader_resource.type == vkb::ShaderResourceType::PushConstant || - shader_resource.type == vkb::ShaderResourceType::SpecializationConstant) + if (shader_resource.type == vkb::ShaderResourceType::Input || shader_resource.type == vkb::ShaderResourceType::Output || + shader_resource.type == vkb::ShaderResourceType::PushConstant || shader_resource.type == vkb::ShaderResourceType::SpecializationConstant) { return result; } @@ -548,21 +546,16 @@ inline void hash_param(size_t &seed, const T &value) template <> inline void hash_param(size_t & /*seed*/, const VkPipelineCache & /*value*/) -{ -} +{} template <> -inline void hash_param>( - size_t &seed, - const std::vector &value) +inline void hash_param>(size_t &seed, const std::vector &value) { hash_combine(seed, std::string{value.begin(), value.end()}); } template <> -inline void hash_param>( - size_t &seed, - const std::vector &value) +inline void hash_param>(size_t &seed, const std::vector &value) { for (auto &attachment : value) { @@ -571,9 +564,7 @@ inline void hash_param>( } template <> -inline void hash_param>( - size_t &seed, - const std::vector &value) +inline void hash_param>(size_t &seed, const std::vector &value) { for (auto &load_store_info : value) { @@ -582,9 +573,7 @@ inline void hash_param>( } template <> -inline void hash_param>( - size_t &seed, - const std::vector &value) +inline void hash_param>(size_t &seed, const std::vector &value) { for (auto &subpass_info : value) { @@ -593,9 +582,7 @@ inline void hash_param>( } template <> -inline void hash_param>( - size_t &seed, - const std::vector &value) +inline void hash_param>(size_t &seed, const std::vector &value) { for (auto &shader_module : value) { @@ -604,9 +591,7 @@ inline void hash_param>( } template <> -inline void hash_param>( - size_t &seed, - const std::vector &value) +inline void hash_param>(size_t &seed, const std::vector &value) { for (auto &resource : value) { @@ -615,9 +600,9 @@ inline void hash_param>( } template <> -inline void hash_param>>( - size_t &seed, - const std::map> &value) +inline void + hash_param>>(size_t &seed, + const std::map> &value) { for (auto &binding_set : value) { @@ -632,9 +617,9 @@ inline void hash_param -inline void hash_param>>( - size_t &seed, - const std::map> &value) +inline void + hash_param>>(size_t &seed, + const std::map> &value) { for (auto &binding_set : value) { @@ -665,8 +650,7 @@ struct RecordHelper } void index(ResourceRecord & /*recorder*/, size_t /*index*/, T & /*resource*/) - { - } + {} }; template diff --git a/framework/common/strings.cpp b/framework/common/strings.cpp index f7a0d45f64..dfbd583a97 100644 --- a/framework/common/strings.cpp +++ b/framework/common/strings.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2024, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -1510,127 +1510,121 @@ const std::string to_string(ShaderResourceType type) const std::string buffer_usage_to_string(VkBufferUsageFlags flags) { - return to_string(flags, - {{VK_BUFFER_USAGE_TRANSFER_SRC_BIT, "VK_BUFFER_USAGE_TRANSFER_SRC_BIT"}, - {VK_BUFFER_USAGE_TRANSFER_DST_BIT, "VK_BUFFER_USAGE_TRANSFER_DST_BIT"}, - {VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, "VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT"}, - {VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, "VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT"}, - {VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, "VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT"}, - {VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, "VK_BUFFER_USAGE_STORAGE_BUFFER_BIT"}, - {VK_BUFFER_USAGE_INDEX_BUFFER_BIT, "VK_BUFFER_USAGE_INDEX_BUFFER_BIT"}, - {VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, "VK_BUFFER_USAGE_VERTEX_BUFFER_BIT"}, - {VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, "VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT"}, - {VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, "VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT"}, - {VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT, "VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT"}, - {VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT, "VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT"}, - {VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, "VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT"}, - {VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, "VK_BUFFER_USAGE_RAY_TRACING_BIT_NV"}, - {VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT, "VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT"}, - {VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR, "VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR"}}); + return to_string( + flags, {{VK_BUFFER_USAGE_TRANSFER_SRC_BIT, "VK_BUFFER_USAGE_TRANSFER_SRC_BIT"}, + {VK_BUFFER_USAGE_TRANSFER_DST_BIT, "VK_BUFFER_USAGE_TRANSFER_DST_BIT"}, + {VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, "VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT"}, + {VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, "VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT"}, + {VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, "VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT"}, + {VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, "VK_BUFFER_USAGE_STORAGE_BUFFER_BIT"}, + {VK_BUFFER_USAGE_INDEX_BUFFER_BIT, "VK_BUFFER_USAGE_INDEX_BUFFER_BIT"}, + {VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, "VK_BUFFER_USAGE_VERTEX_BUFFER_BIT"}, + {VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, "VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT"}, + {VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, "VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT"}, + {VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT, "VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT"}, + {VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT, "VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT"}, + {VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, "VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT"}, + {VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, "VK_BUFFER_USAGE_RAY_TRACING_BIT_NV"}, + {VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT, "VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT"}, + {VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR, "VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR"}}); } const std::string shader_stage_to_string(VkShaderStageFlags flags) { - return to_string(flags, - {{VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, "TESSELLATION_CONTROL"}, - {VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, "TESSELLATION_EVALUATION"}, - {VK_SHADER_STAGE_GEOMETRY_BIT, "GEOMETRY"}, - {VK_SHADER_STAGE_VERTEX_BIT, "VERTEX"}, - {VK_SHADER_STAGE_FRAGMENT_BIT, "FRAGMENT"}, - {VK_SHADER_STAGE_COMPUTE_BIT, "COMPUTE"}, - {VK_SHADER_STAGE_ALL_GRAPHICS, "ALL GRAPHICS"}}); + return to_string(flags, {{VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, "TESSELLATION_CONTROL"}, + {VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, "TESSELLATION_EVALUATION"}, + {VK_SHADER_STAGE_GEOMETRY_BIT, "GEOMETRY"}, + {VK_SHADER_STAGE_VERTEX_BIT, "VERTEX"}, + {VK_SHADER_STAGE_FRAGMENT_BIT, "FRAGMENT"}, + {VK_SHADER_STAGE_COMPUTE_BIT, "COMPUTE"}, + {VK_SHADER_STAGE_ALL_GRAPHICS, "ALL GRAPHICS"}}); } const std::string image_usage_to_string(VkImageUsageFlags flags) { - return to_string(flags, - {{VK_IMAGE_USAGE_TRANSFER_SRC_BIT, "VK_IMAGE_USAGE_TRANSFER_SRC_BIT"}, - {VK_IMAGE_USAGE_TRANSFER_DST_BIT, "VK_IMAGE_USAGE_TRANSFER_DST_BIT"}, - {VK_IMAGE_USAGE_SAMPLED_BIT, "VK_IMAGE_USAGE_SAMPLED_BIT"}, - {VK_IMAGE_USAGE_STORAGE_BIT, "VK_IMAGE_USAGE_STORAGE_BIT"}, - {VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, "VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT"}, - {VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, "VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT"}, - {VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT, "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT"}, - {VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, "VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT"}, - {VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR, "VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR"}, - {VK_IMAGE_USAGE_VIDEO_DECODE_SRC_BIT_KHR, "VK_IMAGE_USAGE_VIDEO_DECODE_SRC_BIT_KHR"}, - {VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR, "VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR"}, - {VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT, "VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT"}, - {VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR, "VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR"}, - {VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT, "VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT"}, - {VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT, "VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT"}, - {VK_IMAGE_USAGE_INVOCATION_MASK_BIT_HUAWEI, "VK_IMAGE_USAGE_INVOCATION_MASK_BIT_HUAWEI"}, - {VK_IMAGE_USAGE_SAMPLE_WEIGHT_BIT_QCOM, "VK_IMAGE_USAGE_SAMPLE_WEIGHT_BIT_QCOM"}, - {VK_IMAGE_USAGE_SAMPLE_BLOCK_MATCH_BIT_QCOM, "VK_IMAGE_USAGE_SAMPLE_BLOCK_MATCH_BIT_QCOM"}}); + return to_string( + flags, {{VK_IMAGE_USAGE_TRANSFER_SRC_BIT, "VK_IMAGE_USAGE_TRANSFER_SRC_BIT"}, + {VK_IMAGE_USAGE_TRANSFER_DST_BIT, "VK_IMAGE_USAGE_TRANSFER_DST_BIT"}, + {VK_IMAGE_USAGE_SAMPLED_BIT, "VK_IMAGE_USAGE_SAMPLED_BIT"}, + {VK_IMAGE_USAGE_STORAGE_BIT, "VK_IMAGE_USAGE_STORAGE_BIT"}, + {VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, "VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT"}, + {VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, "VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT"}, + {VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT, "VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT"}, + {VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, "VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT"}, + {VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR, "VK_IMAGE_USAGE_VIDEO_DECODE_DST_BIT_KHR"}, + {VK_IMAGE_USAGE_VIDEO_DECODE_SRC_BIT_KHR, "VK_IMAGE_USAGE_VIDEO_DECODE_SRC_BIT_KHR"}, + {VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR, "VK_IMAGE_USAGE_VIDEO_DECODE_DPB_BIT_KHR"}, + {VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT, "VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT"}, + {VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR, "VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR"}, + {VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT, "VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT"}, + {VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT, "VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT"}, + {VK_IMAGE_USAGE_INVOCATION_MASK_BIT_HUAWEI, "VK_IMAGE_USAGE_INVOCATION_MASK_BIT_HUAWEI"}, + {VK_IMAGE_USAGE_SAMPLE_WEIGHT_BIT_QCOM, "VK_IMAGE_USAGE_SAMPLE_WEIGHT_BIT_QCOM"}, + {VK_IMAGE_USAGE_SAMPLE_BLOCK_MATCH_BIT_QCOM, "VK_IMAGE_USAGE_SAMPLE_BLOCK_MATCH_BIT_QCOM"}}); } const std::string image_aspect_to_string(VkImageAspectFlags flags) { - return to_string(flags, - {{VK_IMAGE_ASPECT_COLOR_BIT, "VK_IMAGE_ASPECT_COLOR_BIT"}, - {VK_IMAGE_ASPECT_DEPTH_BIT, "VK_IMAGE_ASPECT_DEPTH_BIT"}, - {VK_IMAGE_ASPECT_STENCIL_BIT, "VK_IMAGE_ASPECT_STENCIL_BIT"}, - {VK_IMAGE_ASPECT_METADATA_BIT, "VK_IMAGE_ASPECT_METADATA_BIT"}, - {VK_IMAGE_ASPECT_PLANE_0_BIT, "VK_IMAGE_ASPECT_PLANE_0_BIT"}, - {VK_IMAGE_ASPECT_PLANE_1_BIT, "VK_IMAGE_ASPECT_PLANE_1_BIT"}, - {VK_IMAGE_ASPECT_PLANE_2_BIT, "VK_IMAGE_ASPECT_PLANE_2_BIT"}}); + return to_string(flags, {{VK_IMAGE_ASPECT_COLOR_BIT, "VK_IMAGE_ASPECT_COLOR_BIT"}, + {VK_IMAGE_ASPECT_DEPTH_BIT, "VK_IMAGE_ASPECT_DEPTH_BIT"}, + {VK_IMAGE_ASPECT_STENCIL_BIT, "VK_IMAGE_ASPECT_STENCIL_BIT"}, + {VK_IMAGE_ASPECT_METADATA_BIT, "VK_IMAGE_ASPECT_METADATA_BIT"}, + {VK_IMAGE_ASPECT_PLANE_0_BIT, "VK_IMAGE_ASPECT_PLANE_0_BIT"}, + {VK_IMAGE_ASPECT_PLANE_1_BIT, "VK_IMAGE_ASPECT_PLANE_1_BIT"}, + {VK_IMAGE_ASPECT_PLANE_2_BIT, "VK_IMAGE_ASPECT_PLANE_2_BIT"}}); } const std::string cull_mode_to_string(VkCullModeFlags flags) { - return to_string(flags, - {{VK_CULL_MODE_NONE, "VK_CULL_MODE_NONE"}, - {VK_CULL_MODE_FRONT_BIT, "VK_CULL_MODE_FRONT_BIT"}, - {VK_CULL_MODE_BACK_BIT, "VK_CULL_MODE_BACK_BIT"}, - {VK_CULL_MODE_FRONT_AND_BACK, "VK_CULL_MODE_FRONT_AND_BACK"}}); + return to_string(flags, {{VK_CULL_MODE_NONE, "VK_CULL_MODE_NONE"}, + {VK_CULL_MODE_FRONT_BIT, "VK_CULL_MODE_FRONT_BIT"}, + {VK_CULL_MODE_BACK_BIT, "VK_CULL_MODE_BACK_BIT"}, + {VK_CULL_MODE_FRONT_AND_BACK, "VK_CULL_MODE_FRONT_AND_BACK"}}); } const std::string color_component_to_string(VkColorComponentFlags flags) { - return to_string(flags, - {{VK_COLOR_COMPONENT_R_BIT, "R"}, - {VK_COLOR_COMPONENT_G_BIT, "G"}, - {VK_COLOR_COMPONENT_B_BIT, "B"}, - {VK_COLOR_COMPONENT_A_BIT, "A"}}); + return to_string( + flags, {{VK_COLOR_COMPONENT_R_BIT, "R"}, {VK_COLOR_COMPONENT_G_BIT, "G"}, {VK_COLOR_COMPONENT_B_BIT, "B"}, {VK_COLOR_COMPONENT_A_BIT, "A"}}); } const std::string image_compression_flags_to_string(VkImageCompressionFlagsEXT flags) { - return 0 == flags ? "VK_IMAGE_COMPRESSION_DEFAULT_EXT" : - to_string(flags, - {{VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_EXPLICIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_EXPLICIT_EXT"}, - {VK_IMAGE_COMPRESSION_DISABLED_EXT, "VK_IMAGE_COMPRESSION_DISABLED_EXT"}}); + return 0 == flags ? + "VK_IMAGE_COMPRESSION_DEFAULT_EXT" : + to_string(flags, {{VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_DEFAULT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_EXPLICIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_EXPLICIT_EXT"}, + {VK_IMAGE_COMPRESSION_DISABLED_EXT, "VK_IMAGE_COMPRESSION_DISABLED_EXT"}}); } const std::string image_compression_fixed_rate_flags_to_string(VkImageCompressionFixedRateFlagsEXT flags) { return 0 == flags ? "VK_IMAGE_COMPRESSION_FIXED_RATE_NONE_EXT" : - to_string(flags, - {{VK_IMAGE_COMPRESSION_FIXED_RATE_1BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_1BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_2BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_2BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_3BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_3BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_4BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_4BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_5BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_5BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_6BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_6BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_7BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_7BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_8BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_8BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_9BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_9BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_10BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_10BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_11BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_11BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_12BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_12BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_13BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_13BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_14BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_14BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_15BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_15BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_16BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_16BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_17BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_17BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_18BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_18BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_19BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_19BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_20BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_20BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_21BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_21BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_22BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_22BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_23BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_23BPC_BIT_EXT"}, - {VK_IMAGE_COMPRESSION_FIXED_RATE_24BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_24BPC_BIT_EXT"}}); + to_string( + flags, {{VK_IMAGE_COMPRESSION_FIXED_RATE_1BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_1BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_2BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_2BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_3BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_3BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_4BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_4BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_5BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_5BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_6BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_6BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_7BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_7BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_8BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_8BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_9BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_9BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_10BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_10BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_11BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_11BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_12BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_12BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_13BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_13BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_14BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_14BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_15BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_15BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_16BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_16BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_17BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_17BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_18BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_18BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_19BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_19BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_20BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_20BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_21BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_21BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_22BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_22BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_23BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_23BPC_BIT_EXT"}, + {VK_IMAGE_COMPRESSION_FIXED_RATE_24BPC_BIT_EXT, "VK_IMAGE_COMPRESSION_FIXED_RATE_24BPC_BIT_EXT"}}); } std::vector split(const std::string &input, char delim) diff --git a/framework/common/tags.h b/framework/common/tags.h index 23fe0bc9c1..4c48f44ee0 100644 --- a/framework/common/tags.h +++ b/framework/common/tags.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -26,12 +26,12 @@ typedef void (*TagID)(); /** * @brief Tag acts as a unique identifier to categories objects - * + * * Tags are uniquely defined using different type names. The easiest way of creating a new tag is to use an empty struct * struct TagName{}; * struct DifferentTag{}; * Tag::ID == Tag::member != Tag:ID - * + * * @tparam TAGS A set of tags */ template diff --git a/framework/common/utils.cpp b/framework/common/utils.cpp index 631f4b0327..360dc178d2 100644 --- a/framework/common/utils.cpp +++ b/framework/common/utils.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -44,10 +44,8 @@ std::string get_extension(const std::string &uri) void screenshot(vkb::rendering::RenderContextC &render_context, const std::string &filename) { - assert(render_context.get_format() == VK_FORMAT_R8G8B8A8_UNORM || - render_context.get_format() == VK_FORMAT_B8G8R8A8_UNORM || - render_context.get_format() == VK_FORMAT_R8G8B8A8_SRGB || - render_context.get_format() == VK_FORMAT_B8G8R8A8_SRGB); + assert(render_context.get_format() == VK_FORMAT_R8G8B8A8_UNORM || render_context.get_format() == VK_FORMAT_B8G8R8A8_UNORM || + render_context.get_format() == VK_FORMAT_R8G8B8A8_SRGB || render_context.get_format() == VK_FORMAT_B8G8R8A8_SRGB); // We want the last completed frame since we don't want to be reading from an incomplete framebuffer auto &frame = render_context.get_last_rendered_frame(); @@ -58,10 +56,7 @@ void screenshot(vkb::rendering::RenderContextC &render_context, const std::strin auto height = render_context.get_surface_extent().height; auto dst_size = width * height * 4; - vkb::core::BufferC dst_buffer{render_context.get_device(), - dst_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_TO_CPU, + vkb::core::BufferC dst_buffer{render_context.get_device(), dst_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_TO_CPU, VMA_ALLOCATION_CREATE_MAPPED_BIT}; const auto &queue = render_context.get_device().get_queue_by_flags(VK_QUEUE_GRAPHICS_BIT, 0); @@ -174,12 +169,7 @@ void screenshot(vkb::rendering::RenderContextC &render_context, const std::strin } } - vkb::fs::write_image(raw_data, - filename, - width, - height, - 4, - width * 4); + vkb::fs::write_image(raw_data, filename, width, height, 4, width * 4); dst_buffer.unmap(); } // namespace vkb @@ -259,7 +249,8 @@ sg::Light &add_directional_light(sg::Scene &scene, const glm::quat &rotation, co return add_light(scene, sg::LightType::Directional, {}, rotation, props, parent_node); } -sg::Light &add_spot_light(sg::Scene &scene, const glm::vec3 &position, const glm::quat &rotation, const sg::LightProperties &props, vkb::scene_graph::NodeC *parent_node) +sg::Light &add_spot_light( + sg::Scene &scene, const glm::vec3 &position, const glm::quat &rotation, const sg::LightProperties &props, vkb::scene_graph::NodeC *parent_node) { return add_light(scene, sg::LightType::Spot, position, rotation, props, parent_node); } diff --git a/framework/common/utils.h b/framework/common/utils.h index a5b68bacad..2fd7f59621 100644 --- a/framework/common/utils.h +++ b/framework/common/utils.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -81,8 +81,7 @@ sg::Light &add_light(sg::Scene &scene, * @param parent_node The parent node for the line, defaults to root * @return The newly created light component */ -sg::Light & - add_point_light(sg::Scene &scene, const glm::vec3 &position, const sg::LightProperties &props = {}, vkb::scene_graph::NodeC *parent_node = nullptr); +sg::Light &add_point_light(sg::Scene &scene, const glm::vec3 &position, const sg::LightProperties &props = {}, vkb::scene_graph::NodeC *parent_node = nullptr); /** * @brief Adds a directional light to the scene with the specified parameters @@ -92,10 +91,8 @@ sg::Light & * @param parent_node The parent node for the line, defaults to root * @return The newly created light component */ -sg::Light &add_directional_light(sg::Scene &scene, - const glm::quat &rotation, - const sg::LightProperties &props = {}, - vkb::scene_graph::NodeC *parent_node = nullptr); +sg::Light & + add_directional_light(sg::Scene &scene, const glm::quat &rotation, const sg::LightProperties &props = {}, vkb::scene_graph::NodeC *parent_node = nullptr); /** * @brief Adds a spot light to the scene with the specified parameters diff --git a/framework/common/vk_common.cpp b/framework/common/vk_common.cpp index 5814a3f965..663b95a02e 100644 --- a/framework/common/vk_common.cpp +++ b/framework/common/vk_common.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors - * Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2018-2026, Arm Limited and Contributors + * Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -67,15 +67,12 @@ namespace vkb { bool is_depth_only_format(VkFormat format) { - return format == VK_FORMAT_D16_UNORM || - format == VK_FORMAT_D32_SFLOAT; + return format == VK_FORMAT_D16_UNORM || format == VK_FORMAT_D32_SFLOAT; } bool is_depth_stencil_format(VkFormat format) { - return format == VK_FORMAT_D16_UNORM_S8_UINT || - format == VK_FORMAT_D24_UNORM_S8_UINT || - format == VK_FORMAT_D32_SFLOAT_S8_UINT; + return format == VK_FORMAT_D16_UNORM_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT || format == VK_FORMAT_D32_SFLOAT_S8_UINT; } bool is_depth_format(VkFormat format) @@ -152,14 +149,12 @@ void make_filters_valid(VkPhysicalDevice physical_device, VkFormat format, VkFil bool is_dynamic_buffer_descriptor_type(VkDescriptorType descriptor_type) { - return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC || - descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; + return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; } bool is_buffer_descriptor_type(VkDescriptorType descriptor_type) { - return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER || - descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || + return descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || is_dynamic_buffer_descriptor_type(descriptor_type); } @@ -442,11 +437,8 @@ void image_layout_transition(VkCommandBuffer command_buffer, vkCmdPipelineBarrier(command_buffer, src_stage_mask, dst_stage_mask, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); } -void image_layout_transition(VkCommandBuffer command_buffer, - VkImage image, - VkImageLayout old_layout, - VkImageLayout new_layout, - VkImageSubresourceRange const &subresource_range) +void image_layout_transition( + VkCommandBuffer command_buffer, VkImage image, VkImageLayout old_layout, VkImageLayout new_layout, VkImageSubresourceRange const &subresource_range) { VkPipelineStageFlags src_stage_mask = getPipelineStageFlags(old_layout); VkPipelineStageFlags dst_stage_mask = getPipelineStageFlags(new_layout); @@ -457,10 +449,7 @@ void image_layout_transition(VkCommandBuffer command_buffer, } // Fixed sub resource on first mip level and layer -void image_layout_transition(VkCommandBuffer command_buffer, - VkImage image, - VkImageLayout old_layout, - VkImageLayout new_layout) +void image_layout_transition(VkCommandBuffer command_buffer, VkImage image, VkImageLayout old_layout, VkImageLayout new_layout) { VkImageSubresourceRange subresource_range = {}; subresource_range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; @@ -486,45 +475,27 @@ void image_layout_transition(VkCommandBuffer image_memory_barriers.reserve(imagesAndRanges.size()); for (size_t i = 0; i < imagesAndRanges.size(); i++) { - image_memory_barriers.emplace_back(VkImageMemoryBarrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - nullptr, - src_access_mask, - dst_access_mask, - old_layout, - new_layout, - VK_QUEUE_FAMILY_IGNORED, - VK_QUEUE_FAMILY_IGNORED, - imagesAndRanges[i].first, + image_memory_barriers.emplace_back(VkImageMemoryBarrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, nullptr, src_access_mask, dst_access_mask, old_layout, + new_layout, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, imagesAndRanges[i].first, imagesAndRanges[i].second}); } // Put barriers inside setup command buffer - vkCmdPipelineBarrier(command_buffer, - src_stage_mask, - dst_stage_mask, - 0, - 0, - nullptr, - 0, - nullptr, - static_cast(image_memory_barriers.size()), + vkCmdPipelineBarrier(command_buffer, src_stage_mask, dst_stage_mask, 0, 0, nullptr, 0, nullptr, static_cast(image_memory_barriers.size()), image_memory_barriers.data()); } std::vector fixed_rate_compression_flags_to_vector(VkImageCompressionFixedRateFlagsEXT flags) { - const std::vector all_flags = {VK_IMAGE_COMPRESSION_FIXED_RATE_1BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_2BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_3BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_4BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_5BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_6BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_7BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_8BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_9BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_10BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_11BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_12BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_13BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_14BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_15BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_16BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_17BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_18BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_19BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_20BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_21BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_22BPC_BIT_EXT, - VK_IMAGE_COMPRESSION_FIXED_RATE_23BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_24BPC_BIT_EXT}; + const std::vector all_flags = { + VK_IMAGE_COMPRESSION_FIXED_RATE_1BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_2BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_3BPC_BIT_EXT, + VK_IMAGE_COMPRESSION_FIXED_RATE_4BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_5BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_6BPC_BIT_EXT, + VK_IMAGE_COMPRESSION_FIXED_RATE_7BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_8BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_9BPC_BIT_EXT, + VK_IMAGE_COMPRESSION_FIXED_RATE_10BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_11BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_12BPC_BIT_EXT, + VK_IMAGE_COMPRESSION_FIXED_RATE_13BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_14BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_15BPC_BIT_EXT, + VK_IMAGE_COMPRESSION_FIXED_RATE_16BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_17BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_18BPC_BIT_EXT, + VK_IMAGE_COMPRESSION_FIXED_RATE_19BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_20BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_21BPC_BIT_EXT, + VK_IMAGE_COMPRESSION_FIXED_RATE_22BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_23BPC_BIT_EXT, VK_IMAGE_COMPRESSION_FIXED_RATE_24BPC_BIT_EXT}; std::vector flags_vector; @@ -585,11 +556,9 @@ VkSurfaceFormatKHR select_surface_format(VkPhysicalDevice gpu, VkSurfaceKHR surf std::vector supported_surface_formats(surface_format_count); vkGetPhysicalDeviceSurfaceFormatsKHR(gpu, surface, &surface_format_count, supported_surface_formats.data()); - auto it = std::ranges::find_if(supported_surface_formats, - [&preferred_formats](VkSurfaceFormatKHR surface_format) { - return std::ranges::any_of(preferred_formats, - [&surface_format](VkFormat format) { return format == surface_format.format; }); - }); + auto it = std::ranges::find_if(supported_surface_formats, [&preferred_formats](VkSurfaceFormatKHR surface_format) { + return std::ranges::any_of(preferred_formats, [&surface_format](VkFormat format) { return format == surface_format.format; }); + }); // We use the first supported format as a fallback in case none of the preferred formats is available return it != supported_surface_formats.end() ? *it : supported_surface_formats[0]; @@ -688,8 +657,9 @@ uint32_t get_queue_family_index(std::vector const &queu // Try to find a queue family index that supports compute but not graphics if (queue_flag & VK_QUEUE_COMPUTE_BIT) { - auto propertyIt = std::ranges::find_if(queue_family_properties, - [queue_flag](const VkQueueFamilyProperties &property) { return (property.queueFlags & queue_flag) && !(property.queueFlags & VK_QUEUE_GRAPHICS_BIT); }); + auto propertyIt = std::ranges::find_if(queue_family_properties, [queue_flag](const VkQueueFamilyProperties &property) { + return (property.queueFlags & queue_flag) && !(property.queueFlags & VK_QUEUE_GRAPHICS_BIT); + }); if (propertyIt != queue_family_properties.end()) { return static_cast(std::distance(queue_family_properties.begin(), propertyIt)); @@ -700,11 +670,9 @@ uint32_t get_queue_family_index(std::vector const &queu // Try to find a queue family index that supports transfer but not graphics and compute if (queue_flag & VK_QUEUE_TRANSFER_BIT) { - auto propertyIt = std::ranges::find_if(queue_family_properties, - [queue_flag](const VkQueueFamilyProperties &property) { - return (property.queueFlags & queue_flag) && !(property.queueFlags & VK_QUEUE_GRAPHICS_BIT) && - !(property.queueFlags & VK_QUEUE_COMPUTE_BIT); - }); + auto propertyIt = std::ranges::find_if(queue_family_properties, [queue_flag](const VkQueueFamilyProperties &property) { + return (property.queueFlags & queue_flag) && !(property.queueFlags & VK_QUEUE_GRAPHICS_BIT) && !(property.queueFlags & VK_QUEUE_COMPUTE_BIT); + }); if (propertyIt != queue_family_properties.end()) { return static_cast(std::distance(queue_family_properties.begin(), propertyIt)); @@ -712,8 +680,8 @@ uint32_t get_queue_family_index(std::vector const &queu } // For other queue types or if no separate compute queue is present, return the first one to support the requested flags - auto propertyIt = std::ranges::find_if( - queue_family_properties, [queue_flag](const VkQueueFamilyProperties &property) { return (property.queueFlags & queue_flag) == queue_flag; }); + auto propertyIt = std::ranges::find_if(queue_family_properties, + [queue_flag](const VkQueueFamilyProperties &property) { return (property.queueFlags & queue_flag) == queue_flag; }); if (propertyIt != queue_family_properties.end()) { return static_cast(std::distance(queue_family_properties.begin(), propertyIt)); diff --git a/framework/common/vk_common.h b/framework/common/vk_common.h index 8ddaf4a76d..1608a8786b 100644 --- a/framework/common/vk_common.h +++ b/framework/common/vk_common.h @@ -92,10 +92,8 @@ bool is_depth_format(VkFormat format); */ VkFormat get_suitable_depth_format(VkPhysicalDevice physical_device, bool depth_only = false, - const std::vector &depth_format_priority_list = { - VK_FORMAT_D32_SFLOAT, - VK_FORMAT_D24_UNORM_S8_UINT, - VK_FORMAT_D16_UNORM}); + const std::vector &depth_format_priority_list = {VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT, + VK_FORMAT_D16_UNORM}); /** * @brief Helper function to pick a blendable format from a priority ordered list @@ -168,8 +166,8 @@ VkShaderModule load_shader_from_vector(const std::vector &spirv, VkDev */ VkSurfaceFormatKHR select_surface_format(VkPhysicalDevice gpu, VkSurfaceKHR surface, - std::vector const &preferred_formats = { - VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_A8B8G8R8_SRGB_PACK32}); + std::vector const &preferred_formats = {VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_B8G8R8A8_SRGB, + VK_FORMAT_A8B8G8R8_SRGB_PACK32}); /** * @brief Image memory barrier structure used to define @@ -242,11 +240,8 @@ void image_layout_transition(VkCommandBuffer command_buffer, * @param new_layout The VkImageLayout to transition to. * @param subresource_range The VkImageSubresourceRange to use with the transition. */ -void image_layout_transition(VkCommandBuffer command_buffer, - VkImage image, - VkImageLayout old_layout, - VkImageLayout new_layout, - VkImageSubresourceRange const &subresource_range); +void image_layout_transition( + VkCommandBuffer command_buffer, VkImage image, VkImageLayout old_layout, VkImageLayout new_layout, VkImageSubresourceRange const &subresource_range); /** * @brief Put an image memory barrier for a layout transition of an image, on a fixed subresource with first mip level and layer. @@ -258,10 +253,7 @@ void image_layout_transition(VkCommandBuffer command_buffer, * @param old_layout The VkImageLayout to transition from. * @param new_layout The VkImageLayout to transition to. */ -void image_layout_transition(VkCommandBuffer command_buffer, - VkImage image, - VkImageLayout old_layout, - VkImageLayout new_layout); +void image_layout_transition(VkCommandBuffer command_buffer, VkImage image, VkImageLayout old_layout, VkImageLayout new_layout); /** * @brief Put an image memory barrier for a layout transition of a vector of images, with a given subresource range per image. diff --git a/framework/common/vk_initializers.h b/framework/common/vk_initializers.h index ac05cd8557..1f3b388709 100644 --- a/framework/common/vk_initializers.h +++ b/framework/common/vk_initializers.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Sascha Willems * Copyright (c) 2025, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 @@ -39,10 +39,7 @@ inline VkMappedMemoryRange mapped_memory_range() return mapped_memory_range; } -inline VkCommandBufferAllocateInfo command_buffer_allocate_info( - VkCommandPool command_pool, - VkCommandBufferLevel level, - uint32_t buffer_count) +inline VkCommandBufferAllocateInfo command_buffer_allocate_info(VkCommandPool command_pool, VkCommandBufferLevel level, uint32_t buffer_count) { VkCommandBufferAllocateInfo command_buffer_allocate_info{}; command_buffer_allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; @@ -75,11 +72,7 @@ inline VkCommandBufferInheritanceInfo command_buffer_inheritance_info() inline VkComponentMapping component_mapping() { - return { - .r = VK_COMPONENT_SWIZZLE_R, - .g = VK_COMPONENT_SWIZZLE_G, - .b = VK_COMPONENT_SWIZZLE_B, - .a = VK_COMPONENT_SWIZZLE_A}; + return {.r = VK_COMPONENT_SWIZZLE_R, .g = VK_COMPONENT_SWIZZLE_G, .b = VK_COMPONENT_SWIZZLE_B, .a = VK_COMPONENT_SWIZZLE_A}; } inline VkRenderPassBeginInfo render_pass_begin_info() @@ -210,11 +203,7 @@ inline VkSubmitInfo submit_info() return submit_info; } -inline VkViewport viewport( - float width, - float height, - float min_depth, - float max_depth) +inline VkViewport viewport(float width, float height, float min_depth, float max_depth) { VkViewport viewport{}; viewport.width = width; @@ -224,11 +213,7 @@ inline VkViewport viewport( return viewport; } -inline VkRect2D rect2D( - int32_t width, - int32_t height, - int32_t offset_x, - int32_t offset_y) +inline VkRect2D rect2D(int32_t width, int32_t height, int32_t offset_x, int32_t offset_y) { VkRect2D rect2D{}; rect2D.extent.width = width; @@ -245,9 +230,7 @@ inline VkBufferCreateInfo buffer_create_info() return buffer_create_info; } -inline VkBufferCreateInfo buffer_create_info( - VkBufferUsageFlags usage, - VkDeviceSize size) +inline VkBufferCreateInfo buffer_create_info(VkBufferUsageFlags usage, VkDeviceSize size) { VkBufferCreateInfo buffer_create_info{}; buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; @@ -256,10 +239,7 @@ inline VkBufferCreateInfo buffer_create_info( return buffer_create_info; } -inline VkDescriptorPoolCreateInfo descriptor_pool_create_info( - uint32_t count, - VkDescriptorPoolSize *pool_sizes, - uint32_t max_sets) +inline VkDescriptorPoolCreateInfo descriptor_pool_create_info(uint32_t count, VkDescriptorPoolSize *pool_sizes, uint32_t max_sets) { VkDescriptorPoolCreateInfo descriptor_pool_info{}; descriptor_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; @@ -269,9 +249,7 @@ inline VkDescriptorPoolCreateInfo descriptor_pool_create_info( return descriptor_pool_info; } -inline VkDescriptorPoolCreateInfo descriptor_pool_create_info( - const std::vector &pool_sizes, - uint32_t max_sets) +inline VkDescriptorPoolCreateInfo descriptor_pool_create_info(const std::vector &pool_sizes, uint32_t max_sets) { VkDescriptorPoolCreateInfo descriptor_pool_info{}; descriptor_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; @@ -281,9 +259,7 @@ inline VkDescriptorPoolCreateInfo descriptor_pool_create_info( return descriptor_pool_info; } -inline VkDescriptorPoolSize descriptor_pool_size( - VkDescriptorType type, - uint32_t count) +inline VkDescriptorPoolSize descriptor_pool_size(VkDescriptorType type, uint32_t count) { VkDescriptorPoolSize descriptor_pool_size{}; descriptor_pool_size.type = type; @@ -291,11 +267,7 @@ inline VkDescriptorPoolSize descriptor_pool_size( return descriptor_pool_size; } -inline VkDescriptorSetLayoutBinding descriptor_set_layout_binding( - VkDescriptorType type, - VkShaderStageFlags flags, - uint32_t binding, - uint32_t count = 1) +inline VkDescriptorSetLayoutBinding descriptor_set_layout_binding(VkDescriptorType type, VkShaderStageFlags flags, uint32_t binding, uint32_t count = 1) { VkDescriptorSetLayoutBinding set_layout_binding{}; set_layout_binding.descriptorType = type; @@ -305,9 +277,7 @@ inline VkDescriptorSetLayoutBinding descriptor_set_layout_binding( return set_layout_binding; } -inline VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info( - const VkDescriptorSetLayoutBinding *bindings, - uint32_t binding_count) +inline VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(const VkDescriptorSetLayoutBinding *bindings, uint32_t binding_count) { VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info{}; descriptor_set_layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; @@ -316,8 +286,7 @@ inline VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info( return descriptor_set_layout_create_info; } -inline VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info( - const std::vector &bindings) +inline VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(const std::vector &bindings) { VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info{}; descriptor_set_layout_create_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; @@ -326,9 +295,7 @@ inline VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info( return descriptor_set_layout_create_info; } -inline VkPipelineLayoutCreateInfo pipeline_layout_create_info( - const VkDescriptorSetLayout *set_layouts, - uint32_t set_layout_count = 1) +inline VkPipelineLayoutCreateInfo pipeline_layout_create_info(const VkDescriptorSetLayout *set_layouts, uint32_t set_layout_count = 1) { VkPipelineLayoutCreateInfo pipeline_layout_create_info{}; pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; @@ -337,8 +304,7 @@ inline VkPipelineLayoutCreateInfo pipeline_layout_create_info( return pipeline_layout_create_info; } -inline VkPipelineLayoutCreateInfo pipeline_layout_create_info( - uint32_t set_layout_count = 1) +inline VkPipelineLayoutCreateInfo pipeline_layout_create_info(uint32_t set_layout_count = 1) { VkPipelineLayoutCreateInfo pipeline_layout_create_info{}; pipeline_layout_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; @@ -346,10 +312,8 @@ inline VkPipelineLayoutCreateInfo pipeline_layout_create_info( return pipeline_layout_create_info; } -inline VkDescriptorSetAllocateInfo descriptor_set_allocate_info( - VkDescriptorPool descriptor_pool, - const VkDescriptorSetLayout *set_layouts, - uint32_t descriptor_set_count) +inline VkDescriptorSetAllocateInfo + descriptor_set_allocate_info(VkDescriptorPool descriptor_pool, const VkDescriptorSetLayout *set_layouts, uint32_t descriptor_set_count) { VkDescriptorSetAllocateInfo descriptor_set_allocate_info{}; descriptor_set_allocate_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; @@ -368,12 +332,8 @@ inline VkDescriptorImageInfo descriptor_image_info(VkSampler sampler, VkImageVie return descriptor_image_info; } -inline VkWriteDescriptorSet write_descriptor_set( - VkDescriptorSet dst_set, - VkDescriptorType type, - uint32_t binding, - VkDescriptorBufferInfo *buffer_info, - uint32_t descriptor_count = 1) +inline VkWriteDescriptorSet + write_descriptor_set(VkDescriptorSet dst_set, VkDescriptorType type, uint32_t binding, VkDescriptorBufferInfo *buffer_info, uint32_t descriptor_count = 1) { VkWriteDescriptorSet write_descriptor_set{}; write_descriptor_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; @@ -385,12 +345,8 @@ inline VkWriteDescriptorSet write_descriptor_set( return write_descriptor_set; } -inline VkWriteDescriptorSet write_descriptor_set( - VkDescriptorSet dst_set, - VkDescriptorType type, - uint32_t binding, - VkDescriptorImageInfo *image_info, - uint32_t descriptor_count = 1) +inline VkWriteDescriptorSet + write_descriptor_set(VkDescriptorSet dst_set, VkDescriptorType type, uint32_t binding, VkDescriptorImageInfo *image_info, uint32_t descriptor_count = 1) { VkWriteDescriptorSet write_descriptor_set{}; write_descriptor_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; @@ -402,10 +358,7 @@ inline VkWriteDescriptorSet write_descriptor_set( return write_descriptor_set; } -inline VkVertexInputBindingDescription vertex_input_binding_description( - uint32_t binding, - uint32_t stride, - VkVertexInputRate input_rate) +inline VkVertexInputBindingDescription vertex_input_binding_description(uint32_t binding, uint32_t stride, VkVertexInputRate input_rate) { VkVertexInputBindingDescription vertex_input_binding_description{}; vertex_input_binding_description.binding = binding; @@ -414,11 +367,8 @@ inline VkVertexInputBindingDescription vertex_input_binding_description( return vertex_input_binding_description; } -inline VkVertexInputBindingDescription2EXT vertex_input_binding_description2ext( - uint32_t binding, - uint32_t stride, - VkVertexInputRate input_rate, - uint32_t divisor) +inline VkVertexInputBindingDescription2EXT + vertex_input_binding_description2ext(uint32_t binding, uint32_t stride, VkVertexInputRate input_rate, uint32_t divisor) { VkVertexInputBindingDescription2EXT vertex_input_binding_description2ext{}; vertex_input_binding_description2ext.sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_BINDING_DESCRIPTION_2_EXT; @@ -429,11 +379,7 @@ inline VkVertexInputBindingDescription2EXT vertex_input_binding_description2ext( return vertex_input_binding_description2ext; } -inline VkVertexInputAttributeDescription vertex_input_attribute_description( - uint32_t binding, - uint32_t location, - VkFormat format, - uint32_t offset) +inline VkVertexInputAttributeDescription vertex_input_attribute_description(uint32_t binding, uint32_t location, VkFormat format, uint32_t offset) { VkVertexInputAttributeDescription vertex_input_attribute_description{}; vertex_input_attribute_description.location = location; @@ -443,11 +389,7 @@ inline VkVertexInputAttributeDescription vertex_input_attribute_description( return vertex_input_attribute_description; } -inline VkVertexInputAttributeDescription2EXT vertex_input_attribute_description2ext( - uint32_t binding, - uint32_t location, - VkFormat format, - uint32_t offset) +inline VkVertexInputAttributeDescription2EXT vertex_input_attribute_description2ext(uint32_t binding, uint32_t location, VkFormat format, uint32_t offset) { VkVertexInputAttributeDescription2EXT vertex_input_attribute_description2ext{}; vertex_input_attribute_description2ext.sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_ATTRIBUTE_DESCRIPTION_2_EXT; @@ -465,10 +407,8 @@ inline VkPipelineVertexInputStateCreateInfo pipeline_vertex_input_state_create_i return pipeline_vertex_input_state_create_info; } -inline VkPipelineInputAssemblyStateCreateInfo pipeline_input_assembly_state_create_info( - VkPrimitiveTopology topology, - VkPipelineInputAssemblyStateCreateFlags flags, - VkBool32 primitive_restart_enable) +inline VkPipelineInputAssemblyStateCreateInfo + pipeline_input_assembly_state_create_info(VkPrimitiveTopology topology, VkPipelineInputAssemblyStateCreateFlags flags, VkBool32 primitive_restart_enable) { VkPipelineInputAssemblyStateCreateInfo pipeline_input_assembly_state_create_info{}; pipeline_input_assembly_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; @@ -478,11 +418,10 @@ inline VkPipelineInputAssemblyStateCreateInfo pipeline_input_assembly_state_crea return pipeline_input_assembly_state_create_info; } -inline VkPipelineRasterizationStateCreateInfo pipeline_rasterization_state_create_info( - VkPolygonMode polygon_mode, - VkCullModeFlags cull_mode, - VkFrontFace front_face, - VkPipelineRasterizationStateCreateFlags flags = 0) +inline VkPipelineRasterizationStateCreateInfo pipeline_rasterization_state_create_info(VkPolygonMode polygon_mode, + VkCullModeFlags cull_mode, + VkFrontFace front_face, + VkPipelineRasterizationStateCreateFlags flags = 0) { VkPipelineRasterizationStateCreateInfo pipeline_rasterization_state_create_info{}; pipeline_rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; @@ -495,9 +434,7 @@ inline VkPipelineRasterizationStateCreateInfo pipeline_rasterization_state_creat return pipeline_rasterization_state_create_info; } -inline VkPipelineColorBlendAttachmentState pipeline_color_blend_attachment_state( - VkColorComponentFlags color_write_mask, - VkBool32 blend_enable) +inline VkPipelineColorBlendAttachmentState pipeline_color_blend_attachment_state(VkColorComponentFlags color_write_mask, VkBool32 blend_enable) { VkPipelineColorBlendAttachmentState pipeline_color_blend_attachment_state{}; pipeline_color_blend_attachment_state.colorWriteMask = color_write_mask; @@ -505,9 +442,8 @@ inline VkPipelineColorBlendAttachmentState pipeline_color_blend_attachment_state return pipeline_color_blend_attachment_state; } -inline VkPipelineColorBlendStateCreateInfo pipeline_color_blend_state_create_info( - uint32_t attachment_count, - const VkPipelineColorBlendAttachmentState *attachments) +inline VkPipelineColorBlendStateCreateInfo pipeline_color_blend_state_create_info(uint32_t attachment_count, + const VkPipelineColorBlendAttachmentState *attachments) { VkPipelineColorBlendStateCreateInfo pipeline_color_blend_state_create_info{}; pipeline_color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; @@ -516,10 +452,8 @@ inline VkPipelineColorBlendStateCreateInfo pipeline_color_blend_state_create_inf return pipeline_color_blend_state_create_info; } -inline VkPipelineDepthStencilStateCreateInfo pipeline_depth_stencil_state_create_info( - VkBool32 depth_test_enable, - VkBool32 depth_write_enable, - VkCompareOp depth_compare_op) +inline VkPipelineDepthStencilStateCreateInfo + pipeline_depth_stencil_state_create_info(VkBool32 depth_test_enable, VkBool32 depth_write_enable, VkCompareOp depth_compare_op) { VkPipelineDepthStencilStateCreateInfo pipeline_depth_stencil_state_create_info{}; pipeline_depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; @@ -531,10 +465,8 @@ inline VkPipelineDepthStencilStateCreateInfo pipeline_depth_stencil_state_create return pipeline_depth_stencil_state_create_info; } -inline VkPipelineViewportStateCreateInfo pipeline_viewport_state_create_info( - uint32_t viewport_count, - uint32_t scissor_count, - VkPipelineViewportStateCreateFlags flags = 0) +inline VkPipelineViewportStateCreateInfo + pipeline_viewport_state_create_info(uint32_t viewport_count, uint32_t scissor_count, VkPipelineViewportStateCreateFlags flags = 0) { VkPipelineViewportStateCreateInfo pipeline_viewport_state_create_info{}; pipeline_viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; @@ -544,9 +476,8 @@ inline VkPipelineViewportStateCreateInfo pipeline_viewport_state_create_info( return pipeline_viewport_state_create_info; } -inline VkPipelineMultisampleStateCreateInfo pipeline_multisample_state_create_info( - VkSampleCountFlagBits rasterization_samples, - VkPipelineMultisampleStateCreateFlags flags = 0) +inline VkPipelineMultisampleStateCreateInfo pipeline_multisample_state_create_info(VkSampleCountFlagBits rasterization_samples, + VkPipelineMultisampleStateCreateFlags flags = 0) { VkPipelineMultisampleStateCreateInfo pipeline_multisample_state_create_info{}; pipeline_multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; @@ -555,10 +486,8 @@ inline VkPipelineMultisampleStateCreateInfo pipeline_multisample_state_create_in return pipeline_multisample_state_create_info; } -inline VkPipelineDynamicStateCreateInfo pipeline_dynamic_state_create_info( - const VkDynamicState *dynamic_states, - uint32_t dynamicStateCount, - VkPipelineDynamicStateCreateFlags flags = 0) +inline VkPipelineDynamicStateCreateInfo + pipeline_dynamic_state_create_info(const VkDynamicState *dynamic_states, uint32_t dynamicStateCount, VkPipelineDynamicStateCreateFlags flags = 0) { VkPipelineDynamicStateCreateInfo pipeline_dynamic_state_create_info{}; pipeline_dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; @@ -568,9 +497,8 @@ inline VkPipelineDynamicStateCreateInfo pipeline_dynamic_state_create_info( return pipeline_dynamic_state_create_info; } -inline VkPipelineDynamicStateCreateInfo pipeline_dynamic_state_create_info( - const std::vector &dynamic_states, - VkPipelineDynamicStateCreateFlags flags = 0) +inline VkPipelineDynamicStateCreateInfo pipeline_dynamic_state_create_info(const std::vector &dynamic_states, + VkPipelineDynamicStateCreateFlags flags = 0) { VkPipelineDynamicStateCreateInfo pipeline_dynamic_state_create_info{}; pipeline_dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; @@ -588,10 +516,7 @@ inline VkPipelineTessellationStateCreateInfo pipeline_tessellation_state_create_ return pipeline_tessellation_state_create_info; } -inline VkGraphicsPipelineCreateInfo pipeline_create_info( - VkPipelineLayout layout, - VkRenderPass render_pass, - VkPipelineCreateFlags flags = 0) +inline VkGraphicsPipelineCreateInfo pipeline_create_info(VkPipelineLayout layout, VkRenderPass render_pass, VkPipelineCreateFlags flags = 0) { VkGraphicsPipelineCreateInfo pipeline_create_info{}; pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; @@ -612,9 +537,7 @@ inline VkGraphicsPipelineCreateInfo pipeline_create_info() return pipeline_create_info; } -inline VkComputePipelineCreateInfo compute_pipeline_create_info( - VkPipelineLayout layout, - VkPipelineCreateFlags flags = 0) +inline VkComputePipelineCreateInfo compute_pipeline_create_info(VkPipelineLayout layout, VkPipelineCreateFlags flags = 0) { VkComputePipelineCreateInfo compute_pipeline_create_info{}; compute_pipeline_create_info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; @@ -623,10 +546,7 @@ inline VkComputePipelineCreateInfo compute_pipeline_create_info( return compute_pipeline_create_info; } -inline VkPushConstantRange push_constant_range( - VkShaderStageFlags stage_flags, - uint32_t size, - uint32_t offset) +inline VkPushConstantRange push_constant_range(VkShaderStageFlags stage_flags, uint32_t size, uint32_t offset) { VkPushConstantRange push_constant_range{}; push_constant_range.stageFlags = stage_flags; @@ -663,15 +583,11 @@ inline VkSpecializationInfo specialization_info(uint32_t map_entry_count, const return specialization_info; } -inline VkTimelineSemaphoreSubmitInfo timeline_semaphore_submit_info(uint32_t wait_value_count, uint64_t *wait_values, uint32_t signal_value_count, uint64_t *signal_values) +inline VkTimelineSemaphoreSubmitInfo + timeline_semaphore_submit_info(uint32_t wait_value_count, uint64_t *wait_values, uint32_t signal_value_count, uint64_t *signal_values) { return VkTimelineSemaphoreSubmitInfo{ - VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO, - NULL, - wait_value_count, - wait_values, - signal_value_count, - signal_values}; + VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO, NULL, wait_value_count, wait_values, signal_value_count, signal_values}; } } // namespace initializers } // namespace vkb diff --git a/framework/core/acceleration_structure.cpp b/framework/core/acceleration_structure.cpp index 4ad0885e2e..78c28311b5 100644 --- a/framework/core/acceleration_structure.cpp +++ b/framework/core/acceleration_structure.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, Sascha Willems +/* Copyright (c) 2021-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -23,12 +23,8 @@ namespace vkb { namespace core { -AccelerationStructure::AccelerationStructure(vkb::core::DeviceC &device, - VkAccelerationStructureTypeKHR type) : - device{device}, - type{type} -{ -} +AccelerationStructure::AccelerationStructure(vkb::core::DeviceC &device, VkAccelerationStructureTypeKHR type) : device{device}, type{type} +{} AccelerationStructure::~AccelerationStructure() { @@ -53,17 +49,18 @@ uint64_t AccelerationStructure::add_triangle_geometry(vkb::core::BufferC &vertex uint64_t transform_buffer_data_address) { VkAccelerationStructureGeometryKHR geometry{}; - geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; - geometry.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; - geometry.flags = flags; - geometry.geometry.triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; - geometry.geometry.triangles.vertexFormat = vertex_format; - geometry.geometry.triangles.maxVertex = max_vertex; - geometry.geometry.triangles.vertexStride = vertex_stride; - geometry.geometry.triangles.indexType = index_type; - geometry.geometry.triangles.vertexData.deviceAddress = vertex_buffer_data_address == 0 ? vertex_buffer.get_device_address() : vertex_buffer_data_address; - geometry.geometry.triangles.indexData.deviceAddress = index_buffer_data_address == 0 ? index_buffer.get_device_address() : index_buffer_data_address; - geometry.geometry.triangles.transformData.deviceAddress = transform_buffer_data_address == 0 ? transform_buffer.get_device_address() : transform_buffer_data_address; + geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; + geometry.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; + geometry.flags = flags; + geometry.geometry.triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; + geometry.geometry.triangles.vertexFormat = vertex_format; + geometry.geometry.triangles.maxVertex = max_vertex; + geometry.geometry.triangles.vertexStride = vertex_stride; + geometry.geometry.triangles.indexType = index_type; + geometry.geometry.triangles.vertexData.deviceAddress = vertex_buffer_data_address == 0 ? vertex_buffer.get_device_address() : vertex_buffer_data_address; + geometry.geometry.triangles.indexData.deviceAddress = index_buffer_data_address == 0 ? index_buffer.get_device_address() : index_buffer_data_address; + geometry.geometry.triangles.transformData.deviceAddress = + transform_buffer_data_address == 0 ? transform_buffer.get_device_address() : transform_buffer_data_address; uint64_t index = geometries.size(); geometries.insert({index, {geometry, triangle_count, transform_offset}}); @@ -74,31 +71,38 @@ void AccelerationStructure::update_triangle_geometry(uint64_t std::unique_ptr &vertex_buffer, std::unique_ptr &index_buffer, std::unique_ptr &transform_buffer, - uint32_t triangle_count, uint32_t max_vertex, - VkDeviceSize vertex_stride, uint32_t transform_offset, - VkFormat vertex_format, VkGeometryFlagsKHR flags, - uint64_t vertex_buffer_data_address, - uint64_t index_buffer_data_address, - uint64_t transform_buffer_data_address) + uint32_t triangle_count, + uint32_t max_vertex, + VkDeviceSize vertex_stride, + uint32_t transform_offset, + VkFormat vertex_format, + VkGeometryFlagsKHR flags, + uint64_t vertex_buffer_data_address, + uint64_t index_buffer_data_address, + uint64_t transform_buffer_data_address) { - VkAccelerationStructureGeometryKHR *geometry = &geometries[triangleUUID].geometry; - geometry->sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; - geometry->geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; - geometry->flags = flags; - geometry->geometry.triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; - geometry->geometry.triangles.vertexFormat = vertex_format; - geometry->geometry.triangles.maxVertex = max_vertex; - geometry->geometry.triangles.vertexStride = vertex_stride; - geometry->geometry.triangles.indexType = VK_INDEX_TYPE_UINT32; - geometry->geometry.triangles.vertexData.deviceAddress = vertex_buffer_data_address == 0 ? vertex_buffer->get_device_address() : vertex_buffer_data_address; - geometry->geometry.triangles.indexData.deviceAddress = index_buffer_data_address == 0 ? index_buffer->get_device_address() : index_buffer_data_address; - geometry->geometry.triangles.transformData.deviceAddress = transform_buffer_data_address == 0 ? transform_buffer->get_device_address() : transform_buffer_data_address; - geometries[triangleUUID].primitive_count = triangle_count; - geometries[triangleUUID].transform_offset = transform_offset; - geometries[triangleUUID].updated = true; + VkAccelerationStructureGeometryKHR *geometry = &geometries[triangleUUID].geometry; + geometry->sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; + geometry->geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; + geometry->flags = flags; + geometry->geometry.triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; + geometry->geometry.triangles.vertexFormat = vertex_format; + geometry->geometry.triangles.maxVertex = max_vertex; + geometry->geometry.triangles.vertexStride = vertex_stride; + geometry->geometry.triangles.indexType = VK_INDEX_TYPE_UINT32; + geometry->geometry.triangles.vertexData.deviceAddress = vertex_buffer_data_address == 0 ? vertex_buffer->get_device_address() : vertex_buffer_data_address; + geometry->geometry.triangles.indexData.deviceAddress = index_buffer_data_address == 0 ? index_buffer->get_device_address() : index_buffer_data_address; + geometry->geometry.triangles.transformData.deviceAddress = + transform_buffer_data_address == 0 ? transform_buffer->get_device_address() : transform_buffer_data_address; + geometries[triangleUUID].primitive_count = triangle_count; + geometries[triangleUUID].transform_offset = transform_offset; + geometries[triangleUUID].updated = true; } -uint64_t AccelerationStructure::add_instance_geometry(std::unique_ptr &instance_buffer, uint32_t instance_count, uint32_t transform_offset, VkGeometryFlagsKHR flags) +uint64_t AccelerationStructure::add_instance_geometry(std::unique_ptr &instance_buffer, + uint32_t instance_count, + uint32_t transform_offset, + VkGeometryFlagsKHR flags) { VkAccelerationStructureGeometryKHR geometry{}; geometry.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; @@ -113,10 +117,8 @@ uint64_t AccelerationStructure::add_instance_geometry(std::unique_ptr &instance_buffer, - uint32_t instance_count, uint32_t transform_offset, - VkGeometryFlagsKHR flags) +void AccelerationStructure::update_instance_geometry( + uint64_t instance_UID, std::unique_ptr &instance_buffer, uint32_t instance_count, uint32_t transform_offset, VkGeometryFlagsKHR flags) { VkAccelerationStructureGeometryKHR *geometry = &geometries[instance_UID].geometry; geometry->sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; @@ -170,28 +172,22 @@ void AccelerationStructure::build(VkQueue queue, VkBuildAccelerationStructureFla // Get required build sizes build_sizes_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR; - vkGetAccelerationStructureBuildSizesKHR( - device.get_handle(), - VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, - &build_geometry_info, - primitive_counts.data(), - &build_sizes_info); + vkGetAccelerationStructureBuildSizesKHR(device.get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &build_geometry_info, primitive_counts.data(), + &build_sizes_info); // Create a buffer for the acceleration structure if (!buffer || buffer->get_size() != build_sizes_info.accelerationStructureSize) { - buffer = std::make_unique( - device, - build_sizes_info.accelerationStructureSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + buffer = std::make_unique(device, build_sizes_info.accelerationStructureSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VMA_MEMORY_USAGE_GPU_ONLY); VkAccelerationStructureCreateInfoKHR acceleration_structure_create_info{}; acceleration_structure_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR; acceleration_structure_create_info.buffer = buffer->get_handle(); acceleration_structure_create_info.size = build_sizes_info.accelerationStructureSize; acceleration_structure_create_info.type = type; - VkResult result = vkCreateAccelerationStructureKHR(device.get_handle(), &acceleration_structure_create_info, nullptr, &handle); + VkResult result = vkCreateAccelerationStructureKHR(device.get_handle(), &acceleration_structure_create_info, nullptr, &handle); if (result != VK_SUCCESS) { @@ -206,12 +202,11 @@ void AccelerationStructure::build(VkQueue queue, VkBuildAccelerationStructureFla device_address = vkGetAccelerationStructureDeviceAddressKHR(device.get_handle(), &acceleration_device_address_info); // Create a scratch buffer as a temporary storage for the acceleration structure build - scratch_buffer = std::make_unique( - device, - BufferBuilderC(build_sizes_info.buildScratchSize) - .with_usage(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) - .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY) - .with_alignment(scratch_buffer_alignment)); + scratch_buffer = + std::make_unique(device, BufferBuilderC(build_sizes_info.buildScratchSize) + .with_usage(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) + .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY) + .with_alignment(scratch_buffer_alignment)); build_geometry_info.scratchData.deviceAddress = scratch_buffer->get_device_address(); build_geometry_info.dstAccelerationStructure = handle; @@ -219,11 +214,7 @@ void AccelerationStructure::build(VkQueue queue, VkBuildAccelerationStructureFla // Build the acceleration structure on the device via a one-time command buffer submission VkCommandBuffer command_buffer = device.create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); auto as_build_range_infos = &*acceleration_structure_build_range_infos.data(); - vkCmdBuildAccelerationStructuresKHR( - command_buffer, - 1, - &build_geometry_info, - &as_build_range_infos); + vkCmdBuildAccelerationStructuresKHR(command_buffer, 1, &build_geometry_info, &as_build_range_infos); device.flush_command_buffer(command_buffer, queue); scratch_buffer.reset(); } diff --git a/framework/core/acceleration_structure.h b/framework/core/acceleration_structure.h index 0c29a919fe..166a9415d2 100644 --- a/framework/core/acceleration_structure.h +++ b/framework/core/acceleration_structure.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, Sascha Willems +/* Copyright (c) 2021-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -40,8 +40,7 @@ class AccelerationStructure * @param device A valid Vulkan device * @param type The type of the acceleration structure (top- or bottom-level) */ - AccelerationStructure(vkb::core::DeviceC &device, - VkAccelerationStructureTypeKHR type); + AccelerationStructure(vkb::core::DeviceC &device, VkAccelerationStructureTypeKHR type); ~AccelerationStructure(); @@ -76,7 +75,8 @@ class AccelerationStructure uint64_t index_buffer_data_address = 0, uint64_t transform_buffer_data_address = 0); - void update_triangle_geometry(uint64_t triangleUUID, std::unique_ptr &vertex_buffer, + void update_triangle_geometry(uint64_t triangleUUID, + std::unique_ptr &vertex_buffer, std::unique_ptr &index_buffer, std::unique_ptr &transform_buffer, uint32_t triangle_count, @@ -102,10 +102,11 @@ class AccelerationStructure uint32_t transform_offset = 0, VkGeometryFlagsKHR flags = VK_GEOMETRY_OPAQUE_BIT_KHR); - void update_instance_geometry(uint64_t instance_UID, std::unique_ptr &instance_buffer, - uint32_t instance_count, - uint32_t transform_offset = 0, - VkGeometryFlagsKHR flags = VK_GEOMETRY_OPAQUE_BIT_KHR); + void update_instance_geometry(uint64_t instance_UID, + std::unique_ptr &instance_buffer, + uint32_t instance_count, + uint32_t transform_offset = 0, + VkGeometryFlagsKHR flags = VK_GEOMETRY_OPAQUE_BIT_KHR); /** * @brief Builds the acceleration structure on the device (requires at least one geometry to be added) diff --git a/framework/core/allocated.h b/framework/core/allocated.h index a7734803ab..eca704cff9 100644 --- a/framework/core/allocated.h +++ b/framework/core/allocated.h @@ -79,8 +79,7 @@ void init(const DeviceType &device) allocator_info.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT; } - if (device.get_gpu().is_extension_supported(VK_EXT_MEMORY_PRIORITY_EXTENSION_NAME) && - device.is_extension_enabled(VK_EXT_MEMORY_PRIORITY_EXTENSION_NAME)) + if (device.get_gpu().is_extension_supported(VK_EXT_MEMORY_PRIORITY_EXTENSION_NAME) && device.is_extension_enabled(VK_EXT_MEMORY_PRIORITY_EXTENSION_NAME)) { allocator_info.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT; } @@ -238,8 +237,9 @@ class Allocated : public vkb::core::VulkanResource * pass a vector of items to the update method, which will then be copied into the buffer as bytes. * * This function DOES NOT automatically manage adhering to the alignment requirements of the items being copied, - * for instance the `minUniformBufferOffsetAlignment` property of the [device](https://vulkan.gpuinfo.org/displaydevicelimit.php?name=minUniformBufferOffsetAlignment&platform=all). - * If the data needs to be aligned on something other than `sizeof(T)`, the user must manage that themselves. + * for instance the `minUniformBufferOffsetAlignment` property of the + * [device](https://vulkan.gpuinfo.org/displaydevicelimit.php?name=minUniformBufferOffsetAlignment&platform=all). If the data needs to be aligned on + * something other than `sizeof(T)`, the user must manage that themselves. * @param data The data vector to upload * @param offset The offset to start the copying into the mapped data * @deprecated Use the `updateTyped` method that uses the `vk::ArrayProxy` class instead. @@ -287,8 +287,9 @@ class Allocated : public vkb::core::VulkanResource * coupling is always present, so the `vk::ArrayProxy` may as well be used to our advantage here. * * @note This function DOES NOT automatically manage adhering to the alignment requirements of the items being copied, - * for instance the `minUniformBufferOffsetAlignment` property of the [device](https://vulkan.gpuinfo.org/displaydevicelimit.php?name=minUniformBufferOffsetAlignment&platform=all). - * If the data needs to be aligned on something other than `sizeof(T)`, the user must manage that themselves. + * for instance the `minUniformBufferOffsetAlignment` property of the + * [device](https://vulkan.gpuinfo.org/displaydevicelimit.php?name=minUniformBufferOffsetAlignment&platform=all). If the data needs to be aligned on + * something other than `sizeof(T)`, the user must manage that themselves. * * @todo create `updateTypedAligned` which has an additional argument specifying the required GPU alignment of the elements of the array. */ @@ -398,19 +399,16 @@ inline Allocated::Allocated(Allocated &&other) noexcept mapped_data(std::exchange(other.mapped_data, {})), coherent(std::exchange(other.coherent, {})), persistent(std::exchange(other.persistent, {})) -{ -} +{} template template inline Allocated::Allocated(const VmaAllocationCreateInfo &allocation_create_info, Args &&...args) : - ParentType{std::forward(args)...}, - allocation_create_info(allocation_create_info) + ParentType{std::forward(args)...}, allocation_create_info(allocation_create_info) {} template -inline Allocated::Allocated(HandleType handle, vkb::core::Device *device_) : - ParentType(handle, device_) +inline Allocated::Allocated(HandleType handle, vkb::core::Device *device_) : ParentType(handle, device_) {} template @@ -428,7 +426,8 @@ inline void Allocated::clear() } template -inline typename Allocated::BufferType Allocated::create_buffer(BufferCreateInfoType const &create_info, DeviceSizeType alignment) +inline typename Allocated::BufferType Allocated::create_buffer(BufferCreateInfoType const &create_info, + DeviceSizeType alignment) { if constexpr (bindingType == vkb::BindingType::Cpp) { @@ -449,24 +448,13 @@ inline vk::Buffer Allocated::create_buffer_impl(vk::Buf auto result = VK_SUCCESS; if (alignment == 0) { - result = vmaCreateBuffer( - get_memory_allocator(), - reinterpret_cast(&create_info), - &allocation_create_info, - reinterpret_cast(&buffer), - &allocation, - &allocation_info); + result = vmaCreateBuffer(get_memory_allocator(), reinterpret_cast(&create_info), &allocation_create_info, + reinterpret_cast(&buffer), &allocation, &allocation_info); } else { - result = vmaCreateBufferWithAlignment( - get_memory_allocator(), - reinterpret_cast(&create_info), - &allocation_create_info, - alignment, - reinterpret_cast(&buffer), - &allocation, - &allocation_info); + result = vmaCreateBufferWithAlignment(get_memory_allocator(), reinterpret_cast(&create_info), &allocation_create_info, + alignment, reinterpret_cast(&buffer), &allocation, &allocation_info); } if (result != VK_SUCCESS) @@ -514,12 +502,8 @@ inline vk::Image Allocated::create_image_impl(vk::Image } #endif - VkResult result = vmaCreateImage(get_memory_allocator(), - reinterpret_cast(&create_info), - &allocation_create_info, - reinterpret_cast(&image), - &allocation, - &allocation_info); + VkResult result = vmaCreateImage(get_memory_allocator(), reinterpret_cast(&create_info), &allocation_create_info, + reinterpret_cast(&image), &allocation, &allocation_info); if (result != VK_SUCCESS) { diff --git a/framework/core/buffer.h b/framework/core/buffer.h index 5bcd4439d8..d782dab1a9 100644 --- a/framework/core/buffer.h +++ b/framework/core/buffer.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors - * Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2019-2026, Arm Limited and Contributors + * Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -70,10 +70,8 @@ using BufferBuilderC = BufferBuilder; using BufferBuilderCpp = BufferBuilder; template <> -inline BufferBuilder::BufferBuilder(vk::DeviceSize size) : - ParentType(BufferCreateInfoType{.size = size}) -{ -} +inline BufferBuilder::BufferBuilder(vk::DeviceSize size) : ParentType(BufferCreateInfoType{.size = size}) +{} template <> inline BufferBuilder::BufferBuilder(VkDeviceSize size) : @@ -116,8 +114,7 @@ inline BufferBuilder &BufferBuilder::with_alignment(De /*=========================================================*/ template -class Buffer - : public vkb::allocated::Allocated::type> +class Buffer : public vkb::allocated::Allocated::type> { public: using BufferType = typename std::conditional::type; diff --git a/framework/core/command_buffer.h b/framework/core/command_buffer.h index ff014ecbe7..ccad23ec07 100644 --- a/framework/core/command_buffer.h +++ b/framework/core/command_buffer.h @@ -59,24 +59,22 @@ class CommandBuffer using CommandBufferType = typename std::conditional::type; using CommandBufferUsageFlagsType = typename std::conditional::type; - using DeviceSizeType = typename std::conditional::type; - using ImageBlitType = typename std::conditional::type; - using ImageCopyType = typename std::conditional::type; - using ImageLayoutType = typename std::conditional::type; - using ImageResolveType = typename std::conditional::type; - using IndexTypeType = typename std::conditional::type; - using PipelineStagFlagBitsType = - typename std::conditional::type; - using QueryControlFlagsType = typename std::conditional::type; - using Rect2DType = typename std::conditional::type; - using ResultType = typename std::conditional::type; - using SubpassContentsType = typename std::conditional::type; - using ViewportType = typename std::conditional::type; + using DeviceSizeType = typename std::conditional::type; + using ImageBlitType = typename std::conditional::type; + using ImageCopyType = typename std::conditional::type; + using ImageLayoutType = typename std::conditional::type; + using ImageResolveType = typename std::conditional::type; + using IndexTypeType = typename std::conditional::type; + using PipelineStagFlagBitsType = typename std::conditional::type; + using QueryControlFlagsType = typename std::conditional::type; + using Rect2DType = typename std::conditional::type; + using ResultType = typename std::conditional::type; + using SubpassContentsType = typename std::conditional::type; + using ViewportType = typename std::conditional::type; using BufferMemoryBarrierType = typename std::conditional::type; - using ColorBlendStateType = - typename std::conditional::type; + using ColorBlendStateType = typename std::conditional::type; using DepthStencilStateType = typename std::conditional::type; using FramebufferType = typename std::conditional::type; @@ -127,54 +125,59 @@ class CommandBuffer */ void begin(CommandBufferUsageFlagsType flags, const RenderPassType *render_pass, const FramebufferType *framebuffer, uint32_t subpass_index); - void begin_query(QueryPoolType const &query_pool, uint32_t query, QueryControlFlagsType flags); - void begin_render_pass(vkb::rendering::RenderTarget const &render_target, - std::vector const &load_store_infos, - std::vector const &clear_values, - std::vector>> const &subpasses, - SubpassContentsType contents = VK_SUBPASS_CONTENTS_INLINE); - void begin_render_pass(vkb::rendering::RenderTarget const &render_target, - RenderPassType const &render_pass, - FramebufferType const &framebuffer, - std::vector const &clear_values, - SubpassContentsType contents = vk::SubpassContents::eInline); - void bind_buffer(vkb::core::Buffer const &buffer, DeviceSizeType offset, DeviceSizeType range, uint32_t set, uint32_t binding, uint32_t array_element); - void bind_image(ImageViewType const &image_view, SamplerType const &sampler, uint32_t set, uint32_t binding, uint32_t array_element); - void bind_image(ImageViewType const &image_view, uint32_t set, uint32_t binding, uint32_t array_element); - void bind_index_buffer(vkb::core::Buffer const &buffer, DeviceSizeType offset, IndexTypeType index_type); - void bind_input(ImageViewType const &image_view, uint32_t set, uint32_t binding, uint32_t array_element); - void bind_lighting(vkb::rendering::LightingState &lighting_state, uint32_t set, uint32_t binding); - void bind_pipeline_layout(PipelineLayoutType &pipeline_layout); - void bind_vertex_buffers(uint32_t first_binding, - std::vector>> const &buffers, - std::vector const &offsets); - void blit_image(ImageType const &src_img, ImageType const &dst_img, std::vector const ®ions); - void buffer_memory_barrier(vkb::core::Buffer const &buffer, DeviceSizeType offset, DeviceSizeType size, BufferMemoryBarrierType const &memory_barrier); - void clear(ClearAttachmentType const &info, ClearRectType const &rect); - void copy_buffer(vkb::core::Buffer const &src_buffer, vkb::core::Buffer const &dst_buffer, DeviceSizeType size); - void copy_buffer_to_image(vkb::core::Buffer const &buffer, ImageType const &image, std::vector const ®ions); - void copy_image(ImageType const &src_img, ImageType const &dst_img, std::vector const ®ions); - void copy_image_to_buffer(ImageType const &image, - ImageLayoutType image_layout, - vkb::core::Buffer const &buffer, - std::vector const ®ions); - void dispatch(uint32_t group_count_x, uint32_t group_count_y, uint32_t group_count_z); - void dispatch_indirect(vkb::core::Buffer const &buffer, DeviceSizeType offset); - void draw(uint32_t vertex_count, uint32_t instance_count, uint32_t first_vertex, uint32_t first_instance); - void draw_indexed(uint32_t index_count, uint32_t instance_count, uint32_t first_index, int32_t vertex_offset, uint32_t first_instance); - void draw_indexed_indirect(vkb::core::Buffer const &buffer, DeviceSizeType offset, uint32_t draw_count, uint32_t stride); - void end(); - void end_query(QueryPoolType const &query_pool, uint32_t query); - void end_render_pass(); - void execute_commands(vkb::core::CommandBuffer &secondary_command_buffer); - void execute_commands(std::vector>> &secondary_command_buffers); + void begin_query(QueryPoolType const &query_pool, uint32_t query, QueryControlFlagsType flags); + void begin_render_pass(vkb::rendering::RenderTarget const &render_target, + std::vector const &load_store_infos, + std::vector const &clear_values, + std::vector>> const &subpasses, + SubpassContentsType contents = VK_SUBPASS_CONTENTS_INLINE); + void begin_render_pass(vkb::rendering::RenderTarget const &render_target, + RenderPassType const &render_pass, + FramebufferType const &framebuffer, + std::vector const &clear_values, + SubpassContentsType contents = vk::SubpassContents::eInline); + void bind_buffer( + vkb::core::Buffer const &buffer, DeviceSizeType offset, DeviceSizeType range, uint32_t set, uint32_t binding, uint32_t array_element); + void bind_image(ImageViewType const &image_view, SamplerType const &sampler, uint32_t set, uint32_t binding, uint32_t array_element); + void bind_image(ImageViewType const &image_view, uint32_t set, uint32_t binding, uint32_t array_element); + void bind_index_buffer(vkb::core::Buffer const &buffer, DeviceSizeType offset, IndexTypeType index_type); + void bind_input(ImageViewType const &image_view, uint32_t set, uint32_t binding, uint32_t array_element); + void bind_lighting(vkb::rendering::LightingState &lighting_state, uint32_t set, uint32_t binding); + void bind_pipeline_layout(PipelineLayoutType &pipeline_layout); + void bind_vertex_buffers(uint32_t first_binding, + std::vector>> const &buffers, + std::vector const &offsets); + void blit_image(ImageType const &src_img, ImageType const &dst_img, std::vector const ®ions); + void buffer_memory_barrier(vkb::core::Buffer const &buffer, + DeviceSizeType offset, + DeviceSizeType size, + BufferMemoryBarrierType const &memory_barrier); + void clear(ClearAttachmentType const &info, ClearRectType const &rect); + void copy_buffer(vkb::core::Buffer const &src_buffer, vkb::core::Buffer const &dst_buffer, DeviceSizeType size); + void copy_buffer_to_image(vkb::core::Buffer const &buffer, ImageType const &image, std::vector const ®ions); + void copy_image(ImageType const &src_img, ImageType const &dst_img, std::vector const ®ions); + void copy_image_to_buffer(ImageType const &image, + ImageLayoutType image_layout, + vkb::core::Buffer const &buffer, + std::vector const ®ions); + void dispatch(uint32_t group_count_x, uint32_t group_count_y, uint32_t group_count_z); + void dispatch_indirect(vkb::core::Buffer const &buffer, DeviceSizeType offset); + void draw(uint32_t vertex_count, uint32_t instance_count, uint32_t first_vertex, uint32_t first_instance); + void draw_indexed(uint32_t index_count, uint32_t instance_count, uint32_t first_index, int32_t vertex_offset, uint32_t first_instance); + void draw_indexed_indirect(vkb::core::Buffer const &buffer, DeviceSizeType offset, uint32_t draw_count, uint32_t stride); + void end(); + void end_query(QueryPoolType const &query_pool, uint32_t query); + void end_render_pass(); + void execute_commands(vkb::core::CommandBuffer &secondary_command_buffer); + void execute_commands(std::vector>> &secondary_command_buffers); CommandBufferLevelType get_level() const; RenderPassType &get_render_pass(vkb::rendering::RenderTarget const &render_target, std::vector const &load_store_infos, std::vector>> const &subpasses); void image_memory_barrier(ImageViewType const &image_view, ImageMemoryBarrierType const &memory_barrier) const; - void image_memory_barrier(vkb::rendering::RenderTarget &render_target, uint32_t view_index, ImageMemoryBarrierType const &memory_barrier) const; - void next_subpass(); + void + image_memory_barrier(vkb::rendering::RenderTarget &render_target, uint32_t view_index, ImageMemoryBarrierType const &memory_barrier) const; + void next_subpass(); /** * @brief Records byte data into the command buffer to be pushed as push constants to each draw call @@ -257,8 +260,8 @@ class CommandBuffer vkb::rendering::RenderTargetCpp const &render_target, std::vector const &load_store_infos, std::vector> const &subpasses); - void image_memory_barrier_impl(vkb::core::HPPImageView const &image_view, vkb::common::HPPImageMemoryBarrier const &memory_barrier) const; - vk::Result reset_impl(vkb::CommandBufferResetMode reset_mode); + void image_memory_barrier_impl(vkb::core::HPPImageView const &image_view, vkb::common::HPPImageMemoryBarrier const &memory_barrier) const; + vk::Result reset_impl(vkb::CommandBufferResetMode reset_mode); private: vkb::core::CommandPoolCpp &command_pool; @@ -294,7 +297,10 @@ namespace core { template inline vkb::core::CommandBuffer::CommandBuffer(vkb::core::CommandPool &command_pool_, CommandBufferLevelType level_) : - vkb::core::VulkanResource(nullptr, &command_pool_.get_device()), level(static_cast(level_)), command_pool(reinterpret_cast(command_pool_)), max_push_constants_size(command_pool_.get_device().get_gpu().get_properties().limits.maxPushConstantsSize) + vkb::core::VulkanResource(nullptr, &command_pool_.get_device()), + level(static_cast(level_)), + command_pool(reinterpret_cast(command_pool_)), + max_push_constants_size(command_pool_.get_device().get_gpu().get_properties().limits.maxPushConstantsSize) { vk::CommandBufferAllocateInfo allocate_info{.commandPool = command_pool.get_handle(), .level = level, .commandBufferCount = 1}; @@ -312,8 +318,7 @@ inline CommandBuffer::~CommandBuffer() } template -inline void CommandBuffer::begin(CommandBufferUsageFlagsType flags, - vkb::core::CommandBuffer *primary_cmd_buf) +inline void CommandBuffer::begin(CommandBufferUsageFlagsType flags, vkb::core::CommandBuffer *primary_cmd_buf) { if constexpr (bindingType == vkb::BindingType::Cpp) { @@ -332,7 +337,8 @@ inline void CommandBuffer::begin_impl(vk::CommandBufferUsageFlags f { assert(primary_cmd_buf && "A primary command buffer pointer must be provided when calling begin from a secondary one"); - return begin_impl(flags, primary_cmd_buf->current_render_pass, primary_cmd_buf->current_framebuffer, primary_cmd_buf->pipeline_state.get_subpass_index()); + return begin_impl(flags, primary_cmd_buf->current_render_pass, primary_cmd_buf->current_framebuffer, + primary_cmd_buf->pipeline_state.get_subpass_index()); } else { @@ -352,10 +358,8 @@ inline void CommandBuffer::begin(CommandBufferUsageFlagsType flags, } else { - begin_impl(static_cast(flags), - reinterpret_cast(render_pass), - reinterpret_cast(framebuffer), - subpass_index); + begin_impl(static_cast(flags), reinterpret_cast(render_pass), + reinterpret_cast(framebuffer), subpass_index); } } @@ -438,8 +442,7 @@ inline void CommandBuffer::begin_render_pass(vkb::rendering::Render begin_render_pass_impl(reinterpret_cast(render_target), reinterpret_cast(render_pass), reinterpret_cast(framebuffer), - reinterpret_cast const &>(clear_values), - static_cast(contents)); + reinterpret_cast const &>(clear_values), static_cast(contents)); } } @@ -493,14 +496,14 @@ inline void CommandBuffer::bind_buffer( } else { - resource_binding_state.bind_buffer( - reinterpret_cast const &>(buffer), offset, range, set, binding, array_element); + resource_binding_state.bind_buffer(reinterpret_cast const &>(buffer), offset, range, set, binding, + array_element); } } template -inline void CommandBuffer::bind_image( - ImageViewType const &image_view, SamplerType const &sampler, uint32_t set, uint32_t binding, uint32_t array_element) +inline void + CommandBuffer::bind_image(ImageViewType const &image_view, SamplerType const &sampler, uint32_t set, uint32_t binding, uint32_t array_element) { if constexpr (bindingType == vkb::BindingType::Cpp) { @@ -509,10 +512,7 @@ inline void CommandBuffer::bind_image( else { resource_binding_state.bind_image(reinterpret_cast(image_view), - reinterpret_cast(sampler), - set, - binding, - array_element); + reinterpret_cast(sampler), set, binding, array_element); } } @@ -589,8 +589,7 @@ inline void CommandBuffer::bind_vertex_buffers(uint32_t } else { - bind_vertex_buffers_impl(first_binding, - reinterpret_cast> const &>(buffers), + bind_vertex_buffers_impl(first_binding, reinterpret_cast> const &>(buffers), reinterpret_cast const &>(offsets)); } } @@ -610,20 +609,13 @@ inline void CommandBuffer::blit_image(ImageType const &src_img, Ima { if constexpr (bindingType == vkb::BindingType::Cpp) { - this->get_resource().blitImage(src_img.get_handle(), - vk::ImageLayout::eTransferSrcOptimal, - dst_img.get_handle(), - vk::ImageLayout::eTransferDstOptimal, - regions, - vk::Filter::eNearest); + this->get_resource().blitImage(src_img.get_handle(), vk::ImageLayout::eTransferSrcOptimal, dst_img.get_handle(), vk::ImageLayout::eTransferDstOptimal, + regions, vk::Filter::eNearest); } else { - this->get_resource().blitImage(src_img.get_resource(), - vk::ImageLayout::eTransferSrcOptimal, - dst_img.get_resource(), - vk::ImageLayout::eTransferDstOptimal, - reinterpret_cast const &>(regions), + this->get_resource().blitImage(src_img.get_resource(), vk::ImageLayout::eTransferSrcOptimal, dst_img.get_resource(), + vk::ImageLayout::eTransferDstOptimal, reinterpret_cast const &>(regions), vk::Filter::eNearest); } } @@ -640,10 +632,8 @@ inline void CommandBuffer::buffer_memory_barrier(vkb::core::Buffer< } else { - buffer_memory_barrier_impl(reinterpret_cast(buffer), - static_cast(offset), - static_cast(size), - reinterpret_cast(memory_barrier)); + buffer_memory_barrier_impl(reinterpret_cast(buffer), static_cast(offset), + static_cast(size), reinterpret_cast(memory_barrier)); } } @@ -686,15 +676,13 @@ inline void CommandBuffer::copy_buffer(vkb::core::Buffer(src_buffer), - reinterpret_cast(dst_buffer), + copy_buffer_impl(reinterpret_cast(src_buffer), reinterpret_cast(dst_buffer), static_cast(size)); } } template -inline void - CommandBuffer::copy_buffer_impl(vkb::core::BufferCpp const &src_buffer, vkb::core::BufferCpp const &dst_buffer, vk::DeviceSize size) +inline void CommandBuffer::copy_buffer_impl(vkb::core::BufferCpp const &src_buffer, vkb::core::BufferCpp const &dst_buffer, vk::DeviceSize size) { vk::BufferCopy copy_region{.size = size}; this->get_resource().copyBuffer(src_buffer.get_handle(), dst_buffer.get_handle(), copy_region); @@ -711,9 +699,7 @@ inline void CommandBuffer::copy_buffer_to_image(vkb::core::Bufferget_resource().copyBufferToImage(buffer.get_resource(), - image.get_resource(), - vk::ImageLayout::eTransferDstOptimal, + this->get_resource().copyBufferToImage(buffer.get_resource(), image.get_resource(), vk::ImageLayout::eTransferDstOptimal, reinterpret_cast const &>(regions)); } } @@ -723,15 +709,13 @@ inline void CommandBuffer::copy_image(ImageType const &src_img, Ima { if constexpr (bindingType == vkb::BindingType::Cpp) { - this->get_resource().copyImage(src_img.get_handle(), vk::ImageLayout::eTransferSrcOptimal, dst_img.get_handle(), vk::ImageLayout::eTransferDstOptimal, regions); + this->get_resource().copyImage(src_img.get_handle(), vk::ImageLayout::eTransferSrcOptimal, dst_img.get_handle(), vk::ImageLayout::eTransferDstOptimal, + regions); } else { - this->get_resource().copyImage(src_img.get_resource(), - vk::ImageLayout::eTransferSrcOptimal, - dst_img.get_resource(), - vk::ImageLayout::eTransferDstOptimal, - reinterpret_cast const &>(regions)); + this->get_resource().copyImage(src_img.get_resource(), vk::ImageLayout::eTransferSrcOptimal, dst_img.get_resource(), + vk::ImageLayout::eTransferDstOptimal, reinterpret_cast const &>(regions)); } } @@ -747,9 +731,7 @@ inline void CommandBuffer::copy_image_to_buffer(ImageType const } else { - this->get_resource().copyImageToBuffer(image.get_resource(), - static_cast(image_layout), - buffer.get_resource(), + this->get_resource().copyImageToBuffer(image.get_resource(), static_cast(image_layout), buffer.get_resource(), reinterpret_cast const &>(regions)); } } @@ -791,7 +773,8 @@ inline void CommandBuffer::draw_indexed( } template -inline void CommandBuffer::draw_indexed_indirect(vkb::core::Buffer const &buffer, DeviceSizeType offset, uint32_t draw_count, uint32_t stride) +inline void + CommandBuffer::draw_indexed_indirect(vkb::core::Buffer const &buffer, DeviceSizeType offset, uint32_t draw_count, uint32_t stride) { flush(vk::PipelineBindPoint::eGraphics); if constexpr (bindingType == vkb::BindingType::Cpp) @@ -862,12 +845,11 @@ inline void CommandBuffer::execute_commands(std::vector -inline void CommandBuffer::execute_commands_impl(std::vector>> &secondary_command_buffers) +inline void + CommandBuffer::execute_commands_impl(std::vector>> &secondary_command_buffers) { std::vector sec_cmd_buf_handles(secondary_command_buffers.size(), nullptr); - std::transform(secondary_command_buffers.begin(), - secondary_command_buffers.end(), - sec_cmd_buf_handles.begin(), + std::transform(secondary_command_buffers.begin(), secondary_command_buffers.end(), sec_cmd_buf_handles.begin(), [](auto const &sec_cmd_buf) { return sec_cmd_buf->get_handle(); }); this->get_resource().executeCommands(sec_cmd_buf_handles); } @@ -884,20 +866,18 @@ inline typename vkb::core::CommandBuffer::RenderPassType & } else { - return reinterpret_cast( - get_render_pass_impl(reinterpret_cast(this->get_device()), - reinterpret_cast(render_target), - reinterpret_cast const &>(load_store_infos), - reinterpret_cast> const &>(subpasses))); + return reinterpret_cast(get_render_pass_impl( + reinterpret_cast(this->get_device()), reinterpret_cast(render_target), + reinterpret_cast const &>(load_store_infos), + reinterpret_cast> const &>(subpasses))); } } template -inline vkb::core::HPPRenderPass & - CommandBuffer::get_render_pass_impl(vkb::core::DeviceCpp &device, - vkb::rendering::RenderTargetCpp const &render_target, - std::vector const &load_store_infos, - std::vector> const &subpasses) +inline vkb::core::HPPRenderPass &CommandBuffer::get_render_pass_impl(vkb::core::DeviceCpp &device, + vkb::rendering::RenderTargetCpp const &render_target, + std::vector const &load_store_infos, + std::vector> const &subpasses) { // Create render pass assert(subpasses.size() > 0 && "Cannot create a render pass without any subpass"); @@ -921,7 +901,9 @@ inline vkb::core::HPPRenderPass & } template -inline void CommandBuffer::image_memory_barrier(vkb::rendering::RenderTarget &render_target, uint32_t view_index, ImageMemoryBarrierType const &memory_barrier) const +inline void CommandBuffer::image_memory_barrier(vkb::rendering::RenderTarget &render_target, + uint32_t view_index, + ImageMemoryBarrierType const &memory_barrier) const { auto const &image_view = render_target.get_views()[view_index]; @@ -1081,16 +1063,13 @@ inline void CommandBuffer::resolve_image(ImageType const &src_img, { if constexpr (bindingType == vkb::BindingType::Cpp) { - this->get_resource().resolveImage( - src_img.get_handle(), vk::ImageLayout::eTransferSrcOptimal, dst_img.get_handle(), vk::ImageLayout::eTransferDstOptimal, regions); + this->get_resource().resolveImage(src_img.get_handle(), vk::ImageLayout::eTransferSrcOptimal, dst_img.get_handle(), + vk::ImageLayout::eTransferDstOptimal, regions); } else { - this->get_resource().resolveImage(src_img.get_resource(), - vk::ImageLayout::eTransferSrcOptimal, - dst_img.get_resource(), - vk::ImageLayout::eTransferDstOptimal, - reinterpret_cast const &>(regions)); + this->get_resource().resolveImage(src_img.get_resource(), vk::ImageLayout::eTransferSrcOptimal, dst_img.get_resource(), + vk::ImageLayout::eTransferDstOptimal, reinterpret_cast const &>(regions)); } } @@ -1432,7 +1411,9 @@ inline void CommandBuffer::flush_descriptor_state_impl(vk::Pipeline image_info.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; break; case vk::DescriptorType::eInputAttachment: - image_info.imageLayout = vkb::common::is_depth_format(image_view->get_format()) ? vk::ImageLayout::eDepthStencilReadOnlyOptimal : vk::ImageLayout::eShaderReadOnlyOptimal; + image_info.imageLayout = vkb::common::is_depth_format(image_view->get_format()) ? + vk::ImageLayout::eDepthStencilReadOnlyOptimal : + vk::ImageLayout::eShaderReadOnlyOptimal; break; case vk::DescriptorType::eStorageImage: image_info.imageLayout = vk::ImageLayout::eGeneral; @@ -1455,7 +1436,8 @@ inline void CommandBuffer::flush_descriptor_state_impl(vk::Pipeline descriptor_set_layout, buffer_infos, image_infos, update_after_bind, command_pool.get_thread_index()); // Bind descriptor set - this->get_resource().bindDescriptorSets(pipeline_bind_point, pipeline_layout.get_handle(), descriptor_set_id, descriptor_set_handle, dynamic_offsets); + this->get_resource().bindDescriptorSets(pipeline_bind_point, pipeline_layout.get_handle(), descriptor_set_id, descriptor_set_handle, + dynamic_offsets); } } } @@ -1520,11 +1502,10 @@ inline bool CommandBuffer::is_render_size_optimal(const vk::Extent2 { auto render_area_granularity = current_render_pass->get_render_area_granularity(); - return ((render_area.offset.x % render_area_granularity.width == 0) && (render_area.offset.y % render_area_granularity.height == 0) && - ((render_area.extent.width % render_area_granularity.width == 0) || - (render_area.offset.x + render_area.extent.width == framebuffer_extent.width)) && - ((render_area.extent.height % render_area_granularity.height == 0) || - (render_area.offset.y + render_area.extent.height == framebuffer_extent.height))); + return ( + (render_area.offset.x % render_area_granularity.width == 0) && (render_area.offset.y % render_area_granularity.height == 0) && + ((render_area.extent.width % render_area_granularity.width == 0) || (render_area.offset.x + render_area.extent.width == framebuffer_extent.width)) && + ((render_area.extent.height % render_area_granularity.height == 0) || (render_area.offset.y + render_area.extent.height == framebuffer_extent.height))); } } // namespace core } // namespace vkb diff --git a/framework/core/command_pool.h b/framework/core/command_pool.h index 9620586754..a504dc57e8 100644 --- a/framework/core/command_pool.h +++ b/framework/core/command_pool.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors - * Copyright (c) 2024-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2019-2026, Arm Limited and Contributors + * Copyright (c) 2024-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -75,14 +75,15 @@ class CommandPool : private vkb::core::CommandPoolBase CommandPool &operator=(CommandPool &&other) = default; ~CommandPool() = default; - vkb::core::Device &get_device(); - CommandPoolType get_handle() const; - uint32_t get_queue_family_index() const; - vkb::rendering::RenderFrame *get_render_frame(); - vkb::CommandBufferResetMode get_reset_mode() const; - size_t get_thread_index() const; - std::shared_ptr> request_command_buffer(CommandBufferLevelType level = DefaultCommandBufferLevelValue::value); - void reset_pool(); + vkb::core::Device &get_device(); + CommandPoolType get_handle() const; + uint32_t get_queue_family_index() const; + vkb::rendering::RenderFrame *get_render_frame(); + vkb::CommandBufferResetMode get_reset_mode() const; + size_t get_thread_index() const; + std::shared_ptr> + request_command_buffer(CommandBufferLevelType level = DefaultCommandBufferLevelValue::value); + void reset_pool(); }; using CommandPoolC = CommandPool; diff --git a/framework/core/debug.cpp b/framework/core/debug.cpp index 0ec0283516..53f4fc46aa 100644 --- a/framework/core/debug.cpp +++ b/framework/core/debug.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, Arm Limited and Contributors +/* Copyright (c) 2021-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -25,8 +25,7 @@ namespace vkb { -void DebugUtilsExtDebugUtils::set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, - const char *name) const +void DebugUtilsExtDebugUtils::set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, const char *name) const { VkDebugUtilsObjectNameInfoEXT name_info{}; name_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT; @@ -38,8 +37,8 @@ void DebugUtilsExtDebugUtils::set_debug_name(VkDevice device, VkObjectType objec vkSetDebugUtilsObjectNameEXT(device, &name_info); } -void DebugUtilsExtDebugUtils::set_debug_tag(VkDevice device, VkObjectType object_type, uint64_t object_handle, - uint64_t tag_name, const void *tag_data, size_t tag_data_size) const +void DebugUtilsExtDebugUtils::set_debug_tag( + VkDevice device, VkObjectType object_type, uint64_t object_handle, uint64_t tag_name, const void *tag_data, size_t tag_data_size) const { VkDebugUtilsObjectTagInfoEXT tag_info{}; tag_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_TAG_INFO_EXT; @@ -53,8 +52,7 @@ void DebugUtilsExtDebugUtils::set_debug_tag(VkDevice device, VkObjectType object vkSetDebugUtilsObjectTagEXT(device, &tag_info); } -void DebugUtilsExtDebugUtils::cmd_begin_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) const +void DebugUtilsExtDebugUtils::cmd_begin_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color) const { VkDebugUtilsLabelEXT label_info{}; label_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT; @@ -71,8 +69,7 @@ void DebugUtilsExtDebugUtils::cmd_end_label(VkCommandBuffer command_buffer) cons vkCmdEndDebugUtilsLabelEXT(command_buffer); } -void DebugUtilsExtDebugUtils::cmd_insert_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) const +void DebugUtilsExtDebugUtils::cmd_insert_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color) const { VkDebugUtilsLabelEXT label_info{}; label_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT; @@ -119,8 +116,7 @@ static const std::unordered_map VK_OBJ {VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_EXT}, }; -void DebugMarkerExtDebugUtils::set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, - const char *name) const +void DebugMarkerExtDebugUtils::set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, const char *name) const { VkDebugMarkerObjectNameInfoEXT name_info{}; name_info.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT; @@ -132,8 +128,8 @@ void DebugMarkerExtDebugUtils::set_debug_name(VkDevice device, VkObjectType obje vkDebugMarkerSetObjectNameEXT(device, &name_info); } -void DebugMarkerExtDebugUtils::set_debug_tag(VkDevice device, VkObjectType object_type, uint64_t object_handle, - uint64_t tag_name, const void *tag_data, size_t tag_data_size) const +void DebugMarkerExtDebugUtils::set_debug_tag( + VkDevice device, VkObjectType object_type, uint64_t object_handle, uint64_t tag_name, const void *tag_data, size_t tag_data_size) const { VkDebugMarkerObjectTagInfoEXT tag_info{}; tag_info.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT; @@ -147,8 +143,7 @@ void DebugMarkerExtDebugUtils::set_debug_tag(VkDevice device, VkObjectType objec vkDebugMarkerSetObjectTagEXT(device, &tag_info); } -void DebugMarkerExtDebugUtils::cmd_begin_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) const +void DebugMarkerExtDebugUtils::cmd_begin_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color) const { VkDebugMarkerMarkerInfoEXT marker_info{}; marker_info.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT; @@ -165,8 +160,7 @@ void DebugMarkerExtDebugUtils::cmd_end_label(VkCommandBuffer command_buffer) con vkCmdDebugMarkerEndEXT(command_buffer); } -void DebugMarkerExtDebugUtils::cmd_insert_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) const +void DebugMarkerExtDebugUtils::cmd_insert_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color) const { VkDebugMarkerMarkerInfoEXT marker_info{}; marker_info.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT; @@ -177,10 +171,8 @@ void DebugMarkerExtDebugUtils::cmd_insert_label(VkCommandBuffer command_buffer, vkCmdDebugMarkerInsertEXT(command_buffer, &marker_info); } -ScopedDebugLabel::ScopedDebugLabel(const DebugUtils &debug_utils, VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) : - debug_utils{&debug_utils}, - command_buffer{VK_NULL_HANDLE} +ScopedDebugLabel::ScopedDebugLabel(const DebugUtils &debug_utils, VkCommandBuffer command_buffer, const char *name, glm::vec4 color) : + debug_utils{&debug_utils}, command_buffer{VK_NULL_HANDLE} { if (name && *name != '\0') { @@ -193,8 +185,7 @@ ScopedDebugLabel::ScopedDebugLabel(const DebugUtils &debug_utils, VkCommandBuffe ScopedDebugLabel::ScopedDebugLabel(const vkb::core::CommandBufferC &command_buffer, const char *name, glm::vec4 color) : ScopedDebugLabel{command_buffer.get_device().get_debug_utils(), command_buffer.get_handle(), name, color} -{ -} +{} ScopedDebugLabel::~ScopedDebugLabel() { diff --git a/framework/core/debug.h b/framework/core/debug.h index fdf6cd1e40..60f8b59b0b 100644 --- a/framework/core/debug.h +++ b/framework/core/debug.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, Arm Limited and Contributors +/* Copyright (c) 2021-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -41,20 +41,18 @@ class DebugUtils /** * @brief Sets the debug name for a Vulkan object. */ - virtual void set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, - const char *name) const = 0; + virtual void set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, const char *name) const = 0; /** * @brief Tags the given Vulkan object with some data. */ - virtual void set_debug_tag(VkDevice device, VkObjectType object_type, uint64_t object_handle, - uint64_t tag_name, const void *tag_data, size_t tag_data_size) const = 0; + virtual void set_debug_tag( + VkDevice device, VkObjectType object_type, uint64_t object_handle, uint64_t tag_name, const void *tag_data, size_t tag_data_size) const = 0; /** * @brief Inserts a command to begin a new debug label/marker scope. */ - virtual void cmd_begin_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color = {}) const = 0; + virtual void cmd_begin_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color = {}) const = 0; /** * @brief Inserts a command to end the current debug label/marker scope. @@ -64,8 +62,7 @@ class DebugUtils /** * @brief Inserts a (non-scoped) debug label/marker in the command buffer. */ - virtual void cmd_insert_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color = {}) const = 0; + virtual void cmd_insert_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color = {}) const = 0; }; /** @@ -76,19 +73,16 @@ class DebugUtilsExtDebugUtils final : public DebugUtils public: ~DebugUtilsExtDebugUtils() override = default; - void set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, - const char *name) const override; + void set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, const char *name) const override; - void set_debug_tag(VkDevice device, VkObjectType object_type, uint64_t object_handle, - uint64_t tag_name, const void *tag_data, size_t tag_data_size) const override; + void set_debug_tag( + VkDevice device, VkObjectType object_type, uint64_t object_handle, uint64_t tag_name, const void *tag_data, size_t tag_data_size) const override; - void cmd_begin_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) const override; + void cmd_begin_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color) const override; void cmd_end_label(VkCommandBuffer command_buffer) const override; - void cmd_insert_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) const override; + void cmd_insert_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color) const override; }; /** @@ -99,19 +93,16 @@ class DebugMarkerExtDebugUtils final : public DebugUtils public: ~DebugMarkerExtDebugUtils() override = default; - void set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, - const char *name) const override; + void set_debug_name(VkDevice device, VkObjectType object_type, uint64_t object_handle, const char *name) const override; - void set_debug_tag(VkDevice device, VkObjectType object_type, uint64_t object_handle, - uint64_t tag_name, const void *tag_data, size_t tag_data_size) const override; + void set_debug_tag( + VkDevice device, VkObjectType object_type, uint64_t object_handle, uint64_t tag_name, const void *tag_data, size_t tag_data_size) const override; - void cmd_begin_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) const override; + void cmd_begin_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color) const override; void cmd_end_label(VkCommandBuffer command_buffer) const override; - void cmd_insert_label(VkCommandBuffer command_buffer, - const char *name, glm::vec4 color) const override; + void cmd_insert_label(VkCommandBuffer command_buffer, const char *name, glm::vec4 color) const override; }; /** @@ -125,19 +116,16 @@ class DummyDebugUtils final : public DebugUtils inline void set_debug_name(VkDevice, VkObjectType, uint64_t, const char *) const override {} - inline void set_debug_tag(VkDevice, VkObjectType, uint64_t, - uint64_t, const void *, size_t) const override + inline void set_debug_tag(VkDevice, VkObjectType, uint64_t, uint64_t, const void *, size_t) const override {} - inline void cmd_begin_label(VkCommandBuffer, - const char *, glm::vec4) const override + inline void cmd_begin_label(VkCommandBuffer, const char *, glm::vec4) const override {} inline void cmd_end_label(VkCommandBuffer) const override {} - inline void cmd_insert_label(VkCommandBuffer, - const char *, glm::vec4) const override + inline void cmd_insert_label(VkCommandBuffer, const char *, glm::vec4) const override {} }; @@ -150,8 +138,7 @@ class DummyDebugUtils final : public DebugUtils class ScopedDebugLabel final { public: - ScopedDebugLabel(const DebugUtils &debug_utils, VkCommandBuffer command_buffer, - const char *name, glm::vec4 color = {}); + ScopedDebugLabel(const DebugUtils &debug_utils, VkCommandBuffer command_buffer, const char *name, glm::vec4 color = {}); ScopedDebugLabel(const vkb::core::CommandBufferC &command_buffer, const char *name, glm::vec4 color = {}); diff --git a/framework/core/descriptor_pool.cpp b/framework/core/descriptor_pool.cpp index ee5b7d4ea8..7bfa85bafa 100644 --- a/framework/core/descriptor_pool.cpp +++ b/framework/core/descriptor_pool.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -22,11 +22,8 @@ namespace vkb { -DescriptorPool::DescriptorPool(vkb::core::DeviceC &device, - const DescriptorSetLayout &descriptor_set_layout, - uint32_t pool_size) : - device{device}, - descriptor_set_layout{&descriptor_set_layout} +DescriptorPool::DescriptorPool(vkb::core::DeviceC &device, const DescriptorSetLayout &descriptor_set_layout, uint32_t pool_size) : + device{device}, descriptor_set_layout{&descriptor_set_layout} { const auto &bindings = descriptor_set_layout.get_bindings(); diff --git a/framework/core/descriptor_pool.h b/framework/core/descriptor_pool.h index 8e252aa3f1..736d52ce19 100644 --- a/framework/core/descriptor_pool.h +++ b/framework/core/descriptor_pool.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -41,9 +41,7 @@ class DescriptorPool public: static const uint32_t MAX_SETS_PER_POOL = 16; - DescriptorPool(vkb::core::DeviceC &device, - const DescriptorSetLayout &descriptor_set_layout, - uint32_t pool_size = MAX_SETS_PER_POOL); + DescriptorPool(vkb::core::DeviceC &device, const DescriptorSetLayout &descriptor_set_layout, uint32_t pool_size = MAX_SETS_PER_POOL); DescriptorPool(const DescriptorPool &) = delete; diff --git a/framework/core/descriptor_set.cpp b/framework/core/descriptor_set.cpp index 356f5379cf..79555607bc 100644 --- a/framework/core/descriptor_set.cpp +++ b/framework/core/descriptor_set.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -82,14 +82,20 @@ void DescriptorSet::prepare() size_t buffer_range_limit = static_cast(buffer_info.range); - if ((binding_info->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || binding_info->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) && buffer_range_limit > uniform_buffer_range_limit) + if ((binding_info->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || + binding_info->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) && + buffer_range_limit > uniform_buffer_range_limit) { - LOGE("Set {} binding {} cannot be updated: buffer size {} exceeds the uniform buffer range limit {}", descriptor_set_layout.get_index(), binding_index, buffer_info.range, uniform_buffer_range_limit); + LOGE("Set {} binding {} cannot be updated: buffer size {} exceeds the uniform buffer range limit {}", descriptor_set_layout.get_index(), + binding_index, buffer_info.range, uniform_buffer_range_limit); buffer_range_limit = uniform_buffer_range_limit; } - else if ((binding_info->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER || binding_info->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) && buffer_range_limit > storage_buffer_range_limit) + else if ((binding_info->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER || + binding_info->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) && + buffer_range_limit > storage_buffer_range_limit) { - LOGE("Set {} binding {} cannot be updated: buffer size {} exceeds the storage buffer range limit {}", descriptor_set_layout.get_index(), binding_index, buffer_info.range, storage_buffer_range_limit); + LOGE("Set {} binding {} cannot be updated: buffer size {} exceeds the storage buffer range limit {}", descriptor_set_layout.get_index(), + binding_index, buffer_info.range, storage_buffer_range_limit); buffer_range_limit = storage_buffer_range_limit; } @@ -196,11 +202,7 @@ void DescriptorSet::update(const std::vector &bindings_to_update) // Perform the Vulkan call to update the DescriptorSet by executing the write operations if (!write_operations.empty()) { - vkUpdateDescriptorSets(device.get_handle(), - to_u32(write_operations.size()), - write_operations.data(), - 0, - nullptr); + vkUpdateDescriptorSets(device.get_handle(), to_u32(write_operations.size()), write_operations.data(), 0, nullptr); } // Store the bindings from the write operations that were executed by vkUpdateDescriptorSets (and their hash) @@ -213,11 +215,7 @@ void DescriptorSet::update(const std::vector &bindings_to_update) void DescriptorSet::apply_writes() const { - vkUpdateDescriptorSets(device.get_handle(), - to_u32(write_descriptor_sets.size()), - write_descriptor_sets.data(), - 0, - nullptr); + vkUpdateDescriptorSets(device.get_handle(), to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } DescriptorSet::DescriptorSet(DescriptorSet &&other) : diff --git a/framework/core/descriptor_set.h b/framework/core/descriptor_set.h index 4f8c935717..26466f125e 100644 --- a/framework/core/descriptor_set.h +++ b/framework/core/descriptor_set.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -73,8 +73,7 @@ class DescriptorSet * @param new_buffer_infos A map of buffer descriptors and their respective bindings * @param new_image_infos A map of image descriptors and their respective bindings */ - void reset(const BindingMap &new_buffer_infos = {}, - const BindingMap &new_image_infos = {}); + void reset(const BindingMap &new_buffer_infos = {}, const BindingMap &new_image_infos = {}); /** * @brief Updates the contents of the DescriptorSet by performing the write operations diff --git a/framework/core/descriptor_set_layout.cpp b/framework/core/descriptor_set_layout.cpp index eb67c0b76a..0f716d9a5e 100644 --- a/framework/core/descriptor_set_layout.cpp +++ b/framework/core/descriptor_set_layout.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -100,9 +100,7 @@ DescriptorSetLayout::DescriptorSetLayout(vkb::core::DeviceC &devi const uint32_t set_index, const std::vector &shader_modules, const std::vector &resource_set) : - device{device}, - set_index{set_index}, - shader_modules{shader_modules} + device{device}, set_index{set_index}, shader_modules{shader_modules} { // NOTE: `shader_modules` is passed in mainly for hashing their handles in `request_resource`. // This way, different pipelines (with different shaders / shader variants) will get @@ -111,9 +109,7 @@ DescriptorSetLayout::DescriptorSetLayout(vkb::core::DeviceC &devi for (auto &resource : resource_set) { // Skip shader resources whitout a binding point - if (resource.type == ShaderResourceType::Input || - resource.type == ShaderResourceType::Output || - resource.type == ShaderResourceType::PushConstant || + if (resource.type == ShaderResourceType::Input || resource.type == ShaderResourceType::Output || resource.type == ShaderResourceType::PushConstant || resource.type == ShaderResourceType::SpecializationConstant) { continue; @@ -159,12 +155,12 @@ DescriptorSetLayout::DescriptorSetLayout(vkb::core::DeviceC &devi // Handle update-after-bind extensions VkDescriptorSetLayoutBindingFlagsCreateInfoEXT binding_flags_create_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO_EXT}; - if (std::ranges::find_if(resource_set, - [](const ShaderResource &shader_resource) { return shader_resource.mode == ShaderResourceMode::UpdateAfterBind; }) != resource_set.end()) + if (std::ranges::find_if(resource_set, [](const ShaderResource &shader_resource) { return shader_resource.mode == ShaderResourceMode::UpdateAfterBind; }) != + resource_set.end()) { // Spec states you can't have ANY dynamic resources if you have one of the bindings set to update-after-bind - if (std::ranges::find_if(resource_set, - [](const ShaderResource &shader_resource) { return shader_resource.mode == ShaderResourceMode::Dynamic; }) != resource_set.end()) + if (std::ranges::find_if(resource_set, [](const ShaderResource &shader_resource) { return shader_resource.mode == ShaderResourceMode::Dynamic; }) != + resource_set.end()) { throw std::runtime_error("Cannot create descriptor set layout, dynamic resources are not allowed if at least one resource is update-after-bind."); } @@ -178,7 +174,9 @@ DescriptorSetLayout::DescriptorSetLayout(vkb::core::DeviceC &devi binding_flags_create_info.pBindingFlags = binding_flags.data(); create_info.pNext = &binding_flags_create_info; - create_info.flags |= std::ranges::find(binding_flags, VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT) != binding_flags.end() ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT : 0; + create_info.flags |= std::ranges::find(binding_flags, VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT) != binding_flags.end() ? + VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT : + 0; } // Create the Vulkan descriptor set layout handle diff --git a/framework/core/device.h b/framework/core/device.h index 0d127d9853..5968301a13 100644 --- a/framework/core/device.h +++ b/framework/core/device.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2025-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -44,31 +44,31 @@ using CommandPoolC = CommandPool; using CommandPoolCpp = CommandPool; template -class Device - : public vkb::core::VulkanResource::type> +class Device : public vkb::core::VulkanResource::type> { public: - using Bool32Type = typename std::conditional::type; - using BufferCopyType = typename std::conditional::type; - using CommandBufferLevelType = typename std::conditional::type; - using CommandBufferType = typename std::conditional::type; - using CommandPoolCreateFlagsType = typename std::conditional::type; - using CommandPoolType = typename std::conditional::type; - using DeviceMemoryType = typename std::conditional::type; - using DeviceType = typename std::conditional::type; - using Extent2DType = typename std::conditional::type; - using FenceType = typename std::conditional::type; - using FormatType = typename std::conditional::type; - using ImageType = typename std::conditional::type; - using ImageUsageFlagsType = typename std::conditional::type; - using MemoryPropertyFlagsType = typename std::conditional::type; - using QueueFamilyPropertiesType = typename std::conditional::type; - using QueueFlagBitsType = typename std::conditional::type; - using QueueFlagsType = typename std::conditional::type; - using QueueType = typename std::conditional::type; - using ResultType = typename std::conditional::type; - using SemaphoreType = typename std::conditional::type; - using SurfaceType = typename std::conditional::type; + using Bool32Type = typename std::conditional::type; + using BufferCopyType = typename std::conditional::type; + using CommandBufferLevelType = typename std::conditional::type; + using CommandBufferType = typename std::conditional::type; + using CommandPoolCreateFlagsType = + typename std::conditional::type; + using CommandPoolType = typename std::conditional::type; + using DeviceMemoryType = typename std::conditional::type; + using DeviceType = typename std::conditional::type; + using Extent2DType = typename std::conditional::type; + using FenceType = typename std::conditional::type; + using FormatType = typename std::conditional::type; + using ImageType = typename std::conditional::type; + using ImageUsageFlagsType = typename std::conditional::type; + using MemoryPropertyFlagsType = typename std::conditional::type; + using QueueFamilyPropertiesType = typename std::conditional::type; + using QueueFlagBitsType = typename std::conditional::type; + using QueueFlagsType = typename std::conditional::type; + using QueueType = typename std::conditional::type; + using ResultType = typename std::conditional::type; + using SemaphoreType = typename std::conditional::type; + using SurfaceType = typename std::conditional::type; using DebugUtilsType = typename std::conditional::type; using FencePoolType = typename std::conditional::type; @@ -105,16 +105,18 @@ class Device Device &operator=(const Device &) = delete; Device &operator=(Device &&) = delete; - void add_queue(size_t global_index, uint32_t family_index, QueueFamilyPropertiesType const &properties, Bool32Type can_present); - void copy_buffer( - vkb::core::Buffer const &src, vkb::core::Buffer &dst, QueueType queue, BufferCopyType const *copy_region = nullptr); - CommandBufferType create_command_buffer(CommandBufferLevelType level, bool begin = false) const; - CommandPoolType create_command_pool(uint32_t queue_index, CommandPoolCreateFlagsType flags = 0); - std::pair create_image( - FormatType format, Extent2DType const &extent, uint32_t mip_levels, ImageUsageFlagsType usage, MemoryPropertyFlagsType properties) const; - void create_internal_command_pool(); - void create_internal_fence_pool(); - void flush_command_buffer(CommandBufferType command_buffer, QueueType queue, bool free = true, SemaphoreType signal_semaphore = VK_NULL_HANDLE) const; + void add_queue(size_t global_index, uint32_t family_index, QueueFamilyPropertiesType const &properties, Bool32Type can_present); + void copy_buffer(vkb::core::Buffer const &src, + vkb::core::Buffer &dst, + QueueType queue, + BufferCopyType const *copy_region = nullptr); + CommandBufferType create_command_buffer(CommandBufferLevelType level, bool begin = false) const; + CommandPoolType create_command_pool(uint32_t queue_index, CommandPoolCreateFlagsType flags = 0); + std::pair + create_image(FormatType format, Extent2DType const &extent, uint32_t mip_levels, ImageUsageFlagsType usage, MemoryPropertyFlagsType properties) const; + void create_internal_command_pool(); + void create_internal_fence_pool(); + void flush_command_buffer(CommandBufferType command_buffer, QueueType queue, bool free = true, SemaphoreType signal_semaphore = VK_NULL_HANDLE) const; vkb::core::CommandPool &get_command_pool() const; DebugUtilsType const &get_debug_utils() const; FencePoolType &get_fence_pool() const; @@ -128,15 +130,19 @@ class Device void wait_idle() const; private: - void copy_buffer_impl(vk::Device device, vkb::core::BufferCpp const &src, vkb::core::BufferCpp &dst, vk::Queue queue, vk::BufferCopy const *copy_region); + void copy_buffer_impl(vk::Device device, vkb::core::BufferCpp const &src, vkb::core::BufferCpp &dst, vk::Queue queue, vk::BufferCopy const *copy_region); vk::CommandBuffer create_command_buffer_impl(vk::Device device, vk::CommandBufferLevel level, bool begin) const; - std::pair create_image_impl( - vk::Device device, vk::Format format, vk::Extent2D const &extent, uint32_t mip_levels, vk::ImageUsageFlags usage, vk::MemoryPropertyFlags properties) - const; - void flush_command_buffer_impl( - vk::Device device, vk::CommandBuffer command_buffer, vk::Queue queue, bool free = true, vk::Semaphore signal_semaphore = nullptr) const; + std::pair create_image_impl(vk::Device device, + vk::Format format, + vk::Extent2D const &extent, + uint32_t mip_levels, + vk::ImageUsageFlags usage, + vk::MemoryPropertyFlags properties) const; + void flush_command_buffer_impl( + vk::Device device, vk::CommandBuffer command_buffer, vk::Queue queue, bool free = true, vk::Semaphore signal_semaphore = nullptr) const; vkb::core::HPPQueue const &get_queue_by_flags_impl(vk::QueueFlags queue_flags, uint32_t queue_index) const; - void init(std::unordered_map const &requested_extensions, std::function &)> request_gpu_features); + void init(std::unordered_map const &requested_extensions, + std::function &)> request_gpu_features); private: std::unique_ptr command_pool; @@ -179,7 +185,11 @@ inline Device::Device(vkb::core::PhysicalDeviceC std::unique_ptr &&debug_utils, std::unordered_map const &requested_extensions, std::function request_gpu_features) : - vkb::core::VulkanResourceC{VK_NULL_HANDLE, this}, debug_utils{reinterpret_cast(debug_utils.release())}, gpu{reinterpret_cast(gpu)}, resource_cache{*reinterpret_cast(this)}, surface(static_cast(surface)) + vkb::core::VulkanResourceC{VK_NULL_HANDLE, this}, + debug_utils{reinterpret_cast(debug_utils.release())}, + gpu{reinterpret_cast(gpu)}, + resource_cache{*reinterpret_cast(this)}, + surface(static_cast(surface)) { init(requested_extensions, request_gpu_features); } @@ -193,7 +203,10 @@ inline Device::Device(vkb::core::PhysicalDeviceCpp &gpu, template <> inline Device::Device(vkb::core::PhysicalDeviceC &gpu, VkDevice &vulkan_device, VkSurfaceKHR surface) : - VulkanResource{vulkan_device}, gpu{reinterpret_cast(gpu)}, resource_cache{*reinterpret_cast(this)}, surface{static_cast(surface)} + VulkanResource{vulkan_device}, + gpu{reinterpret_cast(gpu)}, + resource_cache{*reinterpret_cast(this)}, + surface{static_cast(surface)} { debug_utils = std::make_unique(); } @@ -231,11 +244,8 @@ inline void Device::add_queue(size_t global_index, uint32_t family_ } else { - queues[global_index].emplace_back(*reinterpret_cast(this), - family_index, - reinterpret_cast(properties), - static_cast(can_present), - 0); + queues[global_index].emplace_back(*reinterpret_cast(this), family_index, + reinterpret_cast(properties), static_cast(can_present), 0); } } @@ -255,9 +265,7 @@ inline void Device::copy_buffer(vkb::core::Buffer cons else { copy_buffer_impl(static_cast(this->get_handle()), reinterpret_cast(src), - reinterpret_cast(dst), - static_cast(queue), - reinterpret_cast(copy_region)); + reinterpret_cast(dst), static_cast(queue), reinterpret_cast(copy_region)); } } @@ -300,12 +308,9 @@ inline std::pair::ImageType, typename Device>(create_image_impl(static_cast(this->get_handle()), - static_cast(format), - static_cast(extent), - mip_levels, - static_cast(usage), - static_cast(properties))); + return static_cast>( + create_image_impl(static_cast(this->get_handle()), static_cast(format), static_cast(extent), mip_levels, + static_cast(usage), static_cast(properties))); } } @@ -345,11 +350,8 @@ inline void Device::flush_command_buffer(CommandBufferType command_ } else { - flush_command_buffer_impl(static_cast(this->get_handle()), - static_cast(command_buffer), - static_cast(queue), - free, - static_cast(signal_semaphore)); + flush_command_buffer_impl(static_cast(this->get_handle()), static_cast(command_buffer), static_cast(queue), + free, static_cast(signal_semaphore)); } } @@ -438,9 +440,9 @@ inline typename Device::CoreQueueType const &Device::g template inline typename Device::CoreQueueType const &Device::get_queue_by_present(uint32_t queue_index) const { - auto queueIt = - std::ranges::find_if(queues, - [queue_index](const std::vector &queue_family) { return !queue_family.empty() && queue_index < queue_family[0].get_properties().queueCount && queue_family[0].support_present(); }); + auto queueIt = std::ranges::find_if(queues, [queue_index](const std::vector &queue_family) { + return !queue_family.empty() && queue_index < queue_family[0].get_properties().queueCount && queue_family[0].support_present(); + }); if (queueIt != queues.end()) { if constexpr (bindingType == vkb::BindingType::Cpp) @@ -481,9 +483,9 @@ inline bool Device::is_image_format_supported(FormatType format) co { // as we want to check for an error (vk::Result::eErrorFormatNotSupported) we use the non-throwing version of getImageFormatProperties here vk::ImageFormatProperties format_properties; - return vk::Result::eErrorFormatNotSupported != - gpu.get_handle().getImageFormatProperties( - static_cast(format), vk::ImageType::e2D, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eSampled, {}, &format_properties); + return vk::Result::eErrorFormatNotSupported != gpu.get_handle().getImageFormatProperties(static_cast(format), vk::ImageType::e2D, + vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eSampled, {}, + &format_properties); } template @@ -602,13 +604,11 @@ inline void Device::flush_command_buffer_impl( template vkb::core::HPPQueue const &Device::get_queue_by_flags_impl(vk::QueueFlags required_queue_flags, uint32_t queue_index) const { - auto queueIt = - std::ranges::find_if(queues, - [required_queue_flags, queue_index](const std::vector &queue) { - assert(!queue.empty()); - vk::QueueFamilyProperties const &properties = queue[0].get_properties(); - return ((properties.queueFlags & required_queue_flags) == required_queue_flags) && (queue_index < properties.queueCount); - }); + auto queueIt = std::ranges::find_if(queues, [required_queue_flags, queue_index](const std::vector &queue) { + assert(!queue.empty()); + vk::QueueFamilyProperties const &properties = queue[0].get_properties(); + return ((properties.queueFlags & required_queue_flags) == required_queue_flags) && (queue_index < properties.queueCount); + }); if (queueIt == queues.end()) { @@ -619,7 +619,8 @@ vkb::core::HPPQueue const &Device::get_queue_by_flags_impl(vk::Queu } template -inline void Device::init(std::unordered_map const &requested_extensions, std::function &)> request_gpu_features) +inline void Device::init(std::unordered_map const &requested_extensions, + std::function &)> request_gpu_features) { LOGI("Selected GPU: {}", *gpu.get_properties().deviceName); @@ -660,8 +661,7 @@ inline void Device::init(std::unordered_map con // For performance queries, we also use host query reset since queryPool resets cannot // live in the same command buffer as beginQuery - if (gpu.is_extension_supported("VK_KHR_performance_query") && - gpu.is_extension_supported("VK_EXT_host_query_reset")) + if (gpu.is_extension_supported("VK_KHR_performance_query") && gpu.is_extension_supported("VK_EXT_host_query_reset")) { auto perf_counter_features = gpu.get_extension_features(); auto host_query_reset_features = gpu.get_extension_features(); @@ -758,8 +758,8 @@ inline void Device::init(std::unordered_map con } else { - queues[queue_family_index].emplace_back( - *reinterpret_cast(this), queue_family_index, queue_family_property, present_supported, queue_index); + queues[queue_family_index].emplace_back(*reinterpret_cast(this), queue_family_index, queue_family_property, + present_supported, queue_index); } } } diff --git a/framework/core/framebuffer.cpp b/framework/core/framebuffer.cpp index 820d60ecf1..a8ed6c2818 100644 --- a/framework/core/framebuffer.cpp +++ b/framework/core/framebuffer.cpp @@ -33,8 +33,7 @@ const VkExtent2D &Framebuffer::get_extent() const } Framebuffer::Framebuffer(vkb::core::DeviceC &device, const vkb::rendering::RenderTargetC &render_target, const RenderPass &render_pass) : - device{device}, - extent{render_target.get_extent()} + device{device}, extent{render_target.get_extent()} { std::vector attachments; @@ -60,10 +59,7 @@ Framebuffer::Framebuffer(vkb::core::DeviceC &device, const vkb::rendering::Rende } } -Framebuffer::Framebuffer(Framebuffer &&other) : - device{other.device}, - handle{other.handle}, - extent{other.extent} +Framebuffer::Framebuffer(Framebuffer &&other) : device{other.device}, handle{other.handle}, extent{other.extent} { other.handle = VK_NULL_HANDLE; } diff --git a/framework/core/hpp_debug.cpp b/framework/core/hpp_debug.cpp index aefb947fcf..4c1bc9fe0c 100644 --- a/framework/core/hpp_debug.cpp +++ b/framework/core/hpp_debug.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -32,7 +32,8 @@ void HPPDebugUtilsExtDebugUtils::set_debug_name(vk::Device device, vk::ObjectTyp void HPPDebugUtilsExtDebugUtils::set_debug_tag( vk::Device device, vk::ObjectType object_type, uint64_t object_handle, uint64_t tag_name, const void *tag_data, size_t tag_data_size) const { - vk::DebugUtilsObjectTagInfoEXT tag_info{.objectType = object_type, .objectHandle = object_handle, .tagName = tag_name, .tagSize = tag_data_size, .pTag = tag_data}; + vk::DebugUtilsObjectTagInfoEXT tag_info{ + .objectType = object_type, .objectHandle = object_handle, .tagName = tag_name, .tagSize = tag_data_size, .pTag = tag_data}; device.setDebugUtilsObjectTagEXT(tag_info); } @@ -84,10 +85,7 @@ void HPPDebugMarkerExtDebugUtils::cmd_insert_label(vk::CommandBuffer command_buf command_buffer.debugMarkerInsertEXT(marker_info); } -HPPScopedDebugLabel::HPPScopedDebugLabel(const HPPDebugUtils &debug_utils, - vk::CommandBuffer command_buffer, - std::string const &name, - glm::vec4 const color) : +HPPScopedDebugLabel::HPPScopedDebugLabel(const HPPDebugUtils &debug_utils, vk::CommandBuffer command_buffer, std::string const &name, glm::vec4 const color) : debug_utils{&debug_utils}, command_buffer{VK_NULL_HANDLE} { if (!name.empty()) @@ -99,12 +97,9 @@ HPPScopedDebugLabel::HPPScopedDebugLabel(const HPPDebugUtils &debug_utils, } } -HPPScopedDebugLabel::HPPScopedDebugLabel(const vkb::core::CommandBufferCpp &command_buffer, - std::string const &name, - glm::vec4 const color) : +HPPScopedDebugLabel::HPPScopedDebugLabel(const vkb::core::CommandBufferCpp &command_buffer, std::string const &name, glm::vec4 const color) : HPPScopedDebugLabel{command_buffer.get_device().get_debug_utils(), command_buffer.get_handle(), name, color} -{ -} +{} HPPScopedDebugLabel::~HPPScopedDebugLabel() { diff --git a/framework/core/hpp_image.h b/framework/core/hpp_image.h index a670e643eb..f6052b7689 100644 --- a/framework/core/hpp_image.h +++ b/framework/core/hpp_image.h @@ -38,18 +38,13 @@ struct HPPImageBuilder : public vkb::allocated::BuilderBaseCpp uint32_t num_queue_families = 0, const uint32_t *queue_families = nullptr); - HPPImage(vkb::core::DeviceCpp &device, - HPPImageBuilder const &builder); + HPPImage(vkb::core::DeviceCpp &device, HPPImageBuilder const &builder); HPPImage(const HPPImage &) = delete; diff --git a/framework/core/hpp_image_core.cpp b/framework/core/hpp_image_core.cpp index 9058102ffc..ea9f10f1c4 100644 --- a/framework/core/hpp_image_core.cpp +++ b/framework/core/hpp_image_core.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -66,16 +66,15 @@ HPPImage::HPPImage(vkb::core::DeviceCpp &device, vk::ImageCreateFlags flags, uint32_t num_queue_families, const uint32_t *queue_families) : - HPPImage{device, - HPPImageBuilder{extent} - .with_format(format) - .with_mip_levels(mip_levels) - .with_array_layers(array_layers) - .with_sample_count(sample_count) - .with_tiling(tiling) - .with_flags(flags) - .with_usage(image_usage) - .with_queue_families(num_queue_families, queue_families)} + HPPImage{device, HPPImageBuilder{extent} + .with_format(format) + .with_mip_levels(mip_levels) + .with_array_layers(array_layers) + .with_sample_count(sample_count) + .with_tiling(tiling) + .with_flags(flags) + .with_usage(image_usage) + .with_queue_families(num_queue_families, queue_families)} {} HPPImage::HPPImage(vkb::core::DeviceCpp &device, HPPImageBuilder const &builder) : diff --git a/framework/core/hpp_image_view.cpp b/framework/core/hpp_image_view.cpp index bc6059b601..b54215dafb 100644 --- a/framework/core/hpp_image_view.cpp +++ b/framework/core/hpp_image_view.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -39,7 +39,8 @@ HPPImageView::HPPImageView(vkb::core::HPPImage &img, this->format = format = image->get_format(); } - subresource_range = vk::ImageSubresourceRange{.aspectMask = (std::string(vk::componentName(format, 0)) == "D") ? vk::ImageAspectFlagBits::eDepth : vk::ImageAspectFlagBits::eColor, + subresource_range = vk::ImageSubresourceRange{.aspectMask = (std::string(vk::componentName(format, 0)) == "D") ? vk::ImageAspectFlagBits::eDepth : + vk::ImageAspectFlagBits::eColor, .baseMipLevel = mip_level, .levelCount = n_mip_levels == 0 ? image->get_subresource().mipLevel : n_mip_levels, .baseArrayLayer = array_layer, @@ -92,8 +93,8 @@ void HPPImageView::set_image(vkb::core::HPPImage &img) vk::ImageSubresourceLayers HPPImageView::get_subresource_layers() const { - return vk::ImageSubresourceLayers{ - subresource_range.aspectMask, subresource_range.baseMipLevel, subresource_range.baseArrayLayer, subresource_range.layerCount}; + return vk::ImageSubresourceLayers{subresource_range.aspectMask, subresource_range.baseMipLevel, subresource_range.baseArrayLayer, + subresource_range.layerCount}; } vk::ImageSubresourceRange HPPImageView::get_subresource_range() const diff --git a/framework/core/hpp_pipeline_layout.cpp b/framework/core/hpp_pipeline_layout.cpp index 61c08d0c93..fef2814c48 100644 --- a/framework/core/hpp_pipeline_layout.cpp +++ b/framework/core/hpp_pipeline_layout.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -25,8 +25,7 @@ namespace vkb namespace core { HPPPipelineLayout::HPPPipelineLayout(vkb::core::DeviceCpp &device, const std::vector &shader_modules) : - device{device}, - shader_modules{shader_modules} + device{device}, shader_modules{shader_modules} { // Collect and combine all the shader resources from each of the shader modules // Collate them all into a map that is indexed by the name of the resource diff --git a/framework/core/hpp_pipeline_layout.h b/framework/core/hpp_pipeline_layout.h index 8e0515a662..19733b78cc 100644 --- a/framework/core/hpp_pipeline_layout.h +++ b/framework/core/hpp_pipeline_layout.h @@ -42,22 +42,24 @@ class HPPPipelineLayout HPPPipelineLayout &operator=(const HPPPipelineLayout &) = delete; HPPPipelineLayout &operator=(HPPPipelineLayout &&) = delete; - vkb::core::HPPDescriptorSetLayout const &get_descriptor_set_layout(const uint32_t set_index) const; - vk::PipelineLayout get_handle() const; - vk::ShaderStageFlags get_push_constant_range_stage(uint32_t size, uint32_t offset = 0) const; - std::vector get_resources(const vkb::core::HPPShaderResourceType &type = vkb::core::HPPShaderResourceType::All, - vk::ShaderStageFlagBits stage = vk::ShaderStageFlagBits::eAll) const; - const std::vector &get_shader_modules() const; + vkb::core::HPPDescriptorSetLayout const &get_descriptor_set_layout(const uint32_t set_index) const; + vk::PipelineLayout get_handle() const; + vk::ShaderStageFlags get_push_constant_range_stage(uint32_t size, uint32_t offset = 0) const; + std::vector get_resources(const vkb::core::HPPShaderResourceType &type = vkb::core::HPPShaderResourceType::All, + vk::ShaderStageFlagBits stage = vk::ShaderStageFlagBits::eAll) const; + const std::vector &get_shader_modules() const; const std::unordered_map> &get_shader_sets() const; bool has_descriptor_set_layout(const uint32_t set_index) const; private: - vkb::core::DeviceCpp &device; - vk::PipelineLayout handle; - std::vector shader_modules; // The shader modules that this pipeline layout uses - std::unordered_map shader_resources; // The shader resources that this pipeline layout uses, indexed by their name - std::unordered_map> shader_sets; // A map of each set and the resources it owns used by the pipeline layout - std::vector descriptor_set_layouts; // The different descriptor set layouts for this pipeline layout + vkb::core::DeviceCpp &device; + vk::PipelineLayout handle; + std::vector shader_modules; // The shader modules that this pipeline layout uses + std::unordered_map + shader_resources; // The shader resources that this pipeline layout uses, indexed by their name + std::unordered_map> + shader_sets; // A map of each set and the resources it owns used by the pipeline layout + std::vector descriptor_set_layouts; // The different descriptor set layouts for this pipeline layout }; } // namespace core } // namespace vkb diff --git a/framework/core/hpp_sampler.cpp b/framework/core/hpp_sampler.cpp index e8ef85d985..e5fce3108b 100644 --- a/framework/core/hpp_sampler.cpp +++ b/framework/core/hpp_sampler.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -26,8 +26,7 @@ HPPSampler::HPPSampler(vkb::core::DeviceCpp &device, const vk::SamplerCreateInfo vkb::core::VulkanResourceCpp{device.get_handle().createSampler(info), &device} {} -HPPSampler::HPPSampler(HPPSampler &&other) : - VulkanResource(std::move(other)) +HPPSampler::HPPSampler(HPPSampler &&other) : VulkanResource(std::move(other)) {} HPPSampler::~HPPSampler() diff --git a/framework/core/hpp_shader_module.h b/framework/core/hpp_shader_module.h index 1f27d87e62..e1a7946d99 100644 --- a/framework/core/hpp_shader_module.h +++ b/framework/core/hpp_shader_module.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -85,8 +85,7 @@ class HPPShaderSource : private vkb::ShaderSource { public: HPPShaderSource() = default; - HPPShaderSource(const std::string &filename) : - vkb::ShaderSource(filename) + HPPShaderSource(const std::string &filename) : vkb::ShaderSource(filename) {} }; diff --git a/framework/core/hpp_swapchain.cpp b/framework/core/hpp_swapchain.cpp index 5b77c55f28..822b5d4805 100644 --- a/framework/core/hpp_swapchain.cpp +++ b/framework/core/hpp_swapchain.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -34,10 +34,8 @@ inline uint32_t choose_image_count(uint32_t request_image_count, uint32_t min_im return clamp(request_image_count, min_image_count, (max_image_count != 0) ? max_image_count : request_image_count); } -vk::Extent2D choose_extent(vk::Extent2D request_extent, - const vk::Extent2D &min_image_extent, - const vk::Extent2D &max_image_extent, - const vk::Extent2D ¤t_extent) +vk::Extent2D + choose_extent(vk::Extent2D request_extent, const vk::Extent2D &min_image_extent, const vk::Extent2D &max_image_extent, const vk::Extent2D ¤t_extent) { if (current_extent.width == 0xFFFFFFFF) { @@ -46,10 +44,7 @@ vk::Extent2D choose_extent(vk::Extent2D request_extent, if (request_extent.width < 1 || request_extent.height < 1) { - LOGW("(HPPSwapchain) Image extent ({}, {}) not supported. Selecting ({}, {}).", - request_extent.width, - request_extent.height, - current_extent.width, + LOGW("(HPPSwapchain) Image extent ({}, {}) not supported. Selecting ({}, {}).", request_extent.width, request_extent.height, current_extent.width, current_extent.height); return current_extent; } @@ -69,12 +64,13 @@ vk::PresentModeKHR choose_present_mode(vk::PresentModeKHR re if (present_mode_it == available_present_modes.end()) { // If the requested present mode isn't found, then try to find a mode from the priority list - auto const chosen_present_mode_it = - std::ranges::find_if(present_mode_priority_list, - [&available_present_modes](vk::PresentModeKHR present_mode) { return std::ranges::find(available_present_modes, present_mode) != available_present_modes.end(); }); + auto const chosen_present_mode_it = std::ranges::find_if(present_mode_priority_list, [&available_present_modes](vk::PresentModeKHR present_mode) { + return std::ranges::find(available_present_modes, present_mode) != available_present_modes.end(); + }); // If nothing found, always default to FIFO - vk::PresentModeKHR const chosen_present_mode = (chosen_present_mode_it != present_mode_priority_list.end()) ? *chosen_present_mode_it : vk::PresentModeKHR::eFifo; + vk::PresentModeKHR const chosen_present_mode = + (chosen_present_mode_it != present_mode_priority_list.end()) ? *chosen_present_mode_it : vk::PresentModeKHR::eFifo; LOGW("(HPPSwapchain) Present mode '{}' not supported. Selecting '{}'.", vk::to_string(request_present_mode), vk::to_string(chosen_present_mode)); return chosen_present_mode; @@ -97,11 +93,13 @@ vk::SurfaceFormatKHR choose_surface_format(const vk::SurfaceFormatKHR if (surface_format_it == available_surface_formats.end()) { auto const chosen_surface_format_it = - std::ranges::find_if(surface_format_priority_list, - [&available_surface_formats](vk::SurfaceFormatKHR surface_format) { return std::ranges::find(available_surface_formats, surface_format) != available_surface_formats.end(); }); + std::ranges::find_if(surface_format_priority_list, [&available_surface_formats](vk::SurfaceFormatKHR surface_format) { + return std::ranges::find(available_surface_formats, surface_format) != available_surface_formats.end(); + }); // If nothing found, default to the first available format - vk::SurfaceFormatKHR const &chosen_surface_format = (chosen_surface_format_it != surface_format_priority_list.end()) ? *chosen_surface_format_it : available_surface_formats[0]; + vk::SurfaceFormatKHR const &chosen_surface_format = + (chosen_surface_format_it != surface_format_priority_list.end()) ? *chosen_surface_format_it : available_surface_formats[0]; LOGW("(HPPSwapchain) Surface format ({}) not supported. Selecting ({}).", vk::to_string(requested_surface_format.format) + ", " + vk::to_string(requested_surface_format.colorSpace), @@ -142,14 +140,12 @@ vk::CompositeAlphaFlagBitsKHR choose_composite_alpha(vk::CompositeAlphaFlagBitsK return request_composite_alpha; } - static const std::vector composite_alpha_priority_list = {vk::CompositeAlphaFlagBitsKHR::eOpaque, - vk::CompositeAlphaFlagBitsKHR::ePreMultiplied, - vk::CompositeAlphaFlagBitsKHR::ePostMultiplied, - vk::CompositeAlphaFlagBitsKHR::eInherit}; + static const std::vector composite_alpha_priority_list = { + vk::CompositeAlphaFlagBitsKHR::eOpaque, vk::CompositeAlphaFlagBitsKHR::ePreMultiplied, vk::CompositeAlphaFlagBitsKHR::ePostMultiplied, + vk::CompositeAlphaFlagBitsKHR::eInherit}; auto const chosen_composite_alpha_it = - std::find_if(composite_alpha_priority_list.begin(), - composite_alpha_priority_list.end(), + std::find_if(composite_alpha_priority_list.begin(), composite_alpha_priority_list.end(), [&supported_composite_alpha](vk::CompositeAlphaFlagBitsKHR composite_alpha) { return composite_alpha & supported_composite_alpha; }); if (chosen_composite_alpha_it == composite_alpha_priority_list.end()) { @@ -157,7 +153,8 @@ vk::CompositeAlphaFlagBitsKHR choose_composite_alpha(vk::CompositeAlphaFlagBitsK } else { - LOGW("(HPPSwapchain) Composite alpha '{}' not supported. Selecting '{}.", vk::to_string(request_composite_alpha), vk::to_string(*chosen_composite_alpha_it)); + LOGW("(HPPSwapchain) Composite alpha '{}' not supported. Selecting '{}.", vk::to_string(request_composite_alpha), + vk::to_string(*chosen_composite_alpha_it)); return *chosen_composite_alpha_it; } } @@ -190,9 +187,9 @@ std::set choose_image_usage(const std::set image_usage_priority_list = { vk::ImageUsageFlagBits::eColorAttachment, vk::ImageUsageFlagBits::eStorage, vk::ImageUsageFlagBits::eSampled, vk::ImageUsageFlagBits::eTransferDst}; - auto const priority_list_it = - std::ranges::find_if(image_usage_priority_list, - [&supported_image_usage, &supported_features](auto const image_usage) { return ((image_usage & supported_image_usage) && validate_format_feature(image_usage, supported_features)); }); + auto const priority_list_it = std::ranges::find_if(image_usage_priority_list, [&supported_image_usage, &supported_features](auto const image_usage) { + return ((image_usage & supported_image_usage) && validate_format_feature(image_usage, supported_features)); + }); if (priority_list_it != image_usage_priority_list.end()) { validated_image_usage_flags.insert(*priority_list_it); @@ -305,8 +302,7 @@ HPPSwapchain::HPPSwapchain(HPPSwapchain &old_swapc old_swapchain.image_usage_flags, requested_compression, requested_compression_fixed_rate} -{ -} +{} HPPSwapchain::HPPSwapchain(vkb::core::DeviceCpp &device, vk::SurfaceKHR surface, @@ -319,7 +315,8 @@ HPPSwapchain::HPPSwapchain(vkb::core::DeviceCpp &device, const std::set &image_usage_flags, const vk::ImageCompressionFlagsEXT requested_compression, const vk::ImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate) : - HPPSwapchain{*this, device, surface, present_mode, present_mode_priority_list, surface_format_priority_list, extent, image_count, transform, image_usage_flags} + HPPSwapchain{*this, device, surface, present_mode, present_mode_priority_list, surface_format_priority_list, + extent, image_count, transform, image_usage_flags} {} HPPSwapchain::HPPSwapchain(HPPSwapchain &old_swapchain, @@ -334,10 +331,7 @@ HPPSwapchain::HPPSwapchain(HPPSwapchain &old_swapc const std::set &image_usage_flags, const vk::ImageCompressionFlagsEXT requested_compression, const vk::ImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate) : - device{device}, - surface{surface}, - requested_compression{requested_compression}, - requested_compression_fixed_rate{requested_compression_fixed_rate} + device{device}, surface{surface}, requested_compression{requested_compression}, requested_compression_fixed_rate{requested_compression_fixed_rate} { this->present_mode_priority_list = present_mode_priority_list; this->surface_format_priority_list = surface_format_priority_list; @@ -359,14 +353,14 @@ HPPSwapchain::HPPSwapchain(HPPSwapchain &old_swapc // Choose best properties based on surface capabilities vk::SurfaceCapabilitiesKHR const surface_capabilities = device.get_gpu().get_handle().getSurfaceCapabilitiesKHR(surface); - properties.old_swapchain = old_swapchain.get_handle(); - properties.image_count = choose_image_count(image_count, surface_capabilities.minImageCount, surface_capabilities.maxImageCount); - properties.extent = choose_extent(extent, surface_capabilities.minImageExtent, surface_capabilities.maxImageExtent, surface_capabilities.currentExtent); + properties.old_swapchain = old_swapchain.get_handle(); + properties.image_count = choose_image_count(image_count, surface_capabilities.minImageCount, surface_capabilities.maxImageCount); + properties.extent = choose_extent(extent, surface_capabilities.minImageExtent, surface_capabilities.maxImageExtent, surface_capabilities.currentExtent); properties.surface_format = choose_surface_format(properties.surface_format, surface_formats, surface_format_priority_list); properties.array_layers = choose_image_array_layers(1U, surface_capabilities.maxImageArrayLayers); vk::FormatProperties const format_properties = device.get_gpu().get_handle().getFormatProperties(properties.surface_format.format); - this->image_usage_flags = choose_image_usage(image_usage_flags, surface_capabilities.supportedUsageFlags, format_properties.optimalTilingFeatures); + this->image_usage_flags = choose_image_usage(image_usage_flags, surface_capabilities.supportedUsageFlags, format_properties.optimalTilingFeatures); properties.image_usage = composite_image_flags(this->image_usage_flags); properties.pre_transform = choose_transform(transform, surface_capabilities.supportedTransforms, surface_capabilities.currentTransform); @@ -426,8 +420,7 @@ HPPSwapchain::HPPSwapchain(HPPSwapchain &old_swapc if (applied_compression_fixed_rate != requested_compression_fixed_rate) { - LOGW("(Swapchain) Requested fixed-rate compression ({}) was not applied, instead images use {}", - vk::to_string(requested_compression_fixed_rate), + LOGW("(Swapchain) Requested fixed-rate compression ({}) was not applied, instead images use {}", vk::to_string(requested_compression_fixed_rate), vk::to_string(applied_compression_fixed_rate)); this->requested_compression_fixed_rate = applied_compression_fixed_rate; diff --git a/framework/core/hpp_swapchain.h b/framework/core/hpp_swapchain.h index a5505bd206..55dedea6e9 100644 --- a/framework/core/hpp_swapchain.h +++ b/framework/core/hpp_swapchain.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -80,35 +80,35 @@ class HPPSwapchain /** * @brief Constructor to create a swapchain. */ - HPPSwapchain(vkb::core::DeviceCpp &device, - vk::SurfaceKHR surface, - const vk::PresentModeKHR present_mode, - const std::vector &present_mode_priority_list = {vk::PresentModeKHR::eFifo, vk::PresentModeKHR::eMailbox}, - const std::vector &surface_format_priority_list = {{vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}, - {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}}, - const vk::Extent2D &extent = {}, - const uint32_t image_count = 3, - const vk::SurfaceTransformFlagBitsKHR transform = vk::SurfaceTransformFlagBitsKHR::eIdentity, - const std::set &image_usage_flags = {vk::ImageUsageFlagBits::eColorAttachment, vk::ImageUsageFlagBits::eTransferSrc}, - const vk::ImageCompressionFlagsEXT requested_compression = vk::ImageCompressionFlagBitsEXT::eDefault, + HPPSwapchain(vkb::core::DeviceCpp &device, + vk::SurfaceKHR surface, + const vk::PresentModeKHR present_mode, + const std::vector &present_mode_priority_list = {vk::PresentModeKHR::eFifo, vk::PresentModeKHR::eMailbox}, + const std::vector &surface_format_priority_list = {{vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}, + {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}}, + const vk::Extent2D &extent = {}, + const uint32_t image_count = 3, + const vk::SurfaceTransformFlagBitsKHR transform = vk::SurfaceTransformFlagBitsKHR::eIdentity, + const std::set &image_usage_flags = {vk::ImageUsageFlagBits::eColorAttachment, vk::ImageUsageFlagBits::eTransferSrc}, + const vk::ImageCompressionFlagsEXT requested_compression = vk::ImageCompressionFlagBitsEXT::eDefault, const vk::ImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate = vk::ImageCompressionFixedRateFlagBitsEXT::eNone); /** * @brief Constructor to create a swapchain from the old swapchain * by configuring all parameters. */ - HPPSwapchain(HPPSwapchain &old_swapchain, - vkb::core::DeviceCpp &device, - vk::SurfaceKHR surface, - const vk::PresentModeKHR present_mode, - const std::vector &present_mode_priority_list = {vk::PresentModeKHR::eFifo, vk::PresentModeKHR::eMailbox}, - const std::vector &surface_format_priority_list = {{vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}, - {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}}, - const vk::Extent2D &extent = {}, - const uint32_t image_count = 3, - const vk::SurfaceTransformFlagBitsKHR transform = vk::SurfaceTransformFlagBitsKHR::eIdentity, - const std::set &image_usage_flags = {vk::ImageUsageFlagBits::eColorAttachment, vk::ImageUsageFlagBits::eTransferSrc}, - const vk::ImageCompressionFlagsEXT requested_compression = vk::ImageCompressionFlagBitsEXT::eDefault, + HPPSwapchain(HPPSwapchain &old_swapchain, + vkb::core::DeviceCpp &device, + vk::SurfaceKHR surface, + const vk::PresentModeKHR present_mode, + const std::vector &present_mode_priority_list = {vk::PresentModeKHR::eFifo, vk::PresentModeKHR::eMailbox}, + const std::vector &surface_format_priority_list = {{vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}, + {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}}, + const vk::Extent2D &extent = {}, + const uint32_t image_count = 3, + const vk::SurfaceTransformFlagBitsKHR transform = vk::SurfaceTransformFlagBitsKHR::eIdentity, + const std::set &image_usage_flags = {vk::ImageUsageFlagBits::eColorAttachment, vk::ImageUsageFlagBits::eTransferSrc}, + const vk::ImageCompressionFlagsEXT requested_compression = vk::ImageCompressionFlagBitsEXT::eDefault, const vk::ImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate = vk::ImageCompressionFixedRateFlagBitsEXT::eNone); HPPSwapchain(const HPPSwapchain &) = delete; diff --git a/framework/core/image.h b/framework/core/image.h index 40f9df9336..e00d1edb33 100644 --- a/framework/core/image.h +++ b/framework/core/image.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -42,8 +42,7 @@ struct ImageBuilder : public vkb::allocated::BuilderBaseC; public: - ImageBuilder(VkExtent3D const &extent) : - Parent(VkImageCreateInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, nullptr}) + ImageBuilder(VkExtent3D const &extent) : Parent(VkImageCreateInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, nullptr}) { VkImageCreateInfo &create_info = get_create_info(); create_info.extent = extent; @@ -54,10 +53,8 @@ struct ImageBuilder : public vkb::allocated::BuilderBaseC VkSampleCountFlagBits sample_count = VK_SAMPLE_COUNT_1_BIT); // [[deprecated("Use the ImageBuilder ctor instead")]] - Image( - vkb::core::DeviceC &device, - const VkExtent3D &extent, - VkFormat format, - VkImageUsageFlags image_usage, - VmaMemoryUsage memory_usage = VMA_MEMORY_USAGE_AUTO, - VkSampleCountFlagBits sample_count = VK_SAMPLE_COUNT_1_BIT, - uint32_t mip_levels = 1, - uint32_t array_layers = 1, - VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL, - VkImageCreateFlags flags = 0, - uint32_t num_queue_families = 0, - const uint32_t *queue_families = nullptr); + Image(vkb::core::DeviceC &device, + const VkExtent3D &extent, + VkFormat format, + VkImageUsageFlags image_usage, + VmaMemoryUsage memory_usage = VMA_MEMORY_USAGE_AUTO, + VkSampleCountFlagBits sample_count = VK_SAMPLE_COUNT_1_BIT, + uint32_t mip_levels = 1, + uint32_t array_layers = 1, + VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL, + VkImageCreateFlags flags = 0, + uint32_t num_queue_families = 0, + const uint32_t *queue_families = nullptr); Image(vkb::core::DeviceC &device, ImageBuilder const &builder); diff --git a/framework/core/image_core.cpp b/framework/core/image_core.cpp index bf008f9559..46760362ea 100644 --- a/framework/core/image_core.cpp +++ b/framework/core/image_core.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -104,8 +104,7 @@ Image::Image(vkb::core::DeviceC &device, .with_sample_count(sample_count) .with_queue_families(num_queue_families, queue_families) .with_implicit_sharing_mode()) -{ -} +{} Image::Image(vkb::core::DeviceC &device, ImageBuilder const &builder) : vkb::allocated::AllocatedC{builder.get_allocation_create_info(), VK_NULL_HANDLE, &device}, create_info(builder.get_create_info()) @@ -132,9 +131,11 @@ Image::Image( subresource.mipLevel = create_info.mipLevels = 1; } -Image::Image(Image &&other) noexcept - : - vkb::allocated::AllocatedC{std::move(other)}, create_info{std::exchange(other.create_info, {})}, subresource{std::exchange(other.subresource, {})}, views(std::exchange(other.views, {})) +Image::Image(Image &&other) noexcept : + vkb::allocated::AllocatedC{std::move(other)}, + create_info{std::exchange(other.create_info, {})}, + subresource{std::exchange(other.subresource, {})}, + views(std::exchange(other.views, {})) { // Update image views references to this image to avoid dangling pointers for (auto &view : views) diff --git a/framework/core/image_view.cpp b/framework/core/image_view.cpp index ae5c0ebbe8..f5c5b8f923 100644 --- a/framework/core/image_view.cpp +++ b/framework/core/image_view.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2024, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -24,12 +24,9 @@ namespace vkb { namespace core { -ImageView::ImageView(Image &img, VkImageViewType view_type, VkFormat format, - uint32_t mip_level, uint32_t array_layer, - uint32_t n_mip_levels, uint32_t n_array_layers) : - VulkanResource{VK_NULL_HANDLE, &img.get_device()}, - image{&img}, - format{format} +ImageView::ImageView( + Image &img, VkImageViewType view_type, VkFormat format, uint32_t mip_level, uint32_t array_layer, uint32_t n_mip_levels, uint32_t n_array_layers) : + VulkanResource{VK_NULL_HANDLE, &img.get_device()}, image{&img}, format{format} { if (format == VK_FORMAT_UNDEFINED) { @@ -68,11 +65,7 @@ ImageView::ImageView(Image &img, VkImageViewType view_type, VkFormat format, image->get_views().emplace(this); } -ImageView::ImageView(ImageView &&other) : - VulkanResource{std::move(other)}, - image{other.image}, - format{other.format}, - subresource_range{other.subresource_range} +ImageView::ImageView(ImageView &&other) : VulkanResource{std::move(other)}, image{other.image}, format{other.format}, subresource_range{other.subresource_range} { // Remove old view from image set and add this new one auto &views = image->get_views(); diff --git a/framework/core/image_view.h b/framework/core/image_view.h index 876faaaf84..9b9740e532 100644 --- a/framework/core/image_view.h +++ b/framework/core/image_view.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -30,9 +30,13 @@ class Image; class ImageView : public vkb::core::VulkanResourceC { public: - ImageView(Image &image, VkImageViewType view_type, VkFormat format = VK_FORMAT_UNDEFINED, - uint32_t base_mip_level = 0, uint32_t base_array_layer = 0, - uint32_t n_mip_levels = 0, uint32_t n_array_layers = 0); + ImageView(Image &image, + VkImageViewType view_type, + VkFormat format = VK_FORMAT_UNDEFINED, + uint32_t base_mip_level = 0, + uint32_t base_array_layer = 0, + uint32_t n_mip_levels = 0, + uint32_t n_array_layers = 0); ImageView(ImageView &) = delete; diff --git a/framework/core/instance.h b/framework/core/instance.h index 1b009255f8..31aa50c6db 100644 --- a/framework/core/instance.h +++ b/framework/core/instance.h @@ -28,7 +28,8 @@ namespace core namespace { template -typename std::conditional::type get_default_create_flags(std::vector const &) +typename std::conditional::type + get_default_create_flags(std::vector const &) { if constexpr (bindingType == vkb::BindingType::Cpp) { @@ -70,13 +71,12 @@ class Instance * @param get_create_flags A function pointer returning the InstanceCreateFlags for the InstanceCreateInfo * @throws runtime_error if a required layer or extension is not available */ - Instance( - std::string const &application_name, - uint32_t api_version = VK_API_VERSION_1_1, - std::unordered_map const &requested_layers = {}, - std::unordered_map const &requested_extensions = {}, - std::function const &, std::vector const &)> const &get_pNext = get_default_pNext, - std::function const &)> const &get_create_flags = get_default_create_flags); + Instance(std::string const &application_name, + uint32_t api_version = VK_API_VERSION_1_1, + std::unordered_map const &requested_layers = {}, + std::unordered_map const &requested_extensions = {}, + std::function const &, std::vector const &)> const &get_pNext = get_default_pNext, + std::function const &)> const &get_create_flags = get_default_create_flags); Instance(vk::Instance instance, std::vector const &externally_enabled_extensions = {}, bool needsToInitializeDispatcher = false); Instance(VkInstance instance, std::vector const &externally_enabled_extensions = {}); @@ -133,8 +133,7 @@ inline bool enable_extension(std::string const &request return is_available; } -inline bool - enable_layer(std::string const &requested_layer, std::vector const &available_layers, std::vector &enabled_layers) +inline bool enable_layer(std::string const &requested_layer, std::vector const &available_layers, std::vector &enabled_layers) { bool is_available = std::ranges::any_of(available_layers, [&requested_layer](auto const &available_layer) { return requested_layer == available_layer.layerName; }); @@ -158,10 +157,10 @@ inline bool } // namespace template -inline Instance::Instance(std::string const &application_name, - uint32_t api_version, - std::unordered_map const &requested_layers, - std::unordered_map const &requested_extensions, +inline Instance::Instance(std::string const &application_name, + uint32_t api_version, + std::unordered_map const &requested_layers, + std::unordered_map const &requested_extensions, std::function const &, std::vector const &)> const &get_pNext, std::function const &)> const &get_create_flags) { @@ -176,11 +175,8 @@ inline Instance::Instance(std::string const LOGI("Vulkan instance supports API version {}.{}", VK_VERSION_MAJOR(instance_api_version), VK_VERSION_MINOR(instance_api_version)); if (instance_api_version < api_version) { - LOGE("Vulkan API version {}.{} is requested but only version {}.{} is supported.", - VK_VERSION_MAJOR(api_version), - VK_VERSION_MINOR(api_version), - VK_VERSION_MAJOR(instance_api_version), - VK_VERSION_MINOR(instance_api_version)); + LOGE("Vulkan API version {}.{} is requested but only version {}.{} is supported.", VK_VERSION_MAJOR(api_version), VK_VERSION_MINOR(api_version), + VK_VERSION_MAJOR(instance_api_version), VK_VERSION_MINOR(instance_api_version)); throw std::runtime_error("Requested Vulkan API version is too high."); } @@ -215,9 +211,7 @@ inline Instance::Instance(std::string const { std::string const validation_layer_name = "VK_LAYER_KHRONOS_validation"; std::vector available_layer_instance_extensions = vk::enumerateInstanceExtensionProperties(validation_layer_name); - available_extensions.insert(available_extensions.end(), - available_layer_instance_extensions.begin(), - available_layer_instance_extensions.end()); + available_extensions.insert(available_extensions.end(), available_layer_instance_extensions.begin(), available_layer_instance_extensions.end()); } for (auto const &requested_extension : requested_extensions) @@ -262,7 +256,9 @@ inline Instance::Instance(std::string const } template -inline Instance::Instance(vk::Instance instance, std::vector const &externally_enabled_extensions, bool needsToInitializeDispatcher) : +inline Instance::Instance(vk::Instance instance, + std::vector const &externally_enabled_extensions, + bool needsToInitializeDispatcher) : handle{instance} { if (needsToInitializeDispatcher) diff --git a/framework/core/physical_device.h b/framework/core/physical_device.h index fb00e05bb7..a104c2c90e 100644 --- a/framework/core/physical_device.h +++ b/framework/core/physical_device.h @@ -47,17 +47,15 @@ class PhysicalDevice using MemoryPropertyFlagsType = typename std::conditional::type; using PerformanceCounterDescriptionKHRType = typename std::conditional::type; - using PerformanceCounterKHRType = - typename std::conditional::type; + using PerformanceCounterKHRType = typename std::conditional::type; using PhysicalDeviceFeaturesType = typename std::conditional::type; using PhysicalDeviceMemoryPropertiesType = typename std::conditional::type; using PhysicalDevicePropertiesType = typename std::conditional::type; - using PhysicalDeviceType = typename std::conditional::type; - using QueueFamilyPropertiesType = - typename std::conditional::type; + using PhysicalDeviceType = typename std::conditional::type; + using QueueFamilyPropertiesType = typename std::conditional::type; using QueryPoolPerformanceCreateInfoKHRType = typename std::conditional::type; using StructureTypeType = typename std::conditional::type; @@ -108,15 +106,15 @@ class PhysicalDevice template T get_extension_features(); - PhysicalDeviceFeaturesType const &get_features() const; - FormatPropertiesType get_format_properties(FormatType format) const; - PhysicalDeviceType get_handle() const; - vkb::core::Instance &get_instance() const; - PhysicalDeviceMemoryPropertiesType const &get_memory_properties() const; - uint32_t get_memory_type(uint32_t bits, MemoryPropertyFlagsType properties, Bool32Type *memory_type_found = nullptr) const; - PhysicalDeviceFeaturesType &get_mutable_requested_features(); - PhysicalDevicePropertiesType const &get_properties() const; - uint32_t get_queue_family_performance_query_passes(QueryPoolPerformanceCreateInfoKHRType const *perf_query_create_info) const; + PhysicalDeviceFeaturesType const &get_features() const; + FormatPropertiesType get_format_properties(FormatType format) const; + PhysicalDeviceType get_handle() const; + vkb::core::Instance &get_instance() const; + PhysicalDeviceMemoryPropertiesType const &get_memory_properties() const; + uint32_t get_memory_type(uint32_t bits, MemoryPropertyFlagsType properties, Bool32Type *memory_type_found = nullptr) const; + PhysicalDeviceFeaturesType &get_mutable_requested_features(); + PhysicalDevicePropertiesType const &get_properties() const; + uint32_t get_queue_family_performance_query_passes(QueryPoolPerformanceCreateInfoKHRType const *perf_query_create_info) const; std::vector const &get_queue_family_properties() const; PhysicalDeviceFeaturesType const &get_requested_features() const; @@ -169,16 +167,16 @@ class PhysicalDevice private: std::vector device_extensions; // The extensions that this GPU supports std::map> - extension_features; // Holds the extension feature structures, we use a map to retain an order of requested structures - vk::PhysicalDeviceFeatures features; // The features that this GPU supports - vk::PhysicalDevice handle; // Handle to the Vulkan physical device - bool high_priority_graphics_queue = {}; - vkb::core::InstanceCpp &instance; // Handle to the Vulkan instance - void *last_requested_extension_feature = nullptr; // The extension feature pointer - vk::PhysicalDeviceMemoryProperties memory_properties; // The GPU memory properties - vk::PhysicalDeviceProperties properties; // The GPU properties - std::vector queue_family_properties; // The GPU queue family properties - vk::PhysicalDeviceFeatures requested_features; // The features that will be requested to be enabled in the logical device + extension_features; // Holds the extension feature structures, we use a map to retain an order of requested structures + vk::PhysicalDeviceFeatures features; // The features that this GPU supports + vk::PhysicalDevice handle; // Handle to the Vulkan physical device + bool high_priority_graphics_queue = {}; + vkb::core::InstanceCpp &instance; // Handle to the Vulkan instance + void *last_requested_extension_feature = nullptr; // The extension feature pointer + vk::PhysicalDeviceMemoryProperties memory_properties; // The GPU memory properties + vk::PhysicalDeviceProperties properties; // The GPU properties + std::vector queue_family_properties; // The GPU queue family properties + vk::PhysicalDeviceFeatures requested_features; // The features that will be requested to be enabled in the logical device }; using PhysicalDeviceC = PhysicalDevice; @@ -430,8 +428,7 @@ inline typename PhysicalDevice::PhysicalDevicePropertiesType const } template -uint32_t - PhysicalDevice::get_queue_family_performance_query_passes(QueryPoolPerformanceCreateInfoKHRType const *perf_query_create_info) const +uint32_t PhysicalDevice::get_queue_family_performance_query_passes(QueryPoolPerformanceCreateInfoKHRType const *perf_query_create_info) const { if constexpr (bindingType == vkb::BindingType::Cpp) { @@ -471,8 +468,9 @@ inline bool PhysicalDevice::has_high_priority_graphics_queue() cons template inline bool PhysicalDevice::is_extension_supported(const std::string &requested_extension) const { - return std::ranges::find_if(device_extensions, - [requested_extension](auto &device_extension) { return std::strcmp(device_extension.extensionName, requested_extension.c_str()) == 0; }) != device_extensions.end(); + return std::ranges::find_if(device_extensions, [requested_extension](auto &device_extension) { + return std::strcmp(device_extension.extensionName, requested_extension.c_str()) == 0; + }) != device_extensions.end(); } template @@ -501,8 +499,7 @@ inline typename PhysicalDevice::Bool32Type template template -inline void - PhysicalDevice::request_required_feature(Bool32Type Feature::*flag, std::string const &featureName, std::string const &flagName) +inline void PhysicalDevice::request_required_feature(Bool32Type Feature::*flag, std::string const &featureName, std::string const &flagName) { if constexpr (bindingType == BindingType::Cpp) { @@ -510,15 +507,14 @@ inline void } else { - request_required_feature_impl::Type>( - reinterpret_cast::Type::*>(flag), featureName, flagName); + request_required_feature_impl::Type>(reinterpret_cast::Type::*>(flag), featureName, + flagName); } } template template -inline void - PhysicalDevice::request_required_feature_impl(vk::Bool32 Feature::*flag, std::string const &featureName, std::string const &flagName) +inline void PhysicalDevice::request_required_feature_impl(vk::Bool32 Feature::*flag, std::string const &featureName, std::string const &flagName) { if (get_extension_features_impl().*flag) { diff --git a/framework/core/pipeline.cpp b/framework/core/pipeline.cpp index e5efb129b7..7ca1b368f8 100644 --- a/framework/core/pipeline.cpp +++ b/framework/core/pipeline.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -24,14 +24,10 @@ namespace vkb { -Pipeline::Pipeline(vkb::core::DeviceC &device) : - device{device} +Pipeline::Pipeline(vkb::core::DeviceC &device) : device{device} {} -Pipeline::Pipeline(Pipeline &&other) : - device{other.device}, - handle{other.handle}, - state{other.state} +Pipeline::Pipeline(Pipeline &&other) : device{other.device}, handle{other.handle}, state{other.state} { other.handle = VK_NULL_HANDLE; } @@ -55,10 +51,7 @@ const PipelineState &Pipeline::get_state() const return state; } -ComputePipeline::ComputePipeline(vkb::core::DeviceC &device, - VkPipelineCache pipeline_cache, - PipelineState &pipeline_state) : - Pipeline{device} +ComputePipeline::ComputePipeline(vkb::core::DeviceC &device, VkPipelineCache pipeline_cache, PipelineState &pipeline_state) : Pipeline{device} { const ShaderModule *shader_module = pipeline_state.get_pipeline_layout().get_shader_modules().front(); @@ -84,8 +77,7 @@ ComputePipeline::ComputePipeline(vkb::core::DeviceC &device, throw VulkanException{result}; } - device.get_debug_utils().set_debug_name(device.get_handle(), - VK_OBJECT_TYPE_SHADER_MODULE, reinterpret_cast(stage.module), + device.get_debug_utils().set_debug_name(device.get_handle(), VK_OBJECT_TYPE_SHADER_MODULE, reinterpret_cast(stage.module), shader_module->get_debug_name().c_str()); // Create specialization info from tracked state. @@ -123,10 +115,7 @@ ComputePipeline::ComputePipeline(vkb::core::DeviceC &device, vkDestroyShaderModule(device.get_handle(), stage.module, nullptr); } -GraphicsPipeline::GraphicsPipeline(vkb::core::DeviceC &device, - VkPipelineCache pipeline_cache, - PipelineState &pipeline_state) : - Pipeline{device} +GraphicsPipeline::GraphicsPipeline(vkb::core::DeviceC &device, VkPipelineCache pipeline_cache, PipelineState &pipeline_state) : Pipeline{device} { std::vector shader_modules; @@ -169,8 +158,7 @@ GraphicsPipeline::GraphicsPipeline(vkb::core::DeviceC &device, throw VulkanException{result}; } - device.get_debug_utils().set_debug_name(device.get_handle(), - VK_OBJECT_TYPE_SHADER_MODULE, reinterpret_cast(stage_create_info.module), + device.get_debug_utils().set_debug_name(device.get_handle(), VK_OBJECT_TYPE_SHADER_MODULE, reinterpret_cast(stage_create_info.module), shader_module->get_debug_name().c_str()); stage_create_info.pSpecializationInfo = &specialization_info; @@ -251,24 +239,18 @@ GraphicsPipeline::GraphicsPipeline(vkb::core::DeviceC &device, VkPipelineColorBlendStateCreateInfo color_blend_state{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - color_blend_state.logicOpEnable = pipeline_state.get_color_blend_state().logic_op_enable; - color_blend_state.logicOp = pipeline_state.get_color_blend_state().logic_op; - color_blend_state.attachmentCount = to_u32(pipeline_state.get_color_blend_state().attachments.size()); - color_blend_state.pAttachments = reinterpret_cast(pipeline_state.get_color_blend_state().attachments.data()); + color_blend_state.logicOpEnable = pipeline_state.get_color_blend_state().logic_op_enable; + color_blend_state.logicOp = pipeline_state.get_color_blend_state().logic_op; + color_blend_state.attachmentCount = to_u32(pipeline_state.get_color_blend_state().attachments.size()); + color_blend_state.pAttachments = reinterpret_cast(pipeline_state.get_color_blend_state().attachments.data()); color_blend_state.blendConstants[0] = 1.0f; color_blend_state.blendConstants[1] = 1.0f; color_blend_state.blendConstants[2] = 1.0f; color_blend_state.blendConstants[3] = 1.0f; std::array dynamic_states{ - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_LINE_WIDTH, - VK_DYNAMIC_STATE_DEPTH_BIAS, - VK_DYNAMIC_STATE_BLEND_CONSTANTS, - VK_DYNAMIC_STATE_DEPTH_BOUNDS, - VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, - VK_DYNAMIC_STATE_STENCIL_WRITE_MASK, + VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH, VK_DYNAMIC_STATE_DEPTH_BIAS, + VK_DYNAMIC_STATE_BLEND_CONSTANTS, VK_DYNAMIC_STATE_DEPTH_BOUNDS, VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, VK_DYNAMIC_STATE_STENCIL_WRITE_MASK, VK_DYNAMIC_STATE_STENCIL_REFERENCE, }; diff --git a/framework/core/pipeline.h b/framework/core/pipeline.h index 89e3f19010..36cdf85728 100644 --- a/framework/core/pipeline.h +++ b/framework/core/pipeline.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -57,9 +57,7 @@ class ComputePipeline : public Pipeline virtual ~ComputePipeline() = default; - ComputePipeline(vkb::core::DeviceC &device, - VkPipelineCache pipeline_cache, - PipelineState &pipeline_state); + ComputePipeline(vkb::core::DeviceC &device, VkPipelineCache pipeline_cache, PipelineState &pipeline_state); }; class GraphicsPipeline : public Pipeline @@ -69,8 +67,6 @@ class GraphicsPipeline : public Pipeline virtual ~GraphicsPipeline() = default; - GraphicsPipeline(vkb::core::DeviceC &device, - VkPipelineCache pipeline_cache, - PipelineState &pipeline_state); + GraphicsPipeline(vkb::core::DeviceC &device, VkPipelineCache pipeline_cache, PipelineState &pipeline_state); }; } // namespace vkb diff --git a/framework/core/pipeline_layout.cpp b/framework/core/pipeline_layout.cpp index 7035f26ea3..37efc58e58 100644 --- a/framework/core/pipeline_layout.cpp +++ b/framework/core/pipeline_layout.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -25,9 +25,7 @@ namespace vkb { -PipelineLayout::PipelineLayout(vkb::core::DeviceC &device, const std::vector &shader_modules) : - device{device}, - shader_modules{shader_modules} +PipelineLayout::PipelineLayout(vkb::core::DeviceC &device, const std::vector &shader_modules) : device{device}, shader_modules{shader_modules} { // Collect and combine all the shader resources from each of the shader modules // Collate them all into a map that is indexed by the name of the resource @@ -82,7 +80,8 @@ PipelineLayout::PipelineLayout(vkb::core::DeviceC &device, const std::vector &get_shader_modules() const; - const std::vector get_resources(const ShaderResourceType &type = ShaderResourceType::All, VkShaderStageFlagBits stage = VK_SHADER_STAGE_ALL) const; + const std::vector get_resources(const ShaderResourceType &type = ShaderResourceType::All, + VkShaderStageFlagBits stage = VK_SHADER_STAGE_ALL) const; const std::unordered_map> &get_shader_sets() const; diff --git a/framework/core/query_pool.cpp b/framework/core/query_pool.cpp index 151ca4cc86..4e09505b66 100644 --- a/framework/core/query_pool.cpp +++ b/framework/core/query_pool.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Broadcom Inc. and Contributors +/* Copyright (c) 2020-2026, Broadcom Inc. and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,15 +21,12 @@ namespace vkb { -QueryPool::QueryPool(vkb::core::DeviceC &d, const VkQueryPoolCreateInfo &info) : - device{d} +QueryPool::QueryPool(vkb::core::DeviceC &d, const VkQueryPoolCreateInfo &info) : device{d} { VK_CHECK(vkCreateQueryPool(device.get_handle(), &info, nullptr, &handle)); } -QueryPool::QueryPool(QueryPool &&other) : - device{other.device}, - handle{other.handle} +QueryPool::QueryPool(QueryPool &&other) : device{other.device}, handle{other.handle} { other.handle = VK_NULL_HANDLE; } @@ -50,18 +47,14 @@ VkQueryPool QueryPool::get_handle() const void QueryPool::host_reset(uint32_t first_query, uint32_t query_count) { - assert(device.is_extension_enabled("VK_EXT_host_query_reset") && - "VK_EXT_host_query_reset needs to be enabled to call QueryPool::host_reset"); + assert(device.is_extension_enabled("VK_EXT_host_query_reset") && "VK_EXT_host_query_reset needs to be enabled to call QueryPool::host_reset"); vkResetQueryPoolEXT(device.get_handle(), get_handle(), first_query, query_count); } -VkResult QueryPool::get_results(uint32_t first_query, uint32_t num_queries, - size_t result_bytes, void *results, VkDeviceSize stride, - VkQueryResultFlags flags) +VkResult QueryPool::get_results(uint32_t first_query, uint32_t num_queries, size_t result_bytes, void *results, VkDeviceSize stride, VkQueryResultFlags flags) { - return vkGetQueryPoolResults(device.get_handle(), get_handle(), first_query, num_queries, - result_bytes, results, stride, flags); + return vkGetQueryPoolResults(device.get_handle(), get_handle(), first_query, num_queries, result_bytes, results, stride, flags); } } // namespace vkb diff --git a/framework/core/query_pool.h b/framework/core/query_pool.h index a60b333c97..f878912a77 100644 --- a/framework/core/query_pool.h +++ b/framework/core/query_pool.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Broadcom Inc. and Contributors +/* Copyright (c) 2020-2026, Broadcom Inc. and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -73,9 +73,7 @@ class QueryPool * @param stride The stride in bytes between results for individual queries * @param flags A bitmask of VkQueryResultFlagBits */ - VkResult get_results(uint32_t first_query, uint32_t num_queries, - size_t result_bytes, void *results, VkDeviceSize stride, - VkQueryResultFlags flags); + VkResult get_results(uint32_t first_query, uint32_t num_queries, size_t result_bytes, void *results, VkDeviceSize stride, VkQueryResultFlags flags); private: vkb::core::DeviceC &device; diff --git a/framework/core/render_pass.cpp b/framework/core/render_pass.cpp index 6d2e757db6..d80d0294ec 100644 --- a/framework/core/render_pass.cpp +++ b/framework/core/render_pass.cpp @@ -67,12 +67,16 @@ inline void set_structure_type(VkSubpassDescription2KHR &description) description.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2_KHR; } -inline void set_pointer_next(VkSubpassDescription &subpass_description, VkSubpassDescriptionDepthStencilResolveKHR &depth_resolve, VkAttachmentReference &depth_resolve_attachment) +inline void set_pointer_next(VkSubpassDescription &subpass_description, + VkSubpassDescriptionDepthStencilResolveKHR &depth_resolve, + VkAttachmentReference &depth_resolve_attachment) { // VkSubpassDescription cannot have pNext point to a VkSubpassDescriptionDepthStencilResolveKHR containing a VkAttachmentReference } -inline void set_pointer_next(VkSubpassDescription2KHR &subpass_description, VkSubpassDescriptionDepthStencilResolveKHR &depth_resolve, VkAttachmentReference2KHR &depth_resolve_attachment) +inline void set_pointer_next(VkSubpassDescription2KHR &subpass_description, + VkSubpassDescriptionDepthStencilResolveKHR &depth_resolve, + VkAttachmentReference2KHR &depth_resolve_attachment) { depth_resolve.pDepthStencilResolveAttachment = &depth_resolve_attachment; subpass_description.pNext = &depth_resolve; @@ -252,24 +256,17 @@ template bool is_depth_a_dependency(std::vector &subpass_descriptions, std::vector &attachment_descriptions) { // More than 1 subpass uses depth - if (std::ranges::count_if(subpass_descriptions, - [](auto const &subpass) { - return subpass.pDepthStencilAttachment != nullptr; - }) > 1) + if (std::ranges::count_if(subpass_descriptions, [](auto const &subpass) { return subpass.pDepthStencilAttachment != nullptr; }) > 1) { return true; } // Otherwise check if any uses depth as an input - return std::ranges::any_of( - subpass_descriptions, - [&attachment_descriptions](auto const &subpass) { - return std::ranges::any_of( - std::span{subpass.pInputAttachments, subpass.inputAttachmentCount}, - [&attachment_descriptions](auto const &reference) { - return vkb::is_depth_format(attachment_descriptions[reference.attachment].format); - }); - }); + return std::ranges::any_of(subpass_descriptions, [&attachment_descriptions](auto const &subpass) { + return std::ranges::any_of(std::span{subpass.pInputAttachments, subpass.inputAttachmentCount}, [&attachment_descriptions](auto const &reference) { + return vkb::is_depth_format(attachment_descriptions[reference.attachment].format); + }); + }); return false; } @@ -296,12 +293,14 @@ std::vector get_subpass_dependencies(const size_t subpass_count, bool depth_s if (depth_stencil_dependency) { T depth_dep{}; - depth_dep.srcSubpass = subpass_id; - depth_dep.dstSubpass = subpass_id + 1; - depth_dep.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - depth_dep.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - depth_dep.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - depth_dep.dstAccessMask = VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + depth_dep.srcSubpass = subpass_id; + depth_dep.dstSubpass = subpass_id + 1; + depth_dep.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + depth_dep.dstStageMask = + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; + depth_dep.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + depth_dep.dstAccessMask = + VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; depth_dep.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; dependencies.push_back(depth_dep); } @@ -323,8 +322,14 @@ T get_attachment_reference(const uint32_t attachment, const VkImageLayout layout return reference; } -template -void RenderPass::create_renderpass(const std::vector &attachments, const std::vector &load_store_infos, const std::vector &subpasses) +template +void RenderPass::create_renderpass(const std::vector &attachments, + const std::vector &load_store_infos, + const std::vector &subpasses) { if (attachments.size() != load_store_infos.size()) { @@ -359,7 +364,8 @@ void RenderPass::create_renderpass(const std::vector(i_attachment, initial_layout)); } for (auto r_attachment : subpass.color_resolve_attachments) { - auto initial_layout = attachments[r_attachment].initial_layout == VK_IMAGE_LAYOUT_UNDEFINED ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : attachments[r_attachment].initial_layout; + auto initial_layout = attachments[r_attachment].initial_layout == VK_IMAGE_LAYOUT_UNDEFINED ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : + attachments[r_attachment].initial_layout; color_resolve_attachments[i].push_back(get_attachment_reference(r_attachment, initial_layout)); } if (!subpass.disable_depth_stencil_attachment) { // Assumption: depth stencil attachment appears in the list before any depth stencil resolve attachment - auto it = find_if(attachments.begin(), attachments.end(), [](const vkb::rendering::AttachmentC attachment) { return is_depth_format(attachment.format); }); + auto it = find_if(attachments.begin(), attachments.end(), + [](const vkb::rendering::AttachmentC attachment) { return is_depth_format(attachment.format); }); if (it != attachments.end()) { auto i_depth_stencil = vkb::to_u32(std::distance(attachments.begin(), it)); @@ -393,7 +402,9 @@ void RenderPass::create_renderpass(const std::vector(i_depth_stencil_resolve, initial_layout)); } } @@ -470,7 +481,8 @@ void RenderPass::create_renderpass(const std::vector(default_depth_stencil_attachment, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)); + depth_stencil_attachments[0].push_back( + get_attachment_reference(default_depth_stencil_attachment, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)); subpass_description.pDepthStencilAttachment = depth_stencil_attachments[0].data(); } @@ -486,7 +498,8 @@ void RenderPass::create_renderpass(const std::vector(subpass_count, is_depth_a_dependency(subpass_descriptions, attachment_descriptions)); + const auto &subpass_dependencies = + get_subpass_dependencies(subpass_count, is_depth_a_dependency(subpass_descriptions, attachment_descriptions)); T_RenderPassCreateInfo create_info{}; set_structure_type(create_info); @@ -514,13 +527,14 @@ RenderPass::RenderPass(vkb::core::DeviceC &device, const std::vector &attachments, const std::vector &load_store_infos, const std::vector &subpasses) : - VulkanResource{VK_NULL_HANDLE, &device}, subpass_count{std::max(1, subpasses.size())}, // At least 1 subpass + VulkanResource{VK_NULL_HANDLE, &device}, + subpass_count{std::max(1, subpasses.size())}, // At least 1 subpass color_output_count{} { if (device.is_extension_enabled(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) { - create_renderpass( - attachments, load_store_infos, subpasses); + create_renderpass(attachments, load_store_infos, subpasses); } else { @@ -529,10 +543,7 @@ RenderPass::RenderPass(vkb::core::DeviceC &device, } } -RenderPass::RenderPass(RenderPass &&other) : - VulkanResource{std::move(other)}, - subpass_count{other.subpass_count}, - color_output_count{other.color_output_count} +RenderPass::RenderPass(RenderPass &&other) : VulkanResource{std::move(other)}, subpass_count{other.subpass_count}, color_output_count{other.color_output_count} {} RenderPass::~RenderPass() diff --git a/framework/core/render_pass.h b/framework/core/render_pass.h index f8298dc333..1556d50e15 100644 --- a/framework/core/render_pass.h +++ b/framework/core/render_pass.h @@ -77,8 +77,14 @@ class RenderPass : public vkb::core::VulkanResourceC private: size_t subpass_count; - template - void create_renderpass(const std::vector &attachments, const std::vector &load_store_infos, const std::vector &subpasses); + template + void create_renderpass(const std::vector &attachments, + const std::vector &load_store_infos, + const std::vector &subpasses); std::vector color_output_count; }; diff --git a/framework/core/sampled_image.cpp b/framework/core/sampled_image.cpp index 4ea07fc256..e043d59986 100644 --- a/framework/core/sampled_image.cpp +++ b/framework/core/sampled_image.cpp @@ -24,19 +24,11 @@ namespace vkb namespace core { SampledImage::SampledImage(const core::ImageView &image_view, Sampler *sampler) : - image_view{&image_view}, - target_attachment{0}, - render_target{nullptr}, - sampler{sampler}, - isDepthResolve{false} + image_view{&image_view}, target_attachment{0}, render_target{nullptr}, sampler{sampler}, isDepthResolve{false} {} SampledImage::SampledImage(uint32_t target_attachment, vkb::rendering::RenderTargetC *render_target, Sampler *sampler, bool isDepthResolve) : - image_view{nullptr}, - target_attachment{target_attachment}, - render_target{render_target}, - sampler{sampler}, - isDepthResolve{isDepthResolve} + image_view{nullptr}, target_attachment{target_attachment}, render_target{render_target}, sampler{sampler}, isDepthResolve{isDepthResolve} {} SampledImage::SampledImage(const SampledImage &to_copy) : diff --git a/framework/core/sampler_core.cpp b/framework/core/sampler_core.cpp index 21ff8bd450..9df0e9afa7 100644 --- a/framework/core/sampler_core.cpp +++ b/framework/core/sampler_core.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -23,16 +23,13 @@ namespace vkb { namespace core { -Sampler::Sampler(vkb::core::DeviceC &d, const VkSamplerCreateInfo &info) : - VulkanResource{VK_NULL_HANDLE, &d} +Sampler::Sampler(vkb::core::DeviceC &d, const VkSamplerCreateInfo &info) : VulkanResource{VK_NULL_HANDLE, &d} { VK_CHECK(vkCreateSampler(get_device().get_handle(), &info, nullptr, &get_handle())); } -Sampler::Sampler(Sampler &&other) : - VulkanResource{std::move(other)} -{ -} +Sampler::Sampler(Sampler &&other) : VulkanResource{std::move(other)} +{} Sampler::~Sampler() { diff --git a/framework/core/shader_module.cpp b/framework/core/shader_module.cpp index 9dc4c38213..c8cdf28ace 100644 --- a/framework/core/shader_module.cpp +++ b/framework/core/shader_module.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -47,8 +47,7 @@ ShaderModule::ShaderModule(vkb::core::DeviceC &device, // Generate a unique id, determined by source and variant std::hash hasher{}; - id = hasher(std::string{reinterpret_cast(spirv.data()), - reinterpret_cast(spirv.data() + spirv.size())}); + id = hasher(std::string{reinterpret_cast(spirv.data()), reinterpret_cast(spirv.data() + spirv.size())}); } ShaderModule::ShaderModule(ShaderModule &&other) : @@ -149,9 +148,7 @@ void ShaderVariant::clear() id = 0; } -ShaderSource::ShaderSource(const std::string &filename) : - filename{filename}, - source{fs::read_text_file(filename)} +ShaderSource::ShaderSource(const std::string &filename) : filename{filename}, source{fs::read_text_file(filename)} { std::hash hasher{}; id = hasher(std::string{this->source.cbegin(), this->source.cend()}); diff --git a/framework/core/swapchain.cpp b/framework/core/swapchain.cpp index 271ef5e759..83fbeb3b98 100644 --- a/framework/core/swapchain.cpp +++ b/framework/core/swapchain.cpp @@ -25,10 +25,7 @@ namespace vkb { namespace { -inline uint32_t choose_image_count( - uint32_t request_image_count, - uint32_t min_image_count, - uint32_t max_image_count) +inline uint32_t choose_image_count(uint32_t request_image_count, uint32_t min_image_count, uint32_t max_image_count) { if (max_image_count != 0) { @@ -40,9 +37,7 @@ inline uint32_t choose_image_count( return request_image_count; } -inline uint32_t choose_image_array_layers( - uint32_t request_image_array_layers, - uint32_t max_image_array_layers) +inline uint32_t choose_image_array_layers(uint32_t request_image_array_layers, uint32_t max_image_array_layers) { request_image_array_layers = std::min(request_image_array_layers, max_image_array_layers); request_image_array_layers = std::max(request_image_array_layers, 1u); @@ -50,11 +45,8 @@ inline uint32_t choose_image_array_layers( return request_image_array_layers; } -inline VkExtent2D choose_extent( - VkExtent2D request_extent, - const VkExtent2D &min_image_extent, - const VkExtent2D &max_image_extent, - const VkExtent2D ¤t_extent) +inline VkExtent2D + choose_extent(VkExtent2D request_extent, const VkExtent2D &min_image_extent, const VkExtent2D &max_image_extent, const VkExtent2D ¤t_extent) { if (current_extent.width == 0xFFFFFFFF) { @@ -63,7 +55,8 @@ inline VkExtent2D choose_extent( if (request_extent.width < 1 || request_extent.height < 1) { - LOGW("(Swapchain) Image extent ({}, {}) not supported. Selecting ({}, {}).", request_extent.width, request_extent.height, current_extent.width, current_extent.height); + LOGW("(Swapchain) Image extent ({}, {}) not supported. Selecting ({}, {}).", request_extent.width, request_extent.height, current_extent.width, + current_extent.height); return current_extent; } @@ -76,10 +69,9 @@ inline VkExtent2D choose_extent( return request_extent; } -inline VkPresentModeKHR choose_present_mode( - VkPresentModeKHR request_present_mode, - const std::vector &available_present_modes, - const std::vector &present_mode_priority_list) +inline VkPresentModeKHR choose_present_mode(VkPresentModeKHR request_present_mode, + const std::vector &available_present_modes, + const std::vector &present_mode_priority_list) { auto present_mode_it = std::ranges::find(available_present_modes, request_present_mode); @@ -107,40 +99,33 @@ inline VkPresentModeKHR choose_present_mode( } } -inline VkSurfaceFormatKHR choose_surface_format( - const VkSurfaceFormatKHR requested_surface_format, - const std::vector &available_surface_formats, - const std::vector &surface_format_priority_list) +inline VkSurfaceFormatKHR choose_surface_format(const VkSurfaceFormatKHR requested_surface_format, + const std::vector &available_surface_formats, + const std::vector &surface_format_priority_list) { // Try to find the requested surface format in the supported surface formats - auto surface_format_it = std::ranges::find_if( - available_surface_formats, - [&requested_surface_format](const VkSurfaceFormatKHR &surface) { - if (surface.format == requested_surface_format.format && - surface.colorSpace == requested_surface_format.colorSpace) - { - return true; - } - - return false; - }); + auto surface_format_it = std::ranges::find_if(available_surface_formats, [&requested_surface_format](const VkSurfaceFormatKHR &surface) { + if (surface.format == requested_surface_format.format && surface.colorSpace == requested_surface_format.colorSpace) + { + return true; + } + + return false; + }); // If the requested surface format isn't found, then try to request a format from the priority list if (surface_format_it == available_surface_formats.end()) { for (auto &surface_format : surface_format_priority_list) { - surface_format_it = std::ranges::find_if( - available_surface_formats, - [&surface_format](const VkSurfaceFormatKHR &surface) { - if (surface.format == surface_format.format && - surface.colorSpace == surface_format.colorSpace) - { - return true; - } - - return false; - }); + surface_format_it = std::ranges::find_if(available_surface_formats, [&surface_format](const VkSurfaceFormatKHR &surface) { + if (surface.format == surface_format.format && surface.colorSpace == surface_format.colorSpace) + { + return true; + } + + return false; + }); if (surface_format_it != available_surface_formats.end()) { LOGW("(Swapchain) Surface format ({}) not supported. Selecting ({}).", to_string(requested_surface_format), to_string(*surface_format_it)); @@ -160,10 +145,9 @@ inline VkSurfaceFormatKHR choose_surface_format( return *surface_format_it; } -inline VkSurfaceTransformFlagBitsKHR choose_transform( - VkSurfaceTransformFlagBitsKHR request_transform, - VkSurfaceTransformFlagsKHR supported_transform, - VkSurfaceTransformFlagBitsKHR current_transform) +inline VkSurfaceTransformFlagBitsKHR choose_transform(VkSurfaceTransformFlagBitsKHR request_transform, + VkSurfaceTransformFlagsKHR supported_transform, + VkSurfaceTransformFlagBitsKHR current_transform) { if (request_transform & supported_transform) { @@ -175,18 +159,17 @@ inline VkSurfaceTransformFlagBitsKHR choose_transform( return current_transform; } -inline VkCompositeAlphaFlagBitsKHR choose_composite_alpha(VkCompositeAlphaFlagBitsKHR request_composite_alpha, VkCompositeAlphaFlagsKHR supported_composite_alpha) +inline VkCompositeAlphaFlagBitsKHR choose_composite_alpha(VkCompositeAlphaFlagBitsKHR request_composite_alpha, + VkCompositeAlphaFlagsKHR supported_composite_alpha) { if (request_composite_alpha & supported_composite_alpha) { return request_composite_alpha; } - static const std::vector composite_alpha_flags = { - VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, - VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, - VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, - VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR}; + static const std::vector composite_alpha_flags = {VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, + VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, + VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR}; for (VkCompositeAlphaFlagBitsKHR composite_alpha : composite_alpha_flags) { @@ -211,7 +194,9 @@ inline bool validate_format_feature(VkImageUsageFlagBits image_usage, VkFormatFe } } -inline std::set choose_image_usage(const std::set &requested_image_usage_flags, VkImageUsageFlags supported_image_usage, VkFormatFeatureFlags supported_features) +inline std::set choose_image_usage(const std::set &requested_image_usage_flags, + VkImageUsageFlags supported_image_usage, + VkFormatFeatureFlags supported_features) { std::set validated_image_usage_flags; for (auto flag : requested_image_usage_flags) @@ -229,11 +214,8 @@ inline std::set choose_image_usage(const std::set image_usage_flags = { - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, - VK_IMAGE_USAGE_STORAGE_BIT, - VK_IMAGE_USAGE_SAMPLED_BIT, - VK_IMAGE_USAGE_TRANSFER_DST_BIT}; + static const std::vector image_usage_flags = {VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_USAGE_STORAGE_BIT, + VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_USAGE_TRANSFER_DST_BIT}; for (VkImageUsageFlagBits image_usage : image_usage_flags) { @@ -335,7 +317,9 @@ Swapchain::Swapchain(Swapchain &old_swapchain, const VkExtent2D &extent, const V old_swapchain.requested_compression_fixed_rate} {} -Swapchain::Swapchain(Swapchain &old_swapchain, const VkImageCompressionFlagsEXT requested_compression, const VkImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate) : +Swapchain::Swapchain(Swapchain &old_swapchain, + const VkImageCompressionFlagsEXT requested_compression, + const VkImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate) : Swapchain{old_swapchain, old_swapchain.device, old_swapchain.surface, @@ -362,8 +346,7 @@ Swapchain::Swapchain(vkb::core::DeviceC &device, const VkImageCompressionFlagsEXT requested_compression, const VkImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate) : Swapchain{*this, device, surface, present_mode, present_mode_priority_list, surface_format_priority_list, extent, image_count, transform, image_usage_flags} -{ -} +{} Swapchain::Swapchain(Swapchain &old_swapchain, vkb::core::DeviceC &device, @@ -377,10 +360,7 @@ Swapchain::Swapchain(Swapchain &old_swapchain, const std::set &image_usage_flags, const VkImageCompressionFlagsEXT requested_compression, const VkImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate) : - device{device}, - surface{surface}, - requested_compression{requested_compression}, - requested_compression_fixed_rate{requested_compression_fixed_rate} + device{device}, surface{surface}, requested_compression{requested_compression}, requested_compression_fixed_rate{requested_compression_fixed_rate} { this->present_mode_priority_list = present_mode_priority_list; this->surface_format_priority_list = surface_format_priority_list; @@ -413,9 +393,9 @@ Swapchain::Swapchain(Swapchain &old_swapchain, } // Choose best properties based on surface capabilities - properties.old_swapchain = old_swapchain.get_handle(); - properties.image_count = choose_image_count(image_count, surface_capabilities.minImageCount, surface_capabilities.maxImageCount); - properties.extent = choose_extent(extent, surface_capabilities.minImageExtent, surface_capabilities.maxImageExtent, surface_capabilities.currentExtent); + properties.old_swapchain = old_swapchain.get_handle(); + properties.image_count = choose_image_count(image_count, surface_capabilities.minImageCount, surface_capabilities.maxImageCount); + properties.extent = choose_extent(extent, surface_capabilities.minImageExtent, surface_capabilities.maxImageExtent, surface_capabilities.currentExtent); properties.surface_format = choose_surface_format(properties.surface_format, surface_formats, surface_format_priority_list); properties.array_layers = choose_image_array_layers(1U, surface_capabilities.maxImageArrayLayers); @@ -505,8 +485,7 @@ Swapchain::Swapchain(Swapchain &old_swapchain, } else { - LOGI("(Swapchain) Applied fixed-rate compression: {}", - image_compression_fixed_rate_flags_to_string(applied_compression_fixed_rate)); + LOGI("(Swapchain) Applied fixed-rate compression: {}", image_compression_fixed_rate_flags_to_string(applied_compression_fixed_rate)); } } } @@ -528,8 +507,7 @@ Swapchain::Swapchain(Swapchain &&other) : present_mode_priority_list{std::exchange(other.present_mode_priority_list, {})}, surface_format_priority_list{std::exchange(other.surface_format_priority_list, {})}, image_usage_flags{std::move(other.image_usage_flags)} -{ -} +{} bool Swapchain::is_valid() const { diff --git a/framework/core/swapchain.h b/framework/core/swapchain.h index eacb7590b6..c4ff9b970b 100644 --- a/framework/core/swapchain.h +++ b/framework/core/swapchain.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -79,7 +79,9 @@ class Swapchain * @brief Constructor to create a swapchain by changing the compression settings * only and preserving the configuration from the old swapchain. */ - Swapchain(Swapchain &swapchain, const VkImageCompressionFlagsEXT requested_compression, const VkImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate); + Swapchain(Swapchain &swapchain, + const VkImageCompressionFlagsEXT requested_compression, + const VkImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate); /** * @brief Constructor to create a swapchain. @@ -87,15 +89,14 @@ class Swapchain Swapchain(vkb::core::DeviceC &device, VkSurfaceKHR surface, const VkPresentModeKHR present_mode, - const std::vector &present_mode_priority_list = {VK_PRESENT_MODE_FIFO_KHR, - VK_PRESENT_MODE_MAILBOX_KHR}, - const std::vector &surface_format_priority_list = {{VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}, - {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}}, - const VkExtent2D &extent = {}, - const uint32_t image_count = 3, - const VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, - const std::set &image_usage_flags = {VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT}, - const VkImageCompressionFlagsEXT requested_compression = VK_IMAGE_COMPRESSION_DEFAULT_EXT, + const std::vector &present_mode_priority_list = {VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_MAILBOX_KHR}, + const std::vector &surface_format_priority_list = {{VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}, + {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}}, + const VkExtent2D &extent = {}, + const uint32_t image_count = 3, + const VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, + const std::set &image_usage_flags = {VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT}, + const VkImageCompressionFlagsEXT requested_compression = VK_IMAGE_COMPRESSION_DEFAULT_EXT, const VkImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate = VK_IMAGE_COMPRESSION_FIXED_RATE_NONE_EXT); /** @@ -106,14 +107,14 @@ class Swapchain vkb::core::DeviceC &device, VkSurfaceKHR surface, const VkPresentModeKHR present_mode, - const std::vector &present_mode_priority_list = {VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_MAILBOX_KHR}, - const std::vector &surface_format_priority_list = {{VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}, - {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}}, - const VkExtent2D &extent = {}, - const uint32_t image_count = 3, - const VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, - const std::set &image_usage_flags = {VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT}, - const VkImageCompressionFlagsEXT requested_compression = VK_IMAGE_COMPRESSION_DEFAULT_EXT, + const std::vector &present_mode_priority_list = {VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_MAILBOX_KHR}, + const std::vector &surface_format_priority_list = {{VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}, + {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}}, + const VkExtent2D &extent = {}, + const uint32_t image_count = 3, + const VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR, + const std::set &image_usage_flags = {VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT}, + const VkImageCompressionFlagsEXT requested_compression = VK_IMAGE_COMPRESSION_DEFAULT_EXT, const VkImageCompressionFixedRateFlagsEXT requested_compression_fixed_rate = VK_IMAGE_COMPRESSION_FIXED_RATE_NONE_EXT); Swapchain(const Swapchain &) = delete; @@ -176,14 +177,11 @@ class Swapchain SwapchainProperties properties; // A list of present modes in order of priority (vector[0] has high priority, vector[size-1] has low priority) - std::vector present_mode_priority_list = { - VK_PRESENT_MODE_FIFO_KHR, - VK_PRESENT_MODE_MAILBOX_KHR}; + std::vector present_mode_priority_list = {VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_MAILBOX_KHR}; // A list of surface formats in order of priority (vector[0] has high priority, vector[size-1] has low priority) - std::vector surface_format_priority_list = { - {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}, - {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}}; + std::vector surface_format_priority_list = {{VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}, + {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}}; std::set image_usage_flags; diff --git a/framework/core/vulkan_resource.h b/framework/core/vulkan_resource.h index bae780ec53..96dcea4fd5 100644 --- a/framework/core/vulkan_resource.h +++ b/framework/core/vulkan_resource.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2021-2025, Arm Limited and Contributors - * Copyright (c) 2024-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, Arm Limited and Contributors + * Copyright (c) 2024-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -83,8 +83,7 @@ template using VulkanResourceCpp = VulkanResource; template -inline VulkanResource::VulkanResource(Handle handle_, Device *device_) : - handle{handle_} +inline VulkanResource::VulkanResource(Handle handle_, Device *device_) : handle{handle_} { if constexpr (bindingType == vkb::BindingType::Cpp) { @@ -98,9 +97,7 @@ inline VulkanResource::VulkanResource(Handle handle_, Devic template inline VulkanResource::VulkanResource(VulkanResource &&other) : - handle(std::exchange(other.handle, {})), - device(std::exchange(other.device, {})), - debug_name(std::exchange(other.debug_name, {})) + handle(std::exchange(other.handle, {})), device(std::exchange(other.device, {})), debug_name(std::exchange(other.debug_name, {})) {} template diff --git a/framework/debug_info.h b/framework/debug_info.h index d6ce26ef45..064bccdff2 100644 --- a/framework/debug_info.h +++ b/framework/debug_info.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -38,8 +38,7 @@ struct Base { std::string label; - Base(const std::string &label) : - label{label} + Base(const std::string &label) : label{label} {} virtual ~Base() = default; @@ -57,9 +56,7 @@ struct Static : public Base { T value; - Static(const std::string &label, const T &value) : - Base(label), - value{value} + Static(const std::string &label, const T &value) : Base(label), value{value} {} virtual ~Static() = default; @@ -80,9 +77,7 @@ struct Dynamic : public Base { T &value; - Dynamic(const std::string &label, T &value) : - Base(label), - value{value} + Dynamic(const std::string &label, T &value) : Base(label), value{value} {} virtual ~Dynamic() = default; @@ -103,23 +98,16 @@ struct Vector final : public Static { T x, y, z; - Vector(const std::string &label, const glm::vec3 &vec) : - Vector(label, vec.x, vec.y, vec.z) + Vector(const std::string &label, const glm::vec3 &vec) : Vector(label, vec.x, vec.y, vec.z) {} - Vector(const std::string &label, T x, T y, T z) : - Static(label, x), - x{x}, - y{y}, - z{z} + Vector(const std::string &label, T x, T y, T z) : Static(label, x), x{x}, y{y}, z{z} {} virtual ~Vector() = default; const std::string to_string() override { - return "x: " + vkb::to_string(x) + " " + - "y: " + vkb::to_string(y) + " " + - "z: " + vkb::to_string(z); + return "x: " + vkb::to_string(x) + " " + "y: " + vkb::to_string(y) + " " + "z: " + vkb::to_string(z); } }; @@ -133,10 +121,7 @@ struct MinMax final : public Dynamic { T min, max; - MinMax(const std::string &label, T &value) : - Dynamic(label, value), - min{value}, - max{value} + MinMax(const std::string &label, T &value) : Dynamic(label, value), min{value}, max{value} { static_assert(std::is_arithmetic::value, "MinMax must be templated to a numeric type."); } diff --git a/framework/drawer.h b/framework/drawer.h index 8759140027..9fa95d32c7 100644 --- a/framework/drawer.h +++ b/framework/drawer.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2024, Mobica Limited +/* Copyright (c) 2024-2026, Mobica Limited * * SPDX-License-Identifier: Apache-2.0 * @@ -96,7 +96,7 @@ class Drawer * @param precision The precision * @returns True if adding item was successful */ - bool input_float(const char *caption, float *value, float step, const char* precision); + bool input_float(const char *caption, float *value, float step, const char *precision); /** * @brief Adds a slide bar to the gui for floating points to the gui diff --git a/framework/fence_pool.cpp b/framework/fence_pool.cpp index a8d6866582..88c229c565 100644 --- a/framework/fence_pool.cpp +++ b/framework/fence_pool.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,10 +21,8 @@ namespace vkb { -FencePool::FencePool(vkb::core::DeviceC &device) : - device{device} -{ -} +FencePool::FencePool(vkb::core::DeviceC &device) : device{device} +{} FencePool::~FencePool() { diff --git a/framework/gltf_loader.cpp b/framework/gltf_loader.cpp index b7fc3859ab..141361b92c 100644 --- a/framework/gltf_loader.cpp +++ b/framework/gltf_loader.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors - * Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2018-2026, Arm Limited and Contributors + * Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -274,9 +274,7 @@ inline std::vector convert_underlying_data_stride(const std::vector result(elem_count * dst_stride); - for (uint32_t idxSrc = 0, idxDst = 0; - idxSrc < src_data.size() && idxDst < result.size(); - idxSrc += src_stride, idxDst += dst_stride) + for (uint32_t idxSrc = 0, idxDst = 0; idxSrc < src_data.size() && idxDst < result.size(); idxSrc += src_stride, idxDst += dst_stride) { std::copy(src_data.begin() + idxSrc, src_data.begin() + idxSrc + src_stride, result.begin() + idxDst); } @@ -399,13 +397,10 @@ static inline bool texture_needs_srgb_colorspace(const std::string &name) } // namespace -std::unordered_map GLTFLoader::supported_extensions = { - {KHR_LIGHTS_PUNCTUAL_EXTENSION, false}}; +std::unordered_map GLTFLoader::supported_extensions = {{KHR_LIGHTS_PUNCTUAL_EXTENSION, false}}; -GLTFLoader::GLTFLoader(vkb::core::DeviceC &device) : - device{device} -{ -} +GLTFLoader::GLTFLoader(vkb::core::DeviceC &device) : device{device} +{} std::unique_ptr GLTFLoader::read_scene_from_file(const std::string &file_name, int scene_index, VkBufferUsageFlags additional_buffer_usage_flags) { @@ -450,7 +445,8 @@ std::unique_ptr GLTFLoader::read_scene_from_file(const std::string &f return std::make_unique(load_scene(scene_index, additional_buffer_usage_flags)); } -std::unique_ptr GLTFLoader::read_model_from_file(const std::string &file_name, uint32_t index, bool storage_buffer, VkBufferUsageFlags additional_buffer_usage_flags) +std::unique_ptr + GLTFLoader::read_model_from_file(const std::string &file_name, uint32_t index, bool storage_buffer, VkBufferUsageFlags additional_buffer_usage_flags) { PROFILE_SCOPE("Load GLTF Model"); @@ -535,8 +531,7 @@ sg::Scene GLTFLoader::load_scene(int scene_index, VkBufferUsageFlags additional_ scene.set_components(std::move(light_components)); // Load samplers - std::vector> - sampler_components(model.samplers.size()); + std::vector> sampler_components(model.samplers.size()); for (size_t sampler_index = 0; sampler_index < model.samplers.size(); sampler_index++) { @@ -555,14 +550,13 @@ sg::Scene GLTFLoader::load_scene(int scene_index, VkBufferUsageFlags additional_ std::vector>> image_component_futures; for (size_t image_index = 0; image_index < image_count; image_index++) { - image_component_futures.push_back(std::async( - [this, image_index]() { - auto image = parse_image(model.images[image_index]); + image_component_futures.push_back(std::async([this, image_index]() { + auto image = parse_image(model.images[image_index]); - LOGI("Loaded gltf image #{} ({})", image_index, model.images[image_index].uri.c_str()); + LOGI("Loaded gltf image #{} ({})", image_index, model.images[image_index].uri.c_str()); - return image; - })); + return image; + })); } std::vector> image_components; @@ -753,13 +747,10 @@ sg::Scene GLTFLoader::load_scene(int scene_index, VkBufferUsageFlags additional_ submesh->vertices_count = to_u32(model.accessors[attribute.second].count); } - vkb::core::BufferC buffer{device, - vertex_data.size(), - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | additional_buffer_usage_flags, + vkb::core::BufferC buffer{device, vertex_data.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | additional_buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU}; buffer.update(vertex_data); - buffer.set_debug_name(fmt::format("'{}' mesh, primitive #{}: '{}' vertex buffer", - gltf_mesh.name, i_primitive, attrib_name)); + buffer.set_debug_name(fmt::format("'{}' mesh, primitive #{}: '{}' vertex buffer", gltf_mesh.name, i_primitive, attrib_name)); submesh->vertex_buffers.insert(std::make_pair(attrib_name, std::move(buffer))); @@ -796,12 +787,9 @@ sg::Scene GLTFLoader::load_scene(int scene_index, VkBufferUsageFlags additional_ break; } - submesh->index_buffer = std::make_unique(device, - index_data.size(), - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | additional_buffer_usage_flags, - VMA_MEMORY_USAGE_GPU_TO_CPU); - submesh->index_buffer->set_debug_name(fmt::format("'{}' mesh, primitive #{}: index buffer", - gltf_mesh.name, i_primitive)); + submesh->index_buffer = std::make_unique( + device, index_data.size(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT | additional_buffer_usage_flags, VMA_MEMORY_USAGE_GPU_TO_CPU); + submesh->index_buffer->set_debug_name(fmt::format("'{}' mesh, primitive #{}: index buffer", gltf_mesh.name, i_primitive)); submesh->index_buffer->update(index_data); } @@ -1185,10 +1173,8 @@ std::unique_ptr GLTFLoader::load_model(uint32_t index, bool storage vkb::core::BufferC stage_buffer = vkb::core::BufferC::create_staging_buffer(device, aligned_vertex_data); - vkb::core::BufferC buffer{device, - aligned_vertex_data.size() * sizeof(AlignedVertex), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, - VMA_MEMORY_USAGE_GPU_ONLY}; + vkb::core::BufferC buffer{device, aligned_vertex_data.size() * sizeof(AlignedVertex), + VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; command_buffer->copy_buffer(stage_buffer, buffer, aligned_vertex_data.size() * sizeof(AlignedVertex)); @@ -1228,9 +1214,7 @@ std::unique_ptr GLTFLoader::load_model(uint32_t index, bool storage vkb::core::BufferC stage_buffer = vkb::core::BufferC::create_staging_buffer(device, vertex_data); - vkb::core::BufferC buffer{device, - vertex_data.size() * sizeof(Vertex), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + vkb::core::BufferC buffer{device, vertex_data.size() * sizeof(Vertex), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; command_buffer->copy_buffer(stage_buffer, buffer, vertex_data.size() * sizeof(Vertex)); @@ -1285,10 +1269,8 @@ std::unique_ptr GLTFLoader::load_model(uint32_t index, bool storage vkb::core::BufferC stage_buffer = vkb::core::BufferC::create_staging_buffer(device, meshlets); - submesh->index_buffer = std::make_unique(device, - meshlets.size() * sizeof(Meshlet), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + submesh->index_buffer = std::make_unique( + device, meshlets.size() * sizeof(Meshlet), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY); command_buffer->copy_buffer(stage_buffer, *submesh->index_buffer, meshlets.size() * sizeof(Meshlet)); @@ -1298,10 +1280,8 @@ std::unique_ptr GLTFLoader::load_model(uint32_t index, bool storage { vkb::core::BufferC stage_buffer = vkb::core::BufferC::create_staging_buffer(device, index_data); - submesh->index_buffer = std::make_unique(device, - index_data.size(), - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + submesh->index_buffer = std::make_unique( + device, index_data.size(), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY); command_buffer->copy_buffer(stage_buffer, *submesh->index_buffer, index_data.size()); @@ -1465,13 +1445,13 @@ std::unique_ptr GLTFLoader::parse_image(tinygltf::Image &gltf_image) if (!gltf_image.image.empty()) { // Image embedded in gltf file - auto mipmap = sg::Mipmap{ - /* .level = */ 0, - /* .offset = */ 0, - /* .extent = */ {/* .width = */ static_cast(gltf_image.width), - /* .height = */ static_cast(gltf_image.height), - /* .depth = */ 1u}}; - std::vector mipmaps{mipmap}; + auto mipmap = sg::Mipmap{/* .level = */ 0, + /* .offset = */ 0, + /* .extent = */ + {/* .width = */ static_cast(gltf_image.width), + /* .height = */ static_cast(gltf_image.height), + /* .depth = */ 1u}}; + std::vector mipmaps{mipmap}; image = std::make_unique(gltf_image.name, std::move(gltf_image.image), std::move(mipmaps)); } else @@ -1614,10 +1594,9 @@ std::vector> GLTFLoader::parse_khr_lights_punctual() // Get properties if (khr_light.Has("color")) { - properties.color = glm::vec3( - static_cast(khr_light.Get("color").Get(0).Get()), - static_cast(khr_light.Get("color").Get(1).Get()), - static_cast(khr_light.Get("color").Get(2).Get())); + properties.color = + glm::vec3(static_cast(khr_light.Get("color").Get(0).Get()), static_cast(khr_light.Get("color").Get(1).Get()), + static_cast(khr_light.Get("color").Get(2).Get())); } if (khr_light.Has("intensity")) diff --git a/framework/gltf_loader.h b/framework/gltf_loader.h index 4176e96f5d..e8119ea92d 100644 --- a/framework/gltf_loader.h +++ b/framework/gltf_loader.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors - * Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2018-2026, Arm Limited and Contributors + * Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -90,7 +90,8 @@ class GLTFLoader * @brief Loads the first model from a GLTF file for use in simpler samples * makes use of the Vertex struct in vulkan_example_base.h */ - std::unique_ptr read_model_from_file(const std::string &file_name, uint32_t index, bool storage_buffer = false, VkBufferUsageFlags additional_buffer_usage_flags = 0); + std::unique_ptr + read_model_from_file(const std::string &file_name, uint32_t index, bool storage_buffer = false, VkBufferUsageFlags additional_buffer_usage_flags = 0); protected: virtual std::unique_ptr parse_node(const tinygltf::Node &gltf_node, size_t index) const; diff --git a/framework/gui.h b/framework/gui.h index d7971a4496..2e7899aa0c 100644 --- a/framework/gui.h +++ b/framework/gui.h @@ -66,8 +66,7 @@ struct Font * @param name_ The name of the font file that exists within 'assets/fonts' (without extension) * @param size_ The font size, scaled by DPI */ - Font(const std::string &name_, float size_) : - name{name_}, data{vkb::fs::read_asset("fonts/" + name + ".ttf")}, size{size_} + Font(const std::string &name_, float size_) : name{name_}, data{vkb::fs::read_asset("fonts/" + name + ".ttf")}, size{size_} { // Keep ownership of the font data to avoid a double delete ImFontConfig font_config{}; @@ -97,16 +96,17 @@ class Gui public: static inline bool visible = true; // Used to show/hide the GUI - using CommandBufferType = typename std::conditional::type; - using DescriptorSetType = typename std::conditional::type; - using FormatType = typename std::conditional::type; - using ImageViewType = typename std::conditional::type; - using PipelineType = typename std::conditional::type; - using PipelineCacheType = typename std::conditional::type; - using PipelineLayoutType = typename std::conditional::type; - using PipelineShaderStageCreateInfoType = typename std::conditional::type; - using RenderPassType = typename std::conditional::type; - using StatsType = typename std::conditional::type; + using CommandBufferType = typename std::conditional::type; + using DescriptorSetType = typename std::conditional::type; + using FormatType = typename std::conditional::type; + using ImageViewType = typename std::conditional::type; + using PipelineType = typename std::conditional::type; + using PipelineCacheType = typename std::conditional::type; + using PipelineLayoutType = typename std::conditional::type; + using PipelineShaderStageCreateInfoType = + typename std::conditional::type; + using RenderPassType = typename std::conditional::type; + using StatsType = typename std::conditional::type; public: /** @@ -230,10 +230,16 @@ class Gui void new_frame(); // Prepare with a render pass - void prepare(PipelineCacheType pipeline_cache, RenderPassType render_pass, std::vector const &shader_stages, uint32_t subpass = 0); + void prepare(PipelineCacheType pipeline_cache, + RenderPassType render_pass, + std::vector const &shader_stages, + uint32_t subpass = 0); // Prepare for dynamic rendering - void prepare(PipelineCacheType pipeline_cache, FormatType color_format, FormatType depth_format, std::vector const &shader_stages); + void prepare(PipelineCacheType pipeline_cache, + FormatType color_format, + FormatType depth_format, + std::vector const &shader_stages); /** * @brief Handles resizing of the window @@ -288,8 +294,14 @@ class Gui void draw_impl(vk::CommandBuffer command_buffer, vk::Pipeline pipeline, vk::PipelineLayout pipeline_layout, vk::DescriptorSet descriptor_set); void draw_impl(vk::CommandBuffer command_buffer, vk::ImageView swapchain_view, uint32_t width, uint32_t height); void draw_impl(vkb::core::CommandBufferCpp &command_buffer); - void prepare_impl(vk::PipelineCache pipeline_cache, vk::RenderPass render_pass, std::vector const &shader_stages, uint32_t subpass); - void prepare_impl(vk::PipelineCache pipeline_cache, vk::Format color_format, vk::Format depth_format, std::vector const &shader_stages); + void prepare_impl(vk::PipelineCache pipeline_cache, + vk::RenderPass render_pass, + std::vector const &shader_stages, + uint32_t subpass); + void prepare_impl(vk::PipelineCache pipeline_cache, + vk::Format color_format, + vk::Format depth_format, + std::vector const &shader_stages); void prepare_descriptors(); void create_gui_pipeline(vk::PipelineCache pipeline_cache, std::vector const &shader_stages, @@ -322,16 +334,16 @@ class Gui void upload_draw_data(const ImDrawData *draw_data, uint8_t *vertex_data, uint8_t *index_data); private: - float content_scale_factor = 1.0f; // Scale factor to apply due to a difference between the window and GL pixel sizes - DebugView debug_view; - vk::DescriptorPool descriptor_pool; - vk::DescriptorSet descriptor_set; - vk::DescriptorSetLayout descriptor_set_layout; - float dpi_factor = 1.0f; // Scale factor to apply to the size of gui elements (expressed in dp) - Drawer drawer; - bool explicit_update = false; - std::vector fonts; - std::unique_ptr font_image; + float content_scale_factor = 1.0f; // Scale factor to apply due to a difference between the window and GL pixel sizes + DebugView debug_view; + vk::DescriptorPool descriptor_pool; + vk::DescriptorSet descriptor_set; + vk::DescriptorSetLayout descriptor_set_layout; + float dpi_factor = 1.0f; // Scale factor to apply to the size of gui elements (expressed in dp) + Drawer drawer; + bool explicit_update = false; + std::vector fonts; + std::unique_ptr font_image; std::unique_ptr font_image_view; std::unique_ptr index_buffer; vk::Pipeline pipeline; @@ -422,8 +434,7 @@ inline Gui::Gui( vk::Extent3D font_extent{to_u32(tex_width), to_u32(tex_height), 1u}; font_image = std::make_unique(device, font_extent, vk::Format::eR8G8B8A8Unorm, - vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst, - VMA_MEMORY_USAGE_GPU_ONLY); + vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst, VMA_MEMORY_USAGE_GPU_ONLY); font_image->set_debug_name("GUI font image"); font_image_view = std::make_unique(*font_image, vk::ImageViewType::e2D); @@ -515,7 +526,8 @@ inline Gui::Gui( std::make_unique(render_context.get_device(), 1, vk::BufferUsageFlagBits::eVertexBuffer, VMA_MEMORY_USAGE_GPU_TO_CPU); vertex_buffer->set_debug_name("GUI vertex buffer"); - index_buffer = std::make_unique(render_context.get_device(), 1, vk::BufferUsageFlagBits::eIndexBuffer, VMA_MEMORY_USAGE_GPU_TO_CPU); + index_buffer = + std::make_unique(render_context.get_device(), 1, vk::BufferUsageFlagBits::eIndexBuffer, VMA_MEMORY_USAGE_GPU_TO_CPU); index_buffer->set_debug_name("GUI index buffer"); } } @@ -546,10 +558,7 @@ inline void Gui::draw(CommandBufferType command_buffer, ImageViewTy } else { - draw_impl(static_cast(command_buffer), - static_cast(swapchain_view), - width, - height); + draw_impl(static_cast(command_buffer), static_cast(swapchain_view), width, height); } } @@ -562,17 +571,13 @@ inline void Gui::draw_impl(vk::CommandBuffer command_buffer, vk::Im } // Set up the color attachment for UI rendering - vk::RenderingAttachmentInfoKHR color_attachment{ - .imageView = swapchain_view, - .imageLayout = vk::ImageLayout::eColorAttachmentOptimal, - .loadOp = vk::AttachmentLoadOp::eLoad, // Preserve existing content - .storeOp = vk::AttachmentStoreOp::eStore}; + vk::RenderingAttachmentInfoKHR color_attachment{.imageView = swapchain_view, + .imageLayout = vk::ImageLayout::eColorAttachmentOptimal, + .loadOp = vk::AttachmentLoadOp::eLoad, // Preserve existing content + .storeOp = vk::AttachmentStoreOp::eStore}; vk::RenderingInfoKHR rendering_info{ - .renderArea = {{0, 0}, {width, height}}, - .layerCount = 1, - .colorAttachmentCount = 1, - .pColorAttachments = &color_attachment}; + .renderArea = {{0, 0}, {width, height}}, .layerCount = 1, .colorAttachmentCount = 1, .pColorAttachments = &color_attachment}; command_buffer.beginRenderingKHR(rendering_info); @@ -591,9 +596,7 @@ inline void } else { - draw_impl(static_cast(command_buffer), - static_cast(pipeline), - static_cast(pipeline_layout), + draw_impl(static_cast(command_buffer), static_cast(pipeline), static_cast(pipeline_layout), static_cast(descriptor_set)); } } @@ -897,8 +900,7 @@ inline bool Gui::input_event(const InputEvent &input_event) { const auto &mouse_button = static_cast(input_event); - io.MousePos = ImVec2{mouse_button.get_pos_x() * content_scale_factor, - mouse_button.get_pos_y() * content_scale_factor}; + io.MousePos = ImVec2{mouse_button.get_pos_x() * content_scale_factor, mouse_button.get_pos_y() * content_scale_factor}; auto button_id = static_cast(mouse_button.get_button()); @@ -1014,10 +1016,8 @@ inline void Gui::prepare(PipelineCacheType } else { - prepare_impl(static_cast(pipeline_cache), - static_cast(render_pass), - reinterpret_cast const &>(shader_stages), - subpass); + prepare_impl(static_cast(pipeline_cache), static_cast(render_pass), + reinterpret_cast const &>(shader_stages), subpass); } } @@ -1033,9 +1033,7 @@ inline void Gui::prepare(PipelineCacheType } else { - prepare_impl(static_cast(pipeline_cache), - static_cast(color_format), - static_cast(depth_format), + prepare_impl(static_cast(pipeline_cache), static_cast(color_format), static_cast(depth_format), reinterpret_cast const &>(shader_stages)); } } @@ -1061,11 +1059,10 @@ inline void Gui::prepare_descriptors() descriptor_set = device.allocateDescriptorSets(descriptor_allocation).front(); // Update descriptor set with font image - vk::DescriptorImageInfo font_descriptor = {.sampler = sampler->get_handle(), - .imageView = font_image_view->get_handle(), - .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal}; - vk::WriteDescriptorSet write_descriptor_set = { - .dstSet = descriptor_set, .descriptorCount = 1, .descriptorType = vk::DescriptorType::eCombinedImageSampler, .pImageInfo = &font_descriptor}; + vk::DescriptorImageInfo font_descriptor = { + .sampler = sampler->get_handle(), .imageView = font_image_view->get_handle(), .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal}; + vk::WriteDescriptorSet write_descriptor_set = { + .dstSet = descriptor_set, .descriptorCount = 1, .descriptorType = vk::DescriptorType::eCombinedImageSampler, .pImageInfo = &font_descriptor}; device.updateDescriptorSets(write_descriptor_set, nullptr); } @@ -1095,10 +1092,8 @@ inline void Gui::create_gui_pipeline(vk::PipelineCache .colorWriteMask = vk::FlagTraits::allFlags}; vk::PipelineColorBlendStateCreateInfo color_blend_state = {.attachmentCount = 1, .pAttachments = &blend_attachment_state}; - vk::PipelineDepthStencilStateCreateInfo depth_stencil_state = {.depthTestEnable = false, - .depthWriteEnable = false, - .depthCompareOp = vk::CompareOp::eAlways, - .back = {.compareOp = vk::CompareOp::eAlways}}; + vk::PipelineDepthStencilStateCreateInfo depth_stencil_state = { + .depthTestEnable = false, .depthWriteEnable = false, .depthCompareOp = vk::CompareOp::eAlways, .back = {.compareOp = vk::CompareOp::eAlways}}; vk::PipelineViewportStateCreateInfo viewport_state = {.viewportCount = 1, .scissorCount = 1}; @@ -1109,7 +1104,7 @@ inline void Gui::create_gui_pipeline(vk::PipelineCache .pDynamicStates = dynamic_state_enables.data()}; // Vertex bindings an attributes based on ImGui vertex definition - vk::VertexInputBindingDescription vertex_input_binding = {.binding = 0, .stride = sizeof(ImDrawVert), .inputRate = vk::VertexInputRate::eVertex}; + vk::VertexInputBindingDescription vertex_input_binding = {.binding = 0, .stride = sizeof(ImDrawVert), .inputRate = vk::VertexInputRate::eVertex}; std::array vertex_input_attributes = { {{.location = 0, .binding = 0, .format = vk::Format::eR32G32Sfloat, .offset = offsetof(ImDrawVert, pos)}, {.location = 1, .binding = 0, .format = vk::Format::eR32G32Sfloat, .offset = offsetof(ImDrawVert, uv)}, @@ -1161,11 +1156,10 @@ inline void Gui::prepare_impl(vk::PipelineCache { prepare_descriptors(); - vk::PipelineRenderingCreateInfoKHR pipeline_rendering_info = { - .colorAttachmentCount = 1, - .pColorAttachmentFormats = &color_format, - .depthAttachmentFormat = depth_format, - .stencilAttachmentFormat = vk::Format::eUndefined}; + vk::PipelineRenderingCreateInfoKHR pipeline_rendering_info = {.colorAttachmentCount = 1, + .pColorAttachmentFormats = &color_format, + .depthAttachmentFormat = depth_format, + .stencilAttachmentFormat = vk::Format::eUndefined}; create_gui_pipeline(pipeline_cache, shader_stages, VK_NULL_HANDLE, 0, &pipeline_rendering_info); } @@ -1412,8 +1406,7 @@ inline bool Gui::update_buffers() if (!vertex_buffer->get_handle() || (vertex_buffer_size != vertex_buffer->get_size())) { vertex_buffer.reset(); - vertex_buffer = std::make_unique(render_context.get_device(), vertex_buffer_size, - vk::BufferUsageFlagBits::eVertexBuffer, + vertex_buffer = std::make_unique(render_context.get_device(), vertex_buffer_size, vk::BufferUsageFlagBits::eVertexBuffer, VMA_MEMORY_USAGE_GPU_TO_CPU); vertex_buffer->set_debug_name("GUI vertex buffer"); updated = true; @@ -1422,8 +1415,7 @@ inline bool Gui::update_buffers() if (!index_buffer->get_handle() || (index_buffer_size != index_buffer->get_size())) { index_buffer.reset(); - index_buffer = std::make_unique(render_context.get_device(), index_buffer_size, - vk::BufferUsageFlagBits::eIndexBuffer, + index_buffer = std::make_unique(render_context.get_device(), index_buffer_size, vk::BufferUsageFlagBits::eIndexBuffer, VMA_MEMORY_USAGE_GPU_TO_CPU); index_buffer->set_debug_name("GUI index buffer"); updated = true; diff --git a/framework/hpp_api_vulkan_sample.cpp b/framework/hpp_api_vulkan_sample.cpp index f37a9bd7a6..c898ea163a 100644 --- a/framework/hpp_api_vulkan_sample.cpp +++ b/framework/hpp_api_vulkan_sample.cpp @@ -72,9 +72,8 @@ void HPPApiVulkanSample::prepare_gui() { create_gui(*window, nullptr, 15.0f, true); - std::vector shader_stages = { - load_shader("uioverlay/uioverlay.vert.spv", vk::ShaderStageFlagBits::eVertex), - load_shader("uioverlay/uioverlay.frag.spv", vk::ShaderStageFlagBits::eFragment)}; + std::vector shader_stages = {load_shader("uioverlay/uioverlay.vert.spv", vk::ShaderStageFlagBits::eVertex), + load_shader("uioverlay/uioverlay.frag.spv", vk::ShaderStageFlagBits::eFragment)}; if (uses_dynamic_rendering()) { @@ -424,7 +423,8 @@ vk::PipelineShaderStageCreateInfo HPPApiVulkanSample::load_shader(const std::str return vk::PipelineShaderStageCreateInfo{.stage = stage, .module = shader_modules.back(), .pName = "main"}; } -vk::PipelineShaderStageCreateInfo HPPApiVulkanSample::load_shader(const std::string &sample_folder_name, const std::string &shader_filename, vk::ShaderStageFlagBits stage) +vk::PipelineShaderStageCreateInfo + HPPApiVulkanSample::load_shader(const std::string &sample_folder_name, const std::string &shader_filename, vk::ShaderStageFlagBits stage) { std::string full_file_name = sample_folder_name + "/" + get_shader_folder() + "/" + shader_filename; @@ -625,19 +625,16 @@ void HPPApiVulkanSample::create_synchronization_primitives() void HPPApiVulkanSample::create_command_pool() { - uint32_t queue_family_index = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics | vk::QueueFlagBits::eCompute, 0).get_family_index(); + uint32_t queue_family_index = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics | vk::QueueFlagBits::eCompute, 0).get_family_index(); vk::CommandPoolCreateInfo command_pool_info{.queueFamilyIndex = queue_family_index}; cmd_pool = get_device().get_handle().createCommandPool(command_pool_info); } void HPPApiVulkanSample::setup_depth_stencil() { - std::tie(depth_stencil.image, depth_stencil.mem) = - get_device().create_image(depth_format, - get_render_context().get_surface_extent(), - 1, - vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransferSrc, - vk::MemoryPropertyFlagBits::eDeviceLocal); + std::tie(depth_stencil.image, depth_stencil.mem) = get_device().create_image( + depth_format, get_render_context().get_surface_extent(), 1, vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransferSrc, + vk::MemoryPropertyFlagBits::eDeviceLocal); vk::ImageAspectFlags aspect_mask = vk::ImageAspectFlagBits::eDepth; // Stencil aspect should only be set on depth + stencil formats @@ -718,16 +715,16 @@ void HPPApiVulkanSample::setup_render_pass() .dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests, .srcAccessMask = vk::AccessFlagBits::eNoneKHR, - .dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentRead | - vk::AccessFlagBits::eDepthStencilAttachmentWrite, + .dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite | + vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite, .dependencyFlags = vk::DependencyFlagBits::eByRegion}, {.srcSubpass = 0, .dstSubpass = vk::SubpassExternal, .srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests, .dstStageMask = vk::PipelineStageFlagBits::eBottomOfPipe, - .srcAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentRead | - vk::AccessFlagBits::eDepthStencilAttachmentWrite, + .srcAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite | + vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite, .dstAccessMask = vk::AccessFlagBits::eMemoryRead, .dependencyFlags = vk::DependencyFlagBits::eByRegion}, }}; @@ -792,16 +789,16 @@ void HPPApiVulkanSample::update_render_pass_flags(RenderPassCreateFlags flags) .dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests, .srcAccessMask = vk::AccessFlagBits::eNoneKHR, - .dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentRead | - vk::AccessFlagBits::eDepthStencilAttachmentWrite, + .dstAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite | + vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite, .dependencyFlags = vk::DependencyFlagBits::eByRegion}, {.srcSubpass = 0, .dstSubpass = vk::SubpassExternal, .srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests, .dstStageMask = vk::PipelineStageFlagBits::eBottomOfPipe, - .srcAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentRead | - vk::AccessFlagBits::eDepthStencilAttachmentWrite, + .srcAccessMask = vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite | + vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite, .dstAccessMask = vk::AccessFlagBits::eMemoryRead, .dependencyFlags = vk::DependencyFlagBits::eByRegion}, }}; @@ -822,11 +819,7 @@ void HPPApiVulkanSample::on_update_ui_overlay(vkb::Drawer &drawer) vk::Sampler HPPApiVulkanSample::create_default_sampler(vk::SamplerAddressMode address_mode, size_t mipmaps_count, vk::Format format) { return vkb::common::create_sampler( - get_device().get_gpu().get_handle(), - get_device().get_handle(), - format, - vk::Filter::eLinear, - address_mode, + get_device().get_gpu().get_handle(), get_device().get_handle(), format, vk::Filter::eLinear, address_mode, get_device().get_gpu().get_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f, static_cast(mipmaps_count)); } @@ -846,9 +839,8 @@ void HPPApiVulkanSample::create_swapchain_buffers() swapchain_buffers.reserve(images.size()); for (auto &image : images) { - swapchain_buffers.push_back( - {image, - vkb::common::create_image_view(get_device().get_handle(), image, vk::ImageViewType::e2D, get_render_context().get_swapchain().get_format())}); + swapchain_buffers.push_back({image, vkb::common::create_image_view(get_device().get_handle(), image, vk::ImageViewType::e2D, + get_render_context().get_swapchain().get_format())}); } } else @@ -899,7 +891,9 @@ vk::ImageLayout HPPApiVulkanSample::descriptor_type_to_image_layout(vk::Descript } } -HPPTexture HPPApiVulkanSample::load_texture(const std::string &file, vkb::scene_graph::components::HPPImage::ContentType content_type, vk::SamplerAddressMode address_mode) +HPPTexture HPPApiVulkanSample::load_texture(const std::string &file, + vkb::scene_graph::components::HPPImage::ContentType content_type, + vk::SamplerAddressMode address_mode) { HPPTexture texture; @@ -936,19 +930,16 @@ HPPTexture HPPApiVulkanSample::load_texture(const std::string &file, vkb::scene_ // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy - vkb::common::image_layout_transition( - command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); + vkb::common::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, + vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer - command_buffer.copyBufferToImage( - stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, bufferCopyRegions); + command_buffer.copyBufferToImage(stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, + bufferCopyRegions); // Change texture image layout to shader read after all mip levels have been copied - vkb::common::image_layout_transition(command_buffer, - texture.image->get_vk_image().get_handle(), - vk::ImageLayout::eTransferDstOptimal, - vk::ImageLayout::eShaderReadOnlyOptimal, - subresource_range); + vkb::common::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, + vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); @@ -957,7 +948,9 @@ HPPTexture HPPApiVulkanSample::load_texture(const std::string &file, vkb::scene_ return texture; } -HPPTexture HPPApiVulkanSample::load_texture_array(const std::string &file, vkb::scene_graph::components::HPPImage::ContentType content_type, vk::SamplerAddressMode address_mode) +HPPTexture HPPApiVulkanSample::load_texture_array(const std::string &file, + vkb::scene_graph::components::HPPImage::ContentType content_type, + vk::SamplerAddressMode address_mode) { HPPTexture texture{}; @@ -1000,19 +993,16 @@ HPPTexture HPPApiVulkanSample::load_texture_array(const std::string &file, vkb:: // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy - vkb::common::image_layout_transition( - command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); + vkb::common::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, + vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer - command_buffer.copyBufferToImage( - stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, buffer_copy_regions); + command_buffer.copyBufferToImage(stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, + buffer_copy_regions); // Change texture image layout to shader read after all mip levels have been copied - vkb::common::image_layout_transition(command_buffer, - texture.image->get_vk_image().get_handle(), - vk::ImageLayout::eTransferDstOptimal, - vk::ImageLayout::eShaderReadOnlyOptimal, - subresource_range); + vkb::common::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, + vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); @@ -1064,19 +1054,16 @@ HPPTexture HPPApiVulkanSample::load_texture_cubemap(const std::string &file, vkb // Image barrier for optimal image (target) // Optimal image will be used as destination for the copy - vkb::common::image_layout_transition( - command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, subresource_range); + vkb::common::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eUndefined, + vk::ImageLayout::eTransferDstOptimal, subresource_range); // Copy mip levels from staging buffer - command_buffer.copyBufferToImage( - stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, buffer_copy_regions); + command_buffer.copyBufferToImage(stage_buffer.get_handle(), texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, + buffer_copy_regions); // Change texture image layout to shader read after all mip levels have been copied - vkb::common::image_layout_transition(command_buffer, - texture.image->get_vk_image().get_handle(), - vk::ImageLayout::eTransferDstOptimal, - vk::ImageLayout::eShaderReadOnlyOptimal, - subresource_range); + vkb::common::image_layout_transition(command_buffer, texture.image->get_vk_image().get_handle(), vk::ImageLayout::eTransferDstOptimal, + vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); get_device().flush_command_buffer(command_buffer, queue.get_handle()); diff --git a/framework/hpp_api_vulkan_sample.h b/framework/hpp_api_vulkan_sample.h index 01e03a372d..5ba8904392 100644 --- a/framework/hpp_api_vulkan_sample.h +++ b/framework/hpp_api_vulkan_sample.h @@ -183,8 +183,9 @@ class HPPApiVulkanSample : public vkb::VulkanSampleCpp * @param content_type The type of content in the image file * @param address_mode The address mode to use in u-, v-, and w-direction. Defaults to /c vk::SamplerAddressMode::eRepeat. */ - HPPTexture - load_texture(const std::string &file, vkb::scene_graph::components::HPPImage::ContentType content_type, vk::SamplerAddressMode address_mode = vk::SamplerAddressMode::eRepeat); + HPPTexture load_texture(const std::string &file, + vkb::scene_graph::components::HPPImage::ContentType content_type, + vk::SamplerAddressMode address_mode = vk::SamplerAddressMode::eRepeat); /** * @brief Loads in a ktx 2D texture array @@ -210,8 +211,8 @@ class HPPApiVulkanSample : public vkb::VulkanSampleCpp * @param storage_buffer Set true to store model in SSBO * @param additional_buffer_usage_flags Additional buffer usage flags to be applied to vertex and index buffers */ - std::unique_ptr load_model( - const std::string &file, uint32_t index = 0, bool storage_buffer = false, vk::BufferUsageFlags additional_buffer_usage_flags = {}); + std::unique_ptr + load_model(const std::string &file, uint32_t index = 0, bool storage_buffer = false, vk::BufferUsageFlags additional_buffer_usage_flags = {}); /** * @brief Records the necessary drawing commands to a command buffer diff --git a/framework/hpp_fence_pool.h b/framework/hpp_fence_pool.h index 00117fbec9..003a21f65f 100644 --- a/framework/hpp_fence_pool.h +++ b/framework/hpp_fence_pool.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -40,8 +40,7 @@ class HPPFencePool : private vkb::FencePool using vkb::FencePool::reset; using vkb::FencePool::wait; - HPPFencePool(vkb::core::DeviceCpp &device) : - vkb::FencePool(reinterpret_cast(device)) + HPPFencePool(vkb::core::DeviceCpp &device) : vkb::FencePool(reinterpret_cast(device)) {} vk::Fence request_fence() diff --git a/framework/hpp_gltf_loader.h b/framework/hpp_gltf_loader.h index cb001d85ea..19381a64ed 100644 --- a/framework/hpp_gltf_loader.h +++ b/framework/hpp_gltf_loader.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -32,12 +32,11 @@ namespace vkb class HPPGLTFLoader : private vkb::GLTFLoader { public: - HPPGLTFLoader(vkb::core::DeviceCpp &device) : - GLTFLoader(reinterpret_cast(device)) + HPPGLTFLoader(vkb::core::DeviceCpp &device) : GLTFLoader(reinterpret_cast(device)) {} - std::unique_ptr read_model_from_file( - const std::string &file_name, uint32_t index, bool storage_buffer = false, vk::BufferUsageFlags additional_buffer_usage_flags = {}) + std::unique_ptr + read_model_from_file(const std::string &file_name, uint32_t index, bool storage_buffer = false, vk::BufferUsageFlags additional_buffer_usage_flags = {}) { return std::unique_ptr(reinterpret_cast( vkb::GLTFLoader::read_model_from_file(file_name, index, storage_buffer, static_cast(additional_buffer_usage_flags)).release())); @@ -45,7 +44,8 @@ class HPPGLTFLoader : private vkb::GLTFLoader std::unique_ptr read_scene_from_file(const std::string &file_name, int scene_index = -1) { - return std::unique_ptr(reinterpret_cast(vkb::GLTFLoader::read_scene_from_file(file_name, scene_index).release())); + return std::unique_ptr( + reinterpret_cast(vkb::GLTFLoader::read_scene_from_file(file_name, scene_index).release())); } }; } // namespace vkb diff --git a/framework/hpp_resource_binding_state.h b/framework/hpp_resource_binding_state.h index 2e95588515..b201d3a9b7 100644 --- a/framework/hpp_resource_binding_state.h +++ b/framework/hpp_resource_binding_state.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -68,18 +68,14 @@ class HPPResourceBindingState : private vkb::ResourceBindingState public: void bind_buffer(const vkb::core::BufferCpp &buffer, vk::DeviceSize offset, vk::DeviceSize range, uint32_t set, uint32_t binding, uint32_t array_element) { - vkb::ResourceBindingState::bind_buffer(reinterpret_cast(buffer), - static_cast(offset), - static_cast(range), - set, - binding, - array_element); + vkb::ResourceBindingState::bind_buffer(reinterpret_cast(buffer), static_cast(offset), + static_cast(range), set, binding, array_element); } void bind_image(const vkb::core::HPPImageView &image_view, const vkb::core::HPPSampler &sampler, uint32_t set, uint32_t binding, uint32_t array_element) { - vkb::ResourceBindingState::bind_image( - reinterpret_cast(image_view), reinterpret_cast(sampler), set, binding, array_element); + vkb::ResourceBindingState::bind_image(reinterpret_cast(image_view), reinterpret_cast(sampler), + set, binding, array_element); } void bind_image(const vkb::core::HPPImageView &image_view, uint32_t set, uint32_t binding, uint32_t array_element) diff --git a/framework/hpp_resource_cache.cpp b/framework/hpp_resource_cache.cpp index c2de24b8af..53a54f5f14 100644 --- a/framework/hpp_resource_cache.cpp +++ b/framework/hpp_resource_cache.cpp @@ -39,8 +39,7 @@ T &request_resource( } } // namespace -HPPResourceCache::HPPResourceCache(vkb::core::DeviceCpp &device) : - device{device} +HPPResourceCache::HPPResourceCache(vkb::core::DeviceCpp &device) : device{device} {} void HPPResourceCache::clear() diff --git a/framework/hpp_resource_cache.h b/framework/hpp_resource_cache.h index cc580db93b..b920952714 100644 --- a/framework/hpp_resource_cache.h +++ b/framework/hpp_resource_cache.h @@ -95,10 +95,11 @@ class HPPResourceCache vkb::core::HPPRenderPass &request_render_pass(const std::vector &attachments, const std::vector &load_store_infos, const std::vector &subpasses); - vkb::core::HPPShaderModule &request_shader_module( - vk::ShaderStageFlagBits stage, const vkb::core::HPPShaderSource &glsl_source, const vkb::core::HPPShaderVariant &shader_variant = {}); - std::vector serialize(); - void set_pipeline_cache(vk::PipelineCache pipeline_cache); + vkb::core::HPPShaderModule &request_shader_module(vk::ShaderStageFlagBits stage, + const vkb::core::HPPShaderSource &glsl_source, + const vkb::core::HPPShaderVariant &shader_variant = {}); + std::vector serialize(); + void set_pipeline_cache(vk::PipelineCache pipeline_cache); /// @brief Update those descriptor sets referring to old views /// @param old_views Old image views referred by descriptor sets diff --git a/framework/hpp_resource_record.h b/framework/hpp_resource_record.h index 50e37ef124..9f312212aa 100644 --- a/framework/hpp_resource_record.h +++ b/framework/hpp_resource_record.h @@ -78,10 +78,8 @@ class HPPResourceRecord : private vkb::ResourceRecord const std::string &entry_point, const vkb::core::HPPShaderVariant &shader_variant) { - return vkb::ResourceRecord::register_shader_module(static_cast(stage), - reinterpret_cast(glsl_source), - entry_point, - reinterpret_cast(shader_variant)); + return vkb::ResourceRecord::register_shader_module(static_cast(stage), reinterpret_cast(glsl_source), + entry_point, reinterpret_cast(shader_variant)); } void set_graphics_pipeline(size_t index, const vkb::core::HPPGraphicsPipeline &graphics_pipeline) diff --git a/framework/hpp_semaphore_pool.h b/framework/hpp_semaphore_pool.h index 7965275234..2cbe313ccc 100644 --- a/framework/hpp_semaphore_pool.h +++ b/framework/hpp_semaphore_pool.h @@ -32,8 +32,7 @@ class HPPSemaphorePool : private vkb::SemaphorePool public: using vkb::SemaphorePool::reset; - HPPSemaphorePool(vkb::core::DeviceCpp &device) : - vkb::SemaphorePool(reinterpret_cast(device)) + HPPSemaphorePool(vkb::core::DeviceCpp &device) : vkb::SemaphorePool(reinterpret_cast(device)) {} void release_owned_semaphore(vk::Semaphore semaphore) diff --git a/framework/platform/android/android_platform.cpp b/framework/platform/android/android_platform.cpp index fc0ff97db4..7d5a8f0ca8 100644 --- a/framework/platform/android/android_platform.cpp +++ b/framework/platform/android/android_platform.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -39,13 +39,13 @@ extern "C" { - JNIEXPORT jobjectArray JNICALL - Java_com_khronos_vulkan_1samples_SampleLauncherActivity_getSamples(JNIEnv *env, jobject thiz) + JNIEXPORT jobjectArray JNICALL Java_com_khronos_vulkan_1samples_SampleLauncherActivity_getSamples(JNIEnv *env, jobject thiz) { auto sample_list = apps::get_samples(); - jclass c = env->FindClass("com/khronos/vulkan_samples/model/Sample"); - jmethodID constructor = env->GetMethodID(c, "", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V"); + jclass c = env->FindClass("com/khronos/vulkan_samples/model/Sample"); + jmethodID constructor = + env->GetMethodID(c, "", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V"); jobjectArray j_sample_list = env->NewObjectArray(sample_list.size(), c, 0); for (int sample_index = 0; sample_index < sample_list.size(); sample_index++) @@ -86,108 +86,106 @@ inline std::tm thread_safe_time(const std::time_t time) inline KeyCode translate_key_code(int key) { - static const std::unordered_map key_lookup = - { - {AKEYCODE_SPACE, KeyCode::Space}, - {AKEYCODE_APOSTROPHE, KeyCode::Apostrophe}, - {AKEYCODE_COMMA, KeyCode::Comma}, - {AKEYCODE_MINUS, KeyCode::Minus}, - {AKEYCODE_PERIOD, KeyCode::Period}, - {AKEYCODE_SLASH, KeyCode::Slash}, - {AKEYCODE_0, KeyCode::_0}, - {AKEYCODE_1, KeyCode::_1}, - {AKEYCODE_2, KeyCode::_2}, - {AKEYCODE_3, KeyCode::_3}, - {AKEYCODE_4, KeyCode::_4}, - {AKEYCODE_5, KeyCode::_5}, - {AKEYCODE_6, KeyCode::_6}, - {AKEYCODE_7, KeyCode::_7}, - {AKEYCODE_8, KeyCode::_8}, - {AKEYCODE_9, KeyCode::_9}, - {AKEYCODE_SEMICOLON, KeyCode::Semicolon}, - {AKEYCODE_EQUALS, KeyCode::Equal}, - {AKEYCODE_A, KeyCode::A}, - {AKEYCODE_B, KeyCode::B}, - {AKEYCODE_C, KeyCode::C}, - {AKEYCODE_D, KeyCode::D}, - {AKEYCODE_E, KeyCode::E}, - {AKEYCODE_F, KeyCode::F}, - {AKEYCODE_G, KeyCode::G}, - {AKEYCODE_H, KeyCode::H}, - {AKEYCODE_I, KeyCode::I}, - {AKEYCODE_J, KeyCode::J}, - {AKEYCODE_K, KeyCode::K}, - {AKEYCODE_L, KeyCode::L}, - {AKEYCODE_M, KeyCode::M}, - {AKEYCODE_N, KeyCode::N}, - {AKEYCODE_O, KeyCode::O}, - {AKEYCODE_P, KeyCode::P}, - {AKEYCODE_Q, KeyCode::Q}, - {AKEYCODE_R, KeyCode::R}, - {AKEYCODE_S, KeyCode::S}, - {AKEYCODE_T, KeyCode::T}, - {AKEYCODE_U, KeyCode::U}, - {AKEYCODE_V, KeyCode::V}, - {AKEYCODE_W, KeyCode::W}, - {AKEYCODE_X, KeyCode::X}, - {AKEYCODE_Y, KeyCode::Y}, - {AKEYCODE_Z, KeyCode::Z}, - {AKEYCODE_LEFT_BRACKET, KeyCode::LeftBracket}, - {AKEYCODE_BACKSLASH, KeyCode::Backslash}, - {AKEYCODE_RIGHT_BRACKET, KeyCode::RightBracket}, - {AKEYCODE_ESCAPE, KeyCode::Escape}, - {AKEYCODE_BACK, KeyCode::Back}, - {AKEYCODE_ENTER, KeyCode::Enter}, - {AKEYCODE_TAB, KeyCode::Tab}, - {AKEYCODE_DEL, KeyCode::Backspace}, - {AKEYCODE_INSERT, KeyCode::Insert}, - {AKEYCODE_DEL, KeyCode::DelKey}, - {AKEYCODE_SYSTEM_NAVIGATION_RIGHT, KeyCode::Right}, - {AKEYCODE_SYSTEM_NAVIGATION_LEFT, KeyCode::Left}, - {AKEYCODE_SYSTEM_NAVIGATION_DOWN, KeyCode::Down}, - {AKEYCODE_SYSTEM_NAVIGATION_UP, KeyCode::Up}, - {AKEYCODE_PAGE_UP, KeyCode::PageUp}, - {AKEYCODE_PAGE_DOWN, KeyCode::PageDown}, - {AKEYCODE_HOME, KeyCode::Home}, - {AKEYCODE_CAPS_LOCK, KeyCode::CapsLock}, - {AKEYCODE_SCROLL_LOCK, KeyCode::ScrollLock}, - {AKEYCODE_NUM_LOCK, KeyCode::NumLock}, - {AKEYCODE_BREAK, KeyCode::Pause}, - {AKEYCODE_F1, KeyCode::F1}, - {AKEYCODE_F2, KeyCode::F2}, - {AKEYCODE_F3, KeyCode::F3}, - {AKEYCODE_F4, KeyCode::F4}, - {AKEYCODE_F5, KeyCode::F5}, - {AKEYCODE_F6, KeyCode::F6}, - {AKEYCODE_F7, KeyCode::F7}, - {AKEYCODE_F8, KeyCode::F8}, - {AKEYCODE_F9, KeyCode::F9}, - {AKEYCODE_F10, KeyCode::F10}, - {AKEYCODE_F11, KeyCode::F11}, - {AKEYCODE_F12, KeyCode::F12}, - {AKEYCODE_NUMPAD_0, KeyCode::KP_0}, - {AKEYCODE_NUMPAD_1, KeyCode::KP_1}, - {AKEYCODE_NUMPAD_2, KeyCode::KP_2}, - {AKEYCODE_NUMPAD_3, KeyCode::KP_3}, - {AKEYCODE_NUMPAD_4, KeyCode::KP_4}, - {AKEYCODE_NUMPAD_5, KeyCode::KP_5}, - {AKEYCODE_NUMPAD_6, KeyCode::KP_6}, - {AKEYCODE_NUMPAD_7, KeyCode::KP_7}, - {AKEYCODE_NUMPAD_8, KeyCode::KP_8}, - {AKEYCODE_NUMPAD_9, KeyCode::KP_9}, - {AKEYCODE_NUMPAD_DOT, KeyCode::KP_Decimal}, - {AKEYCODE_NUMPAD_DIVIDE, KeyCode::KP_Divide}, - {AKEYCODE_NUMPAD_MULTIPLY, KeyCode::KP_Multiply}, - {AKEYCODE_NUMPAD_SUBTRACT, KeyCode::KP_Subtract}, - {AKEYCODE_NUMPAD_ADD, KeyCode::KP_Add}, - {AKEYCODE_NUMPAD_ENTER, KeyCode::KP_Enter}, - {AKEYCODE_NUMPAD_EQUALS, KeyCode::KP_Equal}, - {AKEYCODE_SHIFT_LEFT, KeyCode::LeftShift}, - {AKEYCODE_CTRL_LEFT, KeyCode::LeftControl}, - {AKEYCODE_ALT_LEFT, KeyCode::LeftAlt}, - {AKEYCODE_SHIFT_RIGHT, KeyCode::RightShift}, - {AKEYCODE_CTRL_RIGHT, KeyCode::RightControl}, - {AKEYCODE_ALT_RIGHT, KeyCode::RightAlt}}; + static const std::unordered_map key_lookup = {{AKEYCODE_SPACE, KeyCode::Space}, + {AKEYCODE_APOSTROPHE, KeyCode::Apostrophe}, + {AKEYCODE_COMMA, KeyCode::Comma}, + {AKEYCODE_MINUS, KeyCode::Minus}, + {AKEYCODE_PERIOD, KeyCode::Period}, + {AKEYCODE_SLASH, KeyCode::Slash}, + {AKEYCODE_0, KeyCode::_0}, + {AKEYCODE_1, KeyCode::_1}, + {AKEYCODE_2, KeyCode::_2}, + {AKEYCODE_3, KeyCode::_3}, + {AKEYCODE_4, KeyCode::_4}, + {AKEYCODE_5, KeyCode::_5}, + {AKEYCODE_6, KeyCode::_6}, + {AKEYCODE_7, KeyCode::_7}, + {AKEYCODE_8, KeyCode::_8}, + {AKEYCODE_9, KeyCode::_9}, + {AKEYCODE_SEMICOLON, KeyCode::Semicolon}, + {AKEYCODE_EQUALS, KeyCode::Equal}, + {AKEYCODE_A, KeyCode::A}, + {AKEYCODE_B, KeyCode::B}, + {AKEYCODE_C, KeyCode::C}, + {AKEYCODE_D, KeyCode::D}, + {AKEYCODE_E, KeyCode::E}, + {AKEYCODE_F, KeyCode::F}, + {AKEYCODE_G, KeyCode::G}, + {AKEYCODE_H, KeyCode::H}, + {AKEYCODE_I, KeyCode::I}, + {AKEYCODE_J, KeyCode::J}, + {AKEYCODE_K, KeyCode::K}, + {AKEYCODE_L, KeyCode::L}, + {AKEYCODE_M, KeyCode::M}, + {AKEYCODE_N, KeyCode::N}, + {AKEYCODE_O, KeyCode::O}, + {AKEYCODE_P, KeyCode::P}, + {AKEYCODE_Q, KeyCode::Q}, + {AKEYCODE_R, KeyCode::R}, + {AKEYCODE_S, KeyCode::S}, + {AKEYCODE_T, KeyCode::T}, + {AKEYCODE_U, KeyCode::U}, + {AKEYCODE_V, KeyCode::V}, + {AKEYCODE_W, KeyCode::W}, + {AKEYCODE_X, KeyCode::X}, + {AKEYCODE_Y, KeyCode::Y}, + {AKEYCODE_Z, KeyCode::Z}, + {AKEYCODE_LEFT_BRACKET, KeyCode::LeftBracket}, + {AKEYCODE_BACKSLASH, KeyCode::Backslash}, + {AKEYCODE_RIGHT_BRACKET, KeyCode::RightBracket}, + {AKEYCODE_ESCAPE, KeyCode::Escape}, + {AKEYCODE_BACK, KeyCode::Back}, + {AKEYCODE_ENTER, KeyCode::Enter}, + {AKEYCODE_TAB, KeyCode::Tab}, + {AKEYCODE_DEL, KeyCode::Backspace}, + {AKEYCODE_INSERT, KeyCode::Insert}, + {AKEYCODE_DEL, KeyCode::DelKey}, + {AKEYCODE_SYSTEM_NAVIGATION_RIGHT, KeyCode::Right}, + {AKEYCODE_SYSTEM_NAVIGATION_LEFT, KeyCode::Left}, + {AKEYCODE_SYSTEM_NAVIGATION_DOWN, KeyCode::Down}, + {AKEYCODE_SYSTEM_NAVIGATION_UP, KeyCode::Up}, + {AKEYCODE_PAGE_UP, KeyCode::PageUp}, + {AKEYCODE_PAGE_DOWN, KeyCode::PageDown}, + {AKEYCODE_HOME, KeyCode::Home}, + {AKEYCODE_CAPS_LOCK, KeyCode::CapsLock}, + {AKEYCODE_SCROLL_LOCK, KeyCode::ScrollLock}, + {AKEYCODE_NUM_LOCK, KeyCode::NumLock}, + {AKEYCODE_BREAK, KeyCode::Pause}, + {AKEYCODE_F1, KeyCode::F1}, + {AKEYCODE_F2, KeyCode::F2}, + {AKEYCODE_F3, KeyCode::F3}, + {AKEYCODE_F4, KeyCode::F4}, + {AKEYCODE_F5, KeyCode::F5}, + {AKEYCODE_F6, KeyCode::F6}, + {AKEYCODE_F7, KeyCode::F7}, + {AKEYCODE_F8, KeyCode::F8}, + {AKEYCODE_F9, KeyCode::F9}, + {AKEYCODE_F10, KeyCode::F10}, + {AKEYCODE_F11, KeyCode::F11}, + {AKEYCODE_F12, KeyCode::F12}, + {AKEYCODE_NUMPAD_0, KeyCode::KP_0}, + {AKEYCODE_NUMPAD_1, KeyCode::KP_1}, + {AKEYCODE_NUMPAD_2, KeyCode::KP_2}, + {AKEYCODE_NUMPAD_3, KeyCode::KP_3}, + {AKEYCODE_NUMPAD_4, KeyCode::KP_4}, + {AKEYCODE_NUMPAD_5, KeyCode::KP_5}, + {AKEYCODE_NUMPAD_6, KeyCode::KP_6}, + {AKEYCODE_NUMPAD_7, KeyCode::KP_7}, + {AKEYCODE_NUMPAD_8, KeyCode::KP_8}, + {AKEYCODE_NUMPAD_9, KeyCode::KP_9}, + {AKEYCODE_NUMPAD_DOT, KeyCode::KP_Decimal}, + {AKEYCODE_NUMPAD_DIVIDE, KeyCode::KP_Divide}, + {AKEYCODE_NUMPAD_MULTIPLY, KeyCode::KP_Multiply}, + {AKEYCODE_NUMPAD_SUBTRACT, KeyCode::KP_Subtract}, + {AKEYCODE_NUMPAD_ADD, KeyCode::KP_Add}, + {AKEYCODE_NUMPAD_ENTER, KeyCode::KP_Enter}, + {AKEYCODE_NUMPAD_EQUALS, KeyCode::KP_Equal}, + {AKEYCODE_SHIFT_LEFT, KeyCode::LeftShift}, + {AKEYCODE_CTRL_LEFT, KeyCode::LeftControl}, + {AKEYCODE_ALT_LEFT, KeyCode::LeftAlt}, + {AKEYCODE_SHIFT_RIGHT, KeyCode::RightShift}, + {AKEYCODE_CTRL_RIGHT, KeyCode::RightControl}, + {AKEYCODE_ALT_RIGHT, KeyCode::RightAlt}}; auto key_it = key_lookup.find(key); @@ -287,8 +285,7 @@ void on_app_cmd(android_app *app, int32_t cmd) { case APP_CMD_INIT_WINDOW: { - platform->resize(ANativeWindow_getWidth(app->window), - ANativeWindow_getHeight(app->window)); + platform->resize(ANativeWindow_getWidth(app->window), ANativeWindow_getHeight(app->window)); platform->set_surface_ready(); break; } @@ -324,8 +321,7 @@ bool key_event_filter(const GameActivityKeyEvent *event) bool motion_event_filter(const GameActivityMotionEvent *event) { - if ((event->source == AINPUT_SOURCE_MOUSE) || - (event->source == AINPUT_SOURCE_TOUCHSCREEN)) + if ((event->source == AINPUT_SOURCE_MOUSE) || (event->source == AINPUT_SOURCE_TOUCHSCREEN)) { return true; } @@ -333,8 +329,7 @@ bool motion_event_filter(const GameActivityMotionEvent *event) } } // namespace -AndroidPlatform::AndroidPlatform(const PlatformContext &context) : - Platform{context} +AndroidPlatform::AndroidPlatform(const PlatformContext &context) : Platform{context} { if (auto *android = dynamic_cast(&context)) { @@ -395,9 +390,7 @@ void AndroidPlatform::process_android_input_events(void) for (int idx = 0; idx < input_buf->motionEventsCount; idx++) { auto event = &input_buf->motionEvents[idx]; - assert((event->source == AINPUT_SOURCE_MOUSE || - event->source == AINPUT_SOURCE_TOUCHSCREEN) && - "Invalid motion event source"); + assert((event->source == AINPUT_SOURCE_MOUSE || event->source == AINPUT_SOURCE_TOUCHSCREEN) && "Invalid motion event source"); std::int32_t action = event->action; @@ -406,10 +399,7 @@ void AndroidPlatform::process_android_input_events(void) if (event->source == AINPUT_SOURCE_MOUSE) { - input_event(MouseButtonInputEvent{ - translate_mouse_button(0), - translate_mouse_action(action), - x, y}); + input_event(MouseButtonInputEvent{translate_mouse_button(0), translate_mouse_action(action), x, y}); } else if (event->source == AINPUT_SOURCE_TOUCHSCREEN) { @@ -417,11 +407,7 @@ void AndroidPlatform::process_android_input_events(void) size_t pointer_count = event->pointerCount; std::int32_t pointer_id = event->pointers[0].id; - input_event(TouchInputEvent{ - pointer_id, - pointer_count, - translate_touch_action(action), - x, y}); + input_event(TouchInputEvent{pointer_id, pointer_count, translate_touch_action(action), x, y}); } } android_app_clear_motion_events(input_buf); @@ -432,11 +418,8 @@ void AndroidPlatform::process_android_input_events(void) for (int idx = 0; idx < input_buf->keyEventsCount; idx++) { auto event = &input_buf->keyEvents[idx]; - assert((event->source == AINPUT_SOURCE_KEYBOARD) && - "Invalid key event source"); - input_event(KeyInputEvent{ - translate_key_code(event->keyCode), - translate_key_action(event->action)}); + assert((event->source == AINPUT_SOURCE_KEYBOARD) && "Invalid key event source"); + input_event(KeyInputEvent{translate_key_code(event->keyCode), translate_key_action(event->action)}); } android_app_clear_key_events(input_buf); } diff --git a/framework/platform/android/android_window.cpp b/framework/platform/android/android_window.cpp index 338d8d4b46..4a1622e151 100644 --- a/framework/platform/android/android_window.cpp +++ b/framework/platform/android/android_window.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -22,11 +22,8 @@ namespace vkb { AndroidWindow::AndroidWindow(AndroidPlatform *platform, ANativeWindow *&window, const Window::Properties &properties) : - Window(properties), - handle{window}, - platform{platform} -{ -} + Window(properties), handle{window}, platform{platform} +{} VkSurfaceKHR AndroidWindow::create_surface(vkb::core::InstanceC &instance) { diff --git a/framework/platform/application.cpp b/framework/platform/application.cpp index 5da8d31b6b..d823d6dcc4 100644 --- a/framework/platform/application.cpp +++ b/framework/platform/application.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -22,10 +22,8 @@ namespace vkb { -Application::Application() : - name{"Sample Name"} -{ -} +Application::Application() : name{"Sample Name"} +{} bool Application::prepare(const ApplicationOptions &options) { @@ -42,8 +40,7 @@ bool Application::prepare(const ApplicationOptions &options) } void Application::finish() -{ -} +{} bool Application::resize(const uint32_t /*width*/, const uint32_t /*height*/) { @@ -51,8 +48,7 @@ bool Application::resize(const uint32_t /*width*/, const uint32_t /*height*/) } void Application::input_event(const InputEvent &input_event) -{ -} +{} Drawer *Application::get_drawer() { @@ -66,8 +62,7 @@ void Application::update(float delta_time) } void Application::update_overlay(float delta_time, const std::function &additional_ui) -{ -} +{} const std::string &Application::get_name() const { diff --git a/framework/platform/configuration.cpp b/framework/platform/configuration.cpp index 3486380f66..20fc75ad59 100644 --- a/framework/platform/configuration.cpp +++ b/framework/platform/configuration.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -19,11 +19,8 @@ namespace vkb { -BoolSetting::BoolSetting(bool &handle, bool value) : - handle{handle}, - value{value} -{ -} +BoolSetting::BoolSetting(bool &handle, bool value) : handle{handle}, value{value} +{} void BoolSetting::set() { @@ -35,11 +32,8 @@ std::type_index BoolSetting::get_type() return typeid(BoolSetting); } -IntSetting::IntSetting(int &handle, int value) : - handle{handle}, - value{value} -{ -} +IntSetting::IntSetting(int &handle, int value) : handle{handle}, value{value} +{} void IntSetting::set() { @@ -52,12 +46,10 @@ std::type_index IntSetting::get_type() } EmptySetting::EmptySetting() -{ -} +{} void EmptySetting::set() -{ -} +{} std::type_index EmptySetting::get_type() { diff --git a/framework/platform/configuration.h b/framework/platform/configuration.h index 6473b1079d..56276c44f1 100644 --- a/framework/platform/configuration.h +++ b/framework/platform/configuration.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -125,10 +125,9 @@ class Configuration * @param args A parameter pack containing the parameters to initialize a setting object */ template - void insert(uint32_t config_index, A &&... args) + void insert(uint32_t config_index, A &&...args) { - static_assert(std::is_base_of::value, - "T is not a type of setting."); + static_assert(std::is_base_of::value, "T is not a type of setting."); insert_setting(config_index, std::make_unique(args...)); } diff --git a/framework/platform/glfw_window.cpp b/framework/platform/glfw_window.cpp index a3d08eb75b..d4e0432619 100644 --- a/framework/platform/glfw_window.cpp +++ b/framework/platform/glfw_window.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -62,111 +62,110 @@ void window_focus_callback(GLFWwindow *window, int focused) inline KeyCode translate_key_code(int key) { - static const std::unordered_map key_lookup = - { - {GLFW_KEY_SPACE, KeyCode::Space}, - {GLFW_KEY_APOSTROPHE, KeyCode::Apostrophe}, - {GLFW_KEY_COMMA, KeyCode::Comma}, - {GLFW_KEY_MINUS, KeyCode::Minus}, - {GLFW_KEY_PERIOD, KeyCode::Period}, - {GLFW_KEY_SLASH, KeyCode::Slash}, - {GLFW_KEY_0, KeyCode::_0}, - {GLFW_KEY_1, KeyCode::_1}, - {GLFW_KEY_2, KeyCode::_2}, - {GLFW_KEY_3, KeyCode::_3}, - {GLFW_KEY_4, KeyCode::_4}, - {GLFW_KEY_5, KeyCode::_5}, - {GLFW_KEY_6, KeyCode::_6}, - {GLFW_KEY_7, KeyCode::_7}, - {GLFW_KEY_8, KeyCode::_8}, - {GLFW_KEY_9, KeyCode::_9}, - {GLFW_KEY_SEMICOLON, KeyCode::Semicolon}, - {GLFW_KEY_EQUAL, KeyCode::Equal}, - {GLFW_KEY_A, KeyCode::A}, - {GLFW_KEY_B, KeyCode::B}, - {GLFW_KEY_C, KeyCode::C}, - {GLFW_KEY_D, KeyCode::D}, - {GLFW_KEY_E, KeyCode::E}, - {GLFW_KEY_F, KeyCode::F}, - {GLFW_KEY_G, KeyCode::G}, - {GLFW_KEY_H, KeyCode::H}, - {GLFW_KEY_I, KeyCode::I}, - {GLFW_KEY_J, KeyCode::J}, - {GLFW_KEY_K, KeyCode::K}, - {GLFW_KEY_L, KeyCode::L}, - {GLFW_KEY_M, KeyCode::M}, - {GLFW_KEY_N, KeyCode::N}, - {GLFW_KEY_O, KeyCode::O}, - {GLFW_KEY_P, KeyCode::P}, - {GLFW_KEY_Q, KeyCode::Q}, - {GLFW_KEY_R, KeyCode::R}, - {GLFW_KEY_S, KeyCode::S}, - {GLFW_KEY_T, KeyCode::T}, - {GLFW_KEY_U, KeyCode::U}, - {GLFW_KEY_V, KeyCode::V}, - {GLFW_KEY_W, KeyCode::W}, - {GLFW_KEY_X, KeyCode::X}, - {GLFW_KEY_Y, KeyCode::Y}, - {GLFW_KEY_Z, KeyCode::Z}, - {GLFW_KEY_LEFT_BRACKET, KeyCode::LeftBracket}, - {GLFW_KEY_BACKSLASH, KeyCode::Backslash}, - {GLFW_KEY_RIGHT_BRACKET, KeyCode::RightBracket}, - {GLFW_KEY_GRAVE_ACCENT, KeyCode::GraveAccent}, - {GLFW_KEY_ESCAPE, KeyCode::Escape}, - {GLFW_KEY_ENTER, KeyCode::Enter}, - {GLFW_KEY_TAB, KeyCode::Tab}, - {GLFW_KEY_BACKSPACE, KeyCode::Backspace}, - {GLFW_KEY_INSERT, KeyCode::Insert}, - {GLFW_KEY_DELETE, KeyCode::DelKey}, - {GLFW_KEY_RIGHT, KeyCode::Right}, - {GLFW_KEY_LEFT, KeyCode::Left}, - {GLFW_KEY_DOWN, KeyCode::Down}, - {GLFW_KEY_UP, KeyCode::Up}, - {GLFW_KEY_PAGE_UP, KeyCode::PageUp}, - {GLFW_KEY_PAGE_DOWN, KeyCode::PageDown}, - {GLFW_KEY_HOME, KeyCode::Home}, - {GLFW_KEY_END, KeyCode::End}, - {GLFW_KEY_CAPS_LOCK, KeyCode::CapsLock}, - {GLFW_KEY_SCROLL_LOCK, KeyCode::ScrollLock}, - {GLFW_KEY_NUM_LOCK, KeyCode::NumLock}, - {GLFW_KEY_PRINT_SCREEN, KeyCode::PrintScreen}, - {GLFW_KEY_PAUSE, KeyCode::Pause}, - {GLFW_KEY_F1, KeyCode::F1}, - {GLFW_KEY_F2, KeyCode::F2}, - {GLFW_KEY_F3, KeyCode::F3}, - {GLFW_KEY_F4, KeyCode::F4}, - {GLFW_KEY_F5, KeyCode::F5}, - {GLFW_KEY_F6, KeyCode::F6}, - {GLFW_KEY_F7, KeyCode::F7}, - {GLFW_KEY_F8, KeyCode::F8}, - {GLFW_KEY_F9, KeyCode::F9}, - {GLFW_KEY_F10, KeyCode::F10}, - {GLFW_KEY_F11, KeyCode::F11}, - {GLFW_KEY_F12, KeyCode::F12}, - {GLFW_KEY_KP_0, KeyCode::KP_0}, - {GLFW_KEY_KP_1, KeyCode::KP_1}, - {GLFW_KEY_KP_2, KeyCode::KP_2}, - {GLFW_KEY_KP_3, KeyCode::KP_3}, - {GLFW_KEY_KP_4, KeyCode::KP_4}, - {GLFW_KEY_KP_5, KeyCode::KP_5}, - {GLFW_KEY_KP_6, KeyCode::KP_6}, - {GLFW_KEY_KP_7, KeyCode::KP_7}, - {GLFW_KEY_KP_8, KeyCode::KP_8}, - {GLFW_KEY_KP_9, KeyCode::KP_9}, - {GLFW_KEY_KP_DECIMAL, KeyCode::KP_Decimal}, - {GLFW_KEY_KP_DIVIDE, KeyCode::KP_Divide}, - {GLFW_KEY_KP_MULTIPLY, KeyCode::KP_Multiply}, - {GLFW_KEY_KP_SUBTRACT, KeyCode::KP_Subtract}, - {GLFW_KEY_KP_ADD, KeyCode::KP_Add}, - {GLFW_KEY_KP_ENTER, KeyCode::KP_Enter}, - {GLFW_KEY_KP_EQUAL, KeyCode::KP_Equal}, - {GLFW_KEY_LEFT_SHIFT, KeyCode::LeftShift}, - {GLFW_KEY_LEFT_CONTROL, KeyCode::LeftControl}, - {GLFW_KEY_LEFT_ALT, KeyCode::LeftAlt}, - {GLFW_KEY_RIGHT_SHIFT, KeyCode::RightShift}, - {GLFW_KEY_RIGHT_CONTROL, KeyCode::RightControl}, - {GLFW_KEY_RIGHT_ALT, KeyCode::RightAlt}, - }; + static const std::unordered_map key_lookup = { + {GLFW_KEY_SPACE, KeyCode::Space}, + {GLFW_KEY_APOSTROPHE, KeyCode::Apostrophe}, + {GLFW_KEY_COMMA, KeyCode::Comma}, + {GLFW_KEY_MINUS, KeyCode::Minus}, + {GLFW_KEY_PERIOD, KeyCode::Period}, + {GLFW_KEY_SLASH, KeyCode::Slash}, + {GLFW_KEY_0, KeyCode::_0}, + {GLFW_KEY_1, KeyCode::_1}, + {GLFW_KEY_2, KeyCode::_2}, + {GLFW_KEY_3, KeyCode::_3}, + {GLFW_KEY_4, KeyCode::_4}, + {GLFW_KEY_5, KeyCode::_5}, + {GLFW_KEY_6, KeyCode::_6}, + {GLFW_KEY_7, KeyCode::_7}, + {GLFW_KEY_8, KeyCode::_8}, + {GLFW_KEY_9, KeyCode::_9}, + {GLFW_KEY_SEMICOLON, KeyCode::Semicolon}, + {GLFW_KEY_EQUAL, KeyCode::Equal}, + {GLFW_KEY_A, KeyCode::A}, + {GLFW_KEY_B, KeyCode::B}, + {GLFW_KEY_C, KeyCode::C}, + {GLFW_KEY_D, KeyCode::D}, + {GLFW_KEY_E, KeyCode::E}, + {GLFW_KEY_F, KeyCode::F}, + {GLFW_KEY_G, KeyCode::G}, + {GLFW_KEY_H, KeyCode::H}, + {GLFW_KEY_I, KeyCode::I}, + {GLFW_KEY_J, KeyCode::J}, + {GLFW_KEY_K, KeyCode::K}, + {GLFW_KEY_L, KeyCode::L}, + {GLFW_KEY_M, KeyCode::M}, + {GLFW_KEY_N, KeyCode::N}, + {GLFW_KEY_O, KeyCode::O}, + {GLFW_KEY_P, KeyCode::P}, + {GLFW_KEY_Q, KeyCode::Q}, + {GLFW_KEY_R, KeyCode::R}, + {GLFW_KEY_S, KeyCode::S}, + {GLFW_KEY_T, KeyCode::T}, + {GLFW_KEY_U, KeyCode::U}, + {GLFW_KEY_V, KeyCode::V}, + {GLFW_KEY_W, KeyCode::W}, + {GLFW_KEY_X, KeyCode::X}, + {GLFW_KEY_Y, KeyCode::Y}, + {GLFW_KEY_Z, KeyCode::Z}, + {GLFW_KEY_LEFT_BRACKET, KeyCode::LeftBracket}, + {GLFW_KEY_BACKSLASH, KeyCode::Backslash}, + {GLFW_KEY_RIGHT_BRACKET, KeyCode::RightBracket}, + {GLFW_KEY_GRAVE_ACCENT, KeyCode::GraveAccent}, + {GLFW_KEY_ESCAPE, KeyCode::Escape}, + {GLFW_KEY_ENTER, KeyCode::Enter}, + {GLFW_KEY_TAB, KeyCode::Tab}, + {GLFW_KEY_BACKSPACE, KeyCode::Backspace}, + {GLFW_KEY_INSERT, KeyCode::Insert}, + {GLFW_KEY_DELETE, KeyCode::DelKey}, + {GLFW_KEY_RIGHT, KeyCode::Right}, + {GLFW_KEY_LEFT, KeyCode::Left}, + {GLFW_KEY_DOWN, KeyCode::Down}, + {GLFW_KEY_UP, KeyCode::Up}, + {GLFW_KEY_PAGE_UP, KeyCode::PageUp}, + {GLFW_KEY_PAGE_DOWN, KeyCode::PageDown}, + {GLFW_KEY_HOME, KeyCode::Home}, + {GLFW_KEY_END, KeyCode::End}, + {GLFW_KEY_CAPS_LOCK, KeyCode::CapsLock}, + {GLFW_KEY_SCROLL_LOCK, KeyCode::ScrollLock}, + {GLFW_KEY_NUM_LOCK, KeyCode::NumLock}, + {GLFW_KEY_PRINT_SCREEN, KeyCode::PrintScreen}, + {GLFW_KEY_PAUSE, KeyCode::Pause}, + {GLFW_KEY_F1, KeyCode::F1}, + {GLFW_KEY_F2, KeyCode::F2}, + {GLFW_KEY_F3, KeyCode::F3}, + {GLFW_KEY_F4, KeyCode::F4}, + {GLFW_KEY_F5, KeyCode::F5}, + {GLFW_KEY_F6, KeyCode::F6}, + {GLFW_KEY_F7, KeyCode::F7}, + {GLFW_KEY_F8, KeyCode::F8}, + {GLFW_KEY_F9, KeyCode::F9}, + {GLFW_KEY_F10, KeyCode::F10}, + {GLFW_KEY_F11, KeyCode::F11}, + {GLFW_KEY_F12, KeyCode::F12}, + {GLFW_KEY_KP_0, KeyCode::KP_0}, + {GLFW_KEY_KP_1, KeyCode::KP_1}, + {GLFW_KEY_KP_2, KeyCode::KP_2}, + {GLFW_KEY_KP_3, KeyCode::KP_3}, + {GLFW_KEY_KP_4, KeyCode::KP_4}, + {GLFW_KEY_KP_5, KeyCode::KP_5}, + {GLFW_KEY_KP_6, KeyCode::KP_6}, + {GLFW_KEY_KP_7, KeyCode::KP_7}, + {GLFW_KEY_KP_8, KeyCode::KP_8}, + {GLFW_KEY_KP_9, KeyCode::KP_9}, + {GLFW_KEY_KP_DECIMAL, KeyCode::KP_Decimal}, + {GLFW_KEY_KP_DIVIDE, KeyCode::KP_Divide}, + {GLFW_KEY_KP_MULTIPLY, KeyCode::KP_Multiply}, + {GLFW_KEY_KP_SUBTRACT, KeyCode::KP_Subtract}, + {GLFW_KEY_KP_ADD, KeyCode::KP_Add}, + {GLFW_KEY_KP_ENTER, KeyCode::KP_Enter}, + {GLFW_KEY_KP_EQUAL, KeyCode::KP_Equal}, + {GLFW_KEY_LEFT_SHIFT, KeyCode::LeftShift}, + {GLFW_KEY_LEFT_CONTROL, KeyCode::LeftControl}, + {GLFW_KEY_LEFT_ALT, KeyCode::LeftAlt}, + {GLFW_KEY_RIGHT_SHIFT, KeyCode::RightShift}, + {GLFW_KEY_RIGHT_CONTROL, KeyCode::RightControl}, + {GLFW_KEY_RIGHT_ALT, KeyCode::RightAlt}, + }; auto key_it = key_lookup.find(key); @@ -235,11 +234,7 @@ void cursor_position_callback(GLFWwindow *window, double xpos, double ypos) { if (auto *platform = reinterpret_cast(glfwGetWindowUserPointer(window))) { - platform->input_event(MouseButtonInputEvent{ - MouseButton::Unknown, - MouseAction::Move, - static_cast(xpos), - static_cast(ypos)}); + platform->input_event(MouseButtonInputEvent{MouseButton::Unknown, MouseAction::Move, static_cast(xpos), static_cast(ypos)}); } } @@ -252,17 +247,12 @@ void mouse_button_callback(GLFWwindow *window, int button, int action, int /*mod double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); - platform->input_event(MouseButtonInputEvent{ - translate_mouse_button(button), - mouse_action, - static_cast(xpos), - static_cast(ypos)}); + platform->input_event(MouseButtonInputEvent{translate_mouse_button(button), mouse_action, static_cast(xpos), static_cast(ypos)}); } } } // namespace -GlfwWindow::GlfwWindow(Platform *platform, const Window::Properties &properties) : - Window(properties) +GlfwWindow::GlfwWindow(Platform *platform, const Window::Properties &properties) : Window(properties) { #if defined(VK_USE_PLATFORM_XLIB_KHR) glfwInitHint(GLFW_X11_XCB_VULKAN_SURFACE, false); diff --git a/framework/platform/headless_window.cpp b/framework/platform/headless_window.cpp index 5d23b0cb32..d4c2b71a6f 100644 --- a/framework/platform/headless_window.cpp +++ b/framework/platform/headless_window.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -19,10 +19,8 @@ namespace vkb { -HeadlessWindow::HeadlessWindow(const Window::Properties &properties) : - Window(properties) -{ -} +HeadlessWindow::HeadlessWindow(const Window::Properties &properties) : Window(properties) +{} VkSurfaceKHR HeadlessWindow::create_surface(vkb::core::InstanceC &instance) { diff --git a/framework/platform/input_events.cpp b/framework/platform/input_events.cpp index 5772470ce0..58886bd905 100644 --- a/framework/platform/input_events.cpp +++ b/framework/platform/input_events.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2021, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -19,22 +19,16 @@ namespace vkb { -InputEvent::InputEvent(EventSource source) : - source{source} -{ -} +InputEvent::InputEvent(EventSource source) : source{source} +{} EventSource InputEvent::get_source() const { return source; } -KeyInputEvent::KeyInputEvent(KeyCode code, KeyAction action) : - InputEvent{EventSource::Keyboard}, - code{code}, - action{action} -{ -} +KeyInputEvent::KeyInputEvent(KeyCode code, KeyAction action) : InputEvent{EventSource::Keyboard}, code{code}, action{action} +{} KeyCode KeyInputEvent::get_code() const { @@ -47,13 +41,8 @@ KeyAction KeyInputEvent::get_action() const } MouseButtonInputEvent::MouseButtonInputEvent(MouseButton button, MouseAction action, float pos_x, float pos_y) : - InputEvent{EventSource::Mouse}, - button{button}, - action{action}, - pos_x{pos_x}, - pos_y{pos_y} -{ -} + InputEvent{EventSource::Mouse}, button{button}, action{action}, pos_x{pos_x}, pos_y{pos_y} +{} MouseButton MouseButtonInputEvent::get_button() const { @@ -76,14 +65,8 @@ float MouseButtonInputEvent::get_pos_y() const } TouchInputEvent::TouchInputEvent(int32_t pointer_id, std::size_t touch_points, TouchAction action, float pos_x, float pos_y) : - InputEvent{EventSource::Touchscreen}, - action{action}, - pointer_id{pointer_id}, - touch_points{touch_points}, - pos_x{pos_x}, - pos_y{pos_y} -{ -} + InputEvent{EventSource::Touchscreen}, action{action}, pointer_id{pointer_id}, touch_points{touch_points}, pos_x{pos_x}, pos_y{pos_y} +{} TouchAction TouchInputEvent::get_action() const { diff --git a/framework/platform/ios/ios_platform.h b/framework/platform/ios/ios_platform.h index a7c13bc7c6..2c336cfc75 100644 --- a/framework/platform/ios/ios_platform.h +++ b/framework/platform/ios/ios_platform.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2024, Holochip Inc. +/* Copyright (c) 2023-2026, Holochip Inc. * * SPDX-License-Identifier: Apache-2.0 * @@ -24,15 +24,15 @@ namespace vkb class IosPlatform : public Platform { -public: - IosPlatform(const PlatformContext &context); - - virtual ~IosPlatform() = default; - - virtual const char *get_surface_extension(); - void* view; + public: + IosPlatform(const PlatformContext &context); -protected: - virtual void create_window(const Window::Properties &properties) override; + virtual ~IosPlatform() = default; + + virtual const char *get_surface_extension(); + void *view; + + protected: + virtual void create_window(const Window::Properties &properties) override; }; } // namespace vkb diff --git a/framework/platform/platform.cpp b/framework/platform/platform.cpp index 5ef0871fd4..da6fd13352 100644 --- a/framework/platform/platform.cpp +++ b/framework/platform/platform.cpp @@ -271,9 +271,7 @@ void Platform::update() delta_time = simulation_frame_time; } - active_app->update_overlay(delta_time, [=, this]() { - on_update_ui_overlay(*active_app->get_drawer()); - }); + active_app->update_overlay(delta_time, [=, this]() { on_update_ui_overlay(*active_app->get_drawer()); }); active_app->update(delta_time); if (auto *app = dynamic_cast(active_app.get())) @@ -499,8 +497,7 @@ void Platform::input_event(const InputEvent &input_event) { const auto &key_event = static_cast(input_event); - if (key_event.get_code() == KeyCode::Back || - key_event.get_code() == KeyCode::Escape) + if (key_event.get_code() == KeyCode::Back || key_event.get_code() == KeyCode::Escape) { close(); } diff --git a/framework/platform/plugins/plugin.h b/framework/platform/plugins/plugin.h index 433e5a6326..7bde00b804 100644 --- a/framework/platform/plugins/plugin.h +++ b/framework/platform/plugins/plugin.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors - * Copyright (c) 2023-2025, Mobica Limited +/* Copyright (c) 2020-2026, Arm Limited and Contributors + * Copyright (c) 2023-2026, Mobica Limited * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -62,7 +62,8 @@ struct Passive } // namespace tags /** - * @brief Associate how plugins can interact with each other. This interoperability is decided by comparing tags of different plugins. The plugins inclusion and exclusion lists are populated by this function + * @brief Associate how plugins can interact with each other. This interoperability is decided by comparing tags of different plugins. The plugins inclusion and + * exclusion lists are populated by this function * * @param plugins A list of plugins which are used together * @return std::vector A list of plugins which are used together diff --git a/framework/platform/plugins/plugin_base.h b/framework/platform/plugins/plugin_base.h index 41f910a7be..382d061c2d 100644 --- a/framework/platform/plugins/plugin_base.h +++ b/framework/platform/plugins/plugin_base.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors - * Copyright (c) 2023-2025, Mobica Limited +/* Copyright (c) 2020-2026, Arm Limited and Contributors + * Copyright (c) 2023-2026, Mobica Limited * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -41,7 +41,11 @@ template class PluginBase : public Plugin, public Tag { public: - PluginBase(const std::string name, const std::string description, const std::vector &hooks = {}, std::vector> const &commands = {}, std::vector> const &options = {}); + PluginBase(const std::string name, + const std::string description, + const std::vector &hooks = {}, + std::vector> const &commands = {}, + std::vector> const &options = {}); virtual ~PluginBase() = default; @@ -64,10 +68,13 @@ class PluginBase : public Plugin, public Tag }; template -PluginBase::PluginBase(const std::string name, const std::string description, const std::vector &hooks, std::vector> const &commands, std::vector> const &options) : +PluginBase::PluginBase(const std::string name, + const std::string description, + const std::vector &hooks, + std::vector> const &commands, + std::vector> const &options) : Plugin(name, description, commands, options), hooks{hooks} -{ -} +{} template bool PluginBase::has_tag(TagID id) const diff --git a/framework/platform/unix/direct_window.cpp b/framework/platform/unix/direct_window.cpp index 79e132c2e3..f3bdb42d51 100644 --- a/framework/platform/unix/direct_window.cpp +++ b/framework/platform/unix/direct_window.cpp @@ -29,135 +29,70 @@ namespace vkb { namespace { -static KeyCode key_map[] = { - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Backspace, - KeyCode::Tab, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Enter, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Escape, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Unknown, - KeyCode::Space, - KeyCode::_1, - KeyCode::Apostrophe, - KeyCode::Backslash, - KeyCode::_4, - KeyCode::_5, - KeyCode::_7, - KeyCode::Apostrophe, - KeyCode::_9, - KeyCode::_0, - KeyCode::_8, - KeyCode::Equal, - KeyCode::Comma, - KeyCode::Minus, - KeyCode::Period, - KeyCode::Slash, - KeyCode::_0, - KeyCode::_1, - KeyCode::_2, - KeyCode::_3, - KeyCode::_4, - KeyCode::_5, - KeyCode::_6, - KeyCode::_7, - KeyCode::_8, - KeyCode::_9, - KeyCode::Semicolon, - KeyCode::Semicolon, - KeyCode::Comma, - KeyCode::Equal, - KeyCode::Period, - KeyCode::Slash, - KeyCode::_2, - KeyCode::A, - KeyCode::B, - KeyCode::C, - KeyCode::D, - KeyCode::E, - KeyCode::F, - KeyCode::G, - KeyCode::H, - KeyCode::I, - KeyCode::J, - KeyCode::K, - KeyCode::L, - KeyCode::M, - KeyCode::N, - KeyCode::O, - KeyCode::P, - KeyCode::Q, - KeyCode::R, - KeyCode::S, - KeyCode::T, - KeyCode::U, - KeyCode::V, - KeyCode::W, - KeyCode::X, - KeyCode::Y, - KeyCode::Z, - KeyCode::LeftBracket, - KeyCode::Backslash, - KeyCode::RightBracket, - KeyCode::_6, - KeyCode::Minus, - KeyCode::GraveAccent, - KeyCode::A, - KeyCode::B, - KeyCode::C, - KeyCode::D, - KeyCode::E, - KeyCode::F, - KeyCode::G, - KeyCode::H, - KeyCode::I, - KeyCode::J, - KeyCode::K, - KeyCode::L, - KeyCode::M, - KeyCode::N, - KeyCode::O, - KeyCode::P, - KeyCode::Q, - KeyCode::R, - KeyCode::S, - KeyCode::T, - KeyCode::U, - KeyCode::V, - KeyCode::W, - KeyCode::X, - KeyCode::Y, - KeyCode::Z, - KeyCode::LeftBracket, - KeyCode::Backslash, - KeyCode::RightBracket, - KeyCode::GraveAccent, - KeyCode::Backspace}; +static KeyCode key_map[] = {KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Backspace, KeyCode::Tab, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Enter, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Escape, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Unknown, KeyCode::Unknown, + KeyCode::Space, KeyCode::_1, + KeyCode::Apostrophe, KeyCode::Backslash, + KeyCode::_4, KeyCode::_5, + KeyCode::_7, KeyCode::Apostrophe, + KeyCode::_9, KeyCode::_0, + KeyCode::_8, KeyCode::Equal, + KeyCode::Comma, KeyCode::Minus, + KeyCode::Period, KeyCode::Slash, + KeyCode::_0, KeyCode::_1, + KeyCode::_2, KeyCode::_3, + KeyCode::_4, KeyCode::_5, + KeyCode::_6, KeyCode::_7, + KeyCode::_8, KeyCode::_9, + KeyCode::Semicolon, KeyCode::Semicolon, + KeyCode::Comma, KeyCode::Equal, + KeyCode::Period, KeyCode::Slash, + KeyCode::_2, KeyCode::A, + KeyCode::B, KeyCode::C, + KeyCode::D, KeyCode::E, + KeyCode::F, KeyCode::G, + KeyCode::H, KeyCode::I, + KeyCode::J, KeyCode::K, + KeyCode::L, KeyCode::M, + KeyCode::N, KeyCode::O, + KeyCode::P, KeyCode::Q, + KeyCode::R, KeyCode::S, + KeyCode::T, KeyCode::U, + KeyCode::V, KeyCode::W, + KeyCode::X, KeyCode::Y, + KeyCode::Z, KeyCode::LeftBracket, + KeyCode::Backslash, KeyCode::RightBracket, + KeyCode::_6, KeyCode::Minus, + KeyCode::GraveAccent, KeyCode::A, + KeyCode::B, KeyCode::C, + KeyCode::D, KeyCode::E, + KeyCode::F, KeyCode::G, + KeyCode::H, KeyCode::I, + KeyCode::J, KeyCode::K, + KeyCode::L, KeyCode::M, + KeyCode::N, KeyCode::O, + KeyCode::P, KeyCode::Q, + KeyCode::R, KeyCode::S, + KeyCode::T, KeyCode::U, + KeyCode::V, KeyCode::W, + KeyCode::X, KeyCode::Y, + KeyCode::Z, KeyCode::LeftBracket, + KeyCode::Backslash, KeyCode::RightBracket, + KeyCode::GraveAccent, KeyCode::Backspace}; static KeyCode map_multichar_key(int tty_fd, KeyCode initial) { @@ -212,9 +147,7 @@ static KeyCode map_multichar_key(int tty_fd, KeyCode initial) } } // namespace -DirectWindow::DirectWindow(Platform *platform, const Window::Properties &properties) : - Window(properties), - platform{platform} +DirectWindow::DirectWindow(Platform *platform, const Window::Properties &properties) : Window(properties), platform{platform} { // Setup tty for reading keyboard from console if ((tty_fd = open("/dev/tty", O_RDWR | O_NDELAY)) > 0) @@ -332,31 +265,25 @@ static std::vector find_display_candidates(VkPhysicalDevice phys_dev, } // Eliminate modes that don't fit the plane capabilities - if (mode.parameters.visibleRegion.width > caps.maxDstExtent.width || - mode.parameters.visibleRegion.height > caps.maxDstExtent.height || - mode.parameters.visibleRegion.width < caps.minDstExtent.width || - mode.parameters.visibleRegion.height < caps.minDstExtent.height) + if (mode.parameters.visibleRegion.width > caps.maxDstExtent.width || mode.parameters.visibleRegion.height > caps.maxDstExtent.height || + mode.parameters.visibleRegion.width < caps.minDstExtent.width || mode.parameters.visibleRegion.height < caps.minDstExtent.height) { continue; } - if (window_mode == Window::Mode::Fullscreen || - window_mode == Window::Mode::FullscreenBorderless) + if (window_mode == Window::Mode::Fullscreen || window_mode == Window::Mode::FullscreenBorderless) { // For full-screen modes (where the src image is the same size as the // display) we must also check the src extents are valid. - if (mode.parameters.visibleRegion.width > caps.maxSrcExtent.width || - mode.parameters.visibleRegion.height > caps.maxSrcExtent.height || - mode.parameters.visibleRegion.width < caps.minSrcExtent.width || - mode.parameters.visibleRegion.height < caps.minSrcExtent.height) + if (mode.parameters.visibleRegion.width > caps.maxSrcExtent.width || mode.parameters.visibleRegion.height > caps.maxSrcExtent.height || + mode.parameters.visibleRegion.width < caps.minSrcExtent.width || mode.parameters.visibleRegion.height < caps.minSrcExtent.height) { continue; } } // Add to list of candidates - candidates.push_back(Candidate{display, *props, mode, caps, plane_index, - plane_properties[plane_index].currentStackIndex}); + candidates.push_back(Candidate{display, *props, mode, caps, plane_index, plane_properties[plane_index].currentStackIndex}); } } } @@ -394,8 +321,7 @@ VkSurfaceKHR DirectWindow::create_surface(VkInstance instance, VkPhysicalDevice { const Candidate &cand = candidates[c]; - uint32_t area = cand.display_props.physicalResolution.width * - cand.display_props.physicalResolution.height; + uint32_t area = cand.display_props.physicalResolution.width * cand.display_props.physicalResolution.height; uint32_t diff = abs(static_cast(area) - static_cast(wanted_area)); @@ -413,8 +339,7 @@ VkSurfaceKHR DirectWindow::create_surface(VkInstance instance, VkPhysicalDevice full_extent.height = best.mode.parameters.visibleRegion.height; VkExtent2D image_extent; - if (properties.mode == Window::Mode::Fullscreen || - properties.mode == Window::Mode::FullscreenBorderless) + if (properties.mode == Window::Mode::Fullscreen || properties.mode == Window::Mode::FullscreenBorderless) { // Fullscreen & Borderless options create a surface that matches the display size image_extent.width = full_extent.width; @@ -424,10 +349,8 @@ VkSurfaceKHR DirectWindow::create_surface(VkInstance instance, VkPhysicalDevice { // Normal and stretch options create a surface at the requested width & height // clamped to the plane capabilities in play - image_extent.width = std::min(best.caps.maxSrcExtent.width, - std::max(properties.extent.width, best.caps.minSrcExtent.width)); - image_extent.height = std::min(best.caps.maxSrcExtent.height, - std::max(properties.extent.height, best.caps.minSrcExtent.height)); + image_extent.width = std::min(best.caps.maxSrcExtent.width, std::max(properties.extent.width, best.caps.minSrcExtent.width)); + image_extent.height = std::min(best.caps.maxSrcExtent.height, std::max(properties.extent.height, best.caps.minSrcExtent.height)); } // Calculate the display DPI @@ -500,8 +423,7 @@ float DirectWindow::get_dpi_factor() const return dpi / win_base_density; } -bool DirectWindow::get_display_present_info(VkDisplayPresentInfoKHR *info, - uint32_t src_width, uint32_t src_height) const +bool DirectWindow::get_display_present_info(VkDisplayPresentInfoKHR *info, uint32_t src_width, uint32_t src_height) const { // Only stretch mode needs to supply a VkDisplayPresentInfoKHR if (properties.mode != Window::Mode::FullscreenStretch || !info) diff --git a/framework/platform/unix/direct_window.h b/framework/platform/unix/direct_window.h index 275d029d19..9064a5560a 100644 --- a/framework/platform/unix/direct_window.h +++ b/framework/platform/unix/direct_window.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -47,8 +47,7 @@ class DirectWindow : public Window virtual void close() override; - virtual bool get_display_present_info(VkDisplayPresentInfoKHR *info, - uint32_t src_width, uint32_t src_height) const override; + virtual bool get_display_present_info(VkDisplayPresentInfoKHR *info, uint32_t src_width, uint32_t src_height) const override; float get_dpi_factor() const override; diff --git a/framework/platform/unix/unix_d2d_platform.cpp b/framework/platform/unix/unix_d2d_platform.cpp index 88e0f2463c..e7da424461 100644 --- a/framework/platform/unix/unix_d2d_platform.cpp +++ b/framework/platform/unix/unix_d2d_platform.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2024, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -22,10 +22,8 @@ namespace vkb { -UnixD2DPlatform::UnixD2DPlatform(const PlatformContext &context) : - Platform{context} -{ -} +UnixD2DPlatform::UnixD2DPlatform(const PlatformContext &context) : Platform{context} +{} void UnixD2DPlatform::create_window(const Window::Properties &properties) { diff --git a/framework/platform/unix/unix_platform.cpp b/framework/platform/unix/unix_platform.cpp index 9fd7fda3e5..6b389bc8e0 100644 --- a/framework/platform/unix/unix_platform.cpp +++ b/framework/platform/unix/unix_platform.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2024, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -43,10 +43,8 @@ namespace vkb { -UnixPlatform::UnixPlatform(const PlatformContext &context, const UnixType &type) : - Platform{context}, type{type} -{ -} +UnixPlatform::UnixPlatform(const PlatformContext &context, const UnixType &type) : Platform{context}, type{type} +{} void UnixPlatform::create_window(const Window::Properties &properties) { diff --git a/framework/platform/window.cpp b/framework/platform/window.cpp index 72c800a1dd..06dea74621 100644 --- a/framework/platform/window.cpp +++ b/framework/platform/window.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2023, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,14 +21,11 @@ namespace vkb { -Window::Window(const Properties &properties) : - properties{properties} -{ -} +Window::Window(const Properties &properties) : properties{properties} +{} void Window::process_events() -{ -} +{} Window::Extent Window::resize(const Extent &new_extent) { @@ -56,8 +53,7 @@ Window::Mode Window::get_window_mode() const return properties.mode; } -bool Window::get_display_present_info(VkDisplayPresentInfoKHR *info, - uint32_t src_width, uint32_t src_height) const +bool Window::get_display_present_info(VkDisplayPresentInfoKHR *info, uint32_t src_width, uint32_t src_height) const { // Default is to not use the extra present info return false; diff --git a/framework/platform/window.h b/framework/platform/window.h index 0f16e7bf88..143b70b5a0 100644 --- a/framework/platform/window.h +++ b/framework/platform/window.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -140,8 +140,7 @@ class Window * @return true if the present info was filled in and should be used * @return false if the extra present info should not be used. info is left untouched. */ - virtual bool get_display_present_info(VkDisplayPresentInfoKHR *info, - uint32_t src_width, uint32_t src_height) const; + virtual bool get_display_present_info(VkDisplayPresentInfoKHR *info, uint32_t src_width, uint32_t src_height) const; virtual std::vector get_required_surface_extensions() const = 0; diff --git a/framework/platform/windows/windows_platform.cpp b/framework/platform/windows/windows_platform.cpp index eaaa37b933..03c32f77d8 100644 --- a/framework/platform/windows/windows_platform.cpp +++ b/framework/platform/windows/windows_platform.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2024, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -27,10 +27,8 @@ namespace vkb { -WindowsPlatform::WindowsPlatform(const PlatformContext &context) : - Platform(context) -{ -} +WindowsPlatform::WindowsPlatform(const PlatformContext &context) : Platform(context) +{} void WindowsPlatform::create_window(const Window::Properties &properties) { diff --git a/framework/rendering/hpp_pipeline_state.h b/framework/rendering/hpp_pipeline_state.h index eca1279e57..cba184fb06 100644 --- a/framework/rendering/hpp_pipeline_state.h +++ b/framework/rendering/hpp_pipeline_state.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -39,7 +39,8 @@ struct HPPColorBlendAttachmentState vk::BlendFactor src_alpha_blend_factor = vk::BlendFactor::eOne; vk::BlendFactor dst_alpha_blend_factor = vk::BlendFactor::eZero; vk::BlendOp alpha_blend_op = vk::BlendOp::eAdd; - vk::ColorComponentFlags color_write_mask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA; + vk::ColorComponentFlags color_write_mask = + vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA; }; struct HPPColorBlendState @@ -59,9 +60,10 @@ struct HPPStencilOpState struct HPPDepthStencilState { - vk::Bool32 depth_test_enable = true; - vk::Bool32 depth_write_enable = true; - vk::CompareOp depth_compare_op = vk::CompareOp::eGreater; // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept + vk::Bool32 depth_test_enable = true; + vk::Bool32 depth_write_enable = true; + vk::CompareOp depth_compare_op = + vk::CompareOp::eGreater; // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept vk::Bool32 depth_bounds_test_enable = false; vk::Bool32 stencil_test_enable = false; HPPStencilOpState front; diff --git a/framework/rendering/pipeline_state.cpp b/framework/rendering/pipeline_state.cpp index 15c4c476da..5c4ef9ec90 100644 --- a/framework/rendering/pipeline_state.cpp +++ b/framework/rendering/pipeline_state.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -30,8 +30,10 @@ bool operator==(const VkVertexInputBindingDescription &lhs, const VkVertexInputB bool operator==(const vkb::ColorBlendAttachmentState &lhs, const vkb::ColorBlendAttachmentState &rhs) { - return std::tie(lhs.alpha_blend_op, lhs.blend_enable, lhs.color_blend_op, lhs.color_write_mask, lhs.dst_alpha_blend_factor, lhs.dst_color_blend_factor, lhs.src_alpha_blend_factor, lhs.src_color_blend_factor) == - std::tie(rhs.alpha_blend_op, rhs.blend_enable, rhs.color_blend_op, rhs.color_write_mask, rhs.dst_alpha_blend_factor, rhs.dst_color_blend_factor, rhs.src_alpha_blend_factor, rhs.src_color_blend_factor); + return std::tie(lhs.alpha_blend_op, lhs.blend_enable, lhs.color_blend_op, lhs.color_write_mask, lhs.dst_alpha_blend_factor, lhs.dst_color_blend_factor, + lhs.src_alpha_blend_factor, lhs.src_color_blend_factor) == + std::tie(rhs.alpha_blend_op, rhs.blend_enable, rhs.color_blend_op, rhs.color_write_mask, rhs.dst_alpha_blend_factor, rhs.dst_color_blend_factor, + rhs.src_alpha_blend_factor, rhs.src_color_blend_factor); } bool operator!=(const vkb::StencilOpState &lhs, const vkb::StencilOpState &rhs) @@ -51,8 +53,9 @@ bool operator!=(const vkb::InputAssemblyState &lhs, const vkb::InputAssemblyStat bool operator!=(const vkb::RasterizationState &lhs, const vkb::RasterizationState &rhs) { - return std::tie(lhs.cull_mode, lhs.depth_bias_enable, lhs.depth_clamp_enable, lhs.front_face, lhs.front_face, lhs.polygon_mode, lhs.rasterizer_discard_enable) != - std::tie(rhs.cull_mode, rhs.depth_bias_enable, rhs.depth_clamp_enable, rhs.front_face, rhs.front_face, rhs.polygon_mode, rhs.rasterizer_discard_enable); + return std::tie(lhs.cull_mode, lhs.depth_bias_enable, lhs.depth_clamp_enable, lhs.front_face, lhs.front_face, lhs.polygon_mode, + lhs.rasterizer_discard_enable) != std::tie(rhs.cull_mode, rhs.depth_bias_enable, rhs.depth_clamp_enable, rhs.front_face, rhs.front_face, + rhs.polygon_mode, rhs.rasterizer_discard_enable); } bool operator!=(const vkb::ViewportState &lhs, const vkb::ViewportState &rhs) @@ -62,8 +65,9 @@ bool operator!=(const vkb::ViewportState &lhs, const vkb::ViewportState &rhs) bool operator!=(const vkb::MultisampleState &lhs, const vkb::MultisampleState &rhs) { - return std::tie(lhs.alpha_to_coverage_enable, lhs.alpha_to_one_enable, lhs.min_sample_shading, lhs.rasterization_samples, lhs.sample_mask, lhs.sample_shading_enable) != - std::tie(rhs.alpha_to_coverage_enable, rhs.alpha_to_one_enable, rhs.min_sample_shading, rhs.rasterization_samples, rhs.sample_mask, rhs.sample_shading_enable); + return std::tie(lhs.alpha_to_coverage_enable, lhs.alpha_to_one_enable, lhs.min_sample_shading, lhs.rasterization_samples, lhs.sample_mask, + lhs.sample_shading_enable) != std::tie(rhs.alpha_to_coverage_enable, rhs.alpha_to_one_enable, rhs.min_sample_shading, + rhs.rasterization_samples, rhs.sample_mask, rhs.sample_shading_enable); } bool operator!=(const vkb::DepthStencilState &lhs, const vkb::DepthStencilState &rhs) @@ -75,12 +79,9 @@ bool operator!=(const vkb::DepthStencilState &lhs, const vkb::DepthStencilState bool operator!=(const vkb::ColorBlendState &lhs, const vkb::ColorBlendState &rhs) { - return std::tie(lhs.logic_op, lhs.logic_op_enable) != std::tie(rhs.logic_op, rhs.logic_op_enable) || - lhs.attachments.size() != rhs.attachments.size() || + return std::tie(lhs.logic_op, lhs.logic_op_enable) != std::tie(rhs.logic_op, rhs.logic_op_enable) || lhs.attachments.size() != rhs.attachments.size() || !std::equal(lhs.attachments.begin(), lhs.attachments.end(), rhs.attachments.begin(), - [](const vkb::ColorBlendAttachmentState &lhs, const vkb::ColorBlendAttachmentState &rhs) { - return lhs == rhs; - }); + [](const vkb::ColorBlendAttachmentState &lhs, const vkb::ColorBlendAttachmentState &rhs) { return lhs == rhs; }); } namespace vkb diff --git a/framework/rendering/pipeline_state.h b/framework/rendering/pipeline_state.h index f6d189bfb7..9a7bde925d 100644 --- a/framework/rendering/pipeline_state.h +++ b/framework/rendering/pipeline_state.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -134,7 +134,8 @@ struct ColorBlendState std::vector attachments; }; -/// Helper class to create specialization constants for a Vulkan pipeline. The state tracks a pipeline globally, and not per shader. Two shaders using the same constant_id will have the same data. +/// Helper class to create specialization constants for a Vulkan pipeline. The state tracks a pipeline globally, and not per shader. Two shaders using the same +/// constant_id will have the same data. class SpecializationConstantState { public: diff --git a/framework/rendering/postprocessing_computepass.cpp b/framework/rendering/postprocessing_computepass.cpp index f4c83e6ea4..8a491ceb00 100644 --- a/framework/rendering/postprocessing_computepass.cpp +++ b/framework/rendering/postprocessing_computepass.cpp @@ -21,12 +21,11 @@ namespace vkb { -PostProcessingComputePass::PostProcessingComputePass(PostProcessingPipeline *parent, const ShaderSource &cs_source, const ShaderVariant &cs_variant, +PostProcessingComputePass::PostProcessingComputePass(PostProcessingPipeline *parent, + const ShaderSource &cs_source, + const ShaderVariant &cs_variant, std::shared_ptr &&default_sampler) : - PostProcessingPass{parent}, - cs_source{cs_source}, - cs_variant{cs_variant}, - default_sampler{std::move(default_sampler)} + PostProcessingPass{parent}, cs_source{cs_source}, cs_variant{cs_variant}, default_sampler{std::move(default_sampler)} { if (this->default_sampler == nullptr) { @@ -152,9 +151,7 @@ void PostProcessingComputePass::transition_images(vkb::core::CommandBufferC &com // use shader reflection to figure out which case, then transition // NOTE: Could add a readonly?> cache to make this faster? auto resource = std::find_if(pipeline_layout.get_resources().begin(), pipeline_layout.get_resources().end(), - [&storage](const auto &res) { - return res.set == 0 && res.name == storage.first; - }); + [&storage](const auto &res) { return res.set == 0 && res.name == storage.first; }); if (resource == pipeline_layout.get_resources().end()) { // No such storage image to bind @@ -220,8 +217,7 @@ void PostProcessingComputePass::draw(vkb::core::CommandBufferC &command_buffer, const VkFormatProperties fmtProps = get_render_context().get_device().get_gpu().get_format_properties(view.get_format()); bool has_linear_filter = (fmtProps.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT); - const auto &sampler = it.second.get_sampler() ? *it.second.get_sampler() : - (has_linear_filter ? *default_sampler : *default_sampler_nearest); + const auto &sampler = it.second.get_sampler() ? *it.second.get_sampler() : (has_linear_filter ? *default_sampler : *default_sampler_nearest); command_buffer.bind_image(view, sampler, 0, layout_binding->binding, 0); } diff --git a/framework/rendering/postprocessing_computepass.h b/framework/rendering/postprocessing_computepass.h index cf9b45e83e..3965da9bbb 100644 --- a/framework/rendering/postprocessing_computepass.h +++ b/framework/rendering/postprocessing_computepass.h @@ -35,7 +35,9 @@ using SampledImageMap = std::unordered_map; class PostProcessingComputePass : public PostProcessingPass { public: - PostProcessingComputePass(PostProcessingPipeline *parent, const ShaderSource &cs_source, const ShaderVariant &cs_variant = {}, + PostProcessingComputePass(PostProcessingPipeline *parent, + const ShaderSource &cs_source, + const ShaderVariant &cs_variant = {}, std::shared_ptr &&default_sampler = {}); PostProcessingComputePass(const PostProcessingComputePass &to_copy) = delete; diff --git a/framework/rendering/postprocessing_pass.cpp b/framework/rendering/postprocessing_pass.cpp index 385e0ad6ce..d8fd7adefc 100644 --- a/framework/rendering/postprocessing_pass.cpp +++ b/framework/rendering/postprocessing_pass.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,8 +21,7 @@ namespace vkb { -PostProcessingPassBase::PostProcessingPassBase(PostProcessingPipeline *parent) : - parent{parent} +PostProcessingPassBase::PostProcessingPassBase(PostProcessingPipeline *parent) : parent{parent} {} vkb::rendering::RenderContextC &PostProcessingPassBase::get_render_context() const diff --git a/framework/rendering/postprocessing_pipeline.cpp b/framework/rendering/postprocessing_pipeline.cpp index 83f7d81359..9579620de0 100644 --- a/framework/rendering/postprocessing_pipeline.cpp +++ b/framework/rendering/postprocessing_pipeline.cpp @@ -22,8 +22,7 @@ namespace vkb { PostProcessingPipeline::PostProcessingPipeline(vkb::rendering::RenderContextC &render_context, ShaderSource triangle_vs) : - render_context{&render_context}, - triangle_vs{std::move(triangle_vs)} + render_context{&render_context}, triangle_vs{std::move(triangle_vs)} {} void PostProcessingPipeline::draw(vkb::core::CommandBufferC &command_buffer, vkb::rendering::RenderTargetC &default_render_target) diff --git a/framework/rendering/postprocessing_renderpass.cpp b/framework/rendering/postprocessing_renderpass.cpp index 9cd7da2fe9..ed2f30ef72 100644 --- a/framework/rendering/postprocessing_renderpass.cpp +++ b/framework/rendering/postprocessing_renderpass.cpp @@ -29,9 +29,7 @@ PostProcessingSubpass::PostProcessingSubpass(PostProcessingRenderPass *par ShaderSource &&triangle_vs, ShaderSource &&fs, ShaderVariant &&fs_variant) : - Subpass(render_context, std::move(triangle_vs), std::move(fs)), - parent{parent}, - fs_variant{std::move(fs_variant)} + Subpass(render_context, std::move(triangle_vs), std::move(fs)), parent{parent}, fs_variant{std::move(fs_variant)} { set_disable_depth_stencil_attachment(true); @@ -174,8 +172,8 @@ void PostProcessingSubpass::draw(vkb::core::CommandBufferC &command_buffer) const VkFormatProperties fmtProps = get_render_context().get_device().get_gpu().get_format_properties(view.get_format()); bool has_linear_filter = (fmtProps.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT); - const auto &sampler = it.second.get_sampler() ? *it.second.get_sampler() : - (has_linear_filter ? *parent->default_sampler : *parent->default_sampler_nearest); + const auto &sampler = + it.second.get_sampler() ? *it.second.get_sampler() : (has_linear_filter ? *parent->default_sampler : *parent->default_sampler_nearest); command_buffer.bind_image(view, sampler, 0, layout_binding->binding, 0); } @@ -203,8 +201,7 @@ void PostProcessingSubpass::default_draw_func(vkb::core::CommandBufferC &command } PostProcessingRenderPass::PostProcessingRenderPass(PostProcessingPipeline *parent, std::unique_ptr &&default_sampler) : - PostProcessingPass{parent}, - default_sampler{std::move(default_sampler)} + PostProcessingPass{parent}, default_sampler{std::move(default_sampler)} { if (this->default_sampler == nullptr) { @@ -234,11 +231,10 @@ PostProcessingRenderPass::PostProcessingRenderPass(PostProcessingPipeline *paren } } -void PostProcessingRenderPass::update_load_stores( - const AttachmentSet &input_attachments, - const SampledAttachmentSet &sampled_attachments, - const AttachmentSet &output_attachments, - const vkb::rendering::RenderTargetC &fallback_render_target) +void PostProcessingRenderPass::update_load_stores(const AttachmentSet &input_attachments, + const SampledAttachmentSet &sampled_attachments, + const AttachmentSet &output_attachments, + const vkb::rendering::RenderTargetC &fallback_render_target) { if (!load_stores_dirty) { @@ -253,14 +249,13 @@ void PostProcessingRenderPass::update_load_stores( for (uint32_t j = 0; j < static_cast(render_target.get_attachments().size()); j++) { const bool is_input = input_attachments.find(j) != input_attachments.end(); - const bool is_sampled = std::ranges::find_if(sampled_attachments, - [&render_target, j](auto &pair) { - // NOTE: if RT not set, default is the currently-active one - auto *sampled_rt = pair.first ? pair.first : &render_target; - // unpack attachment - uint32_t attachment = pair.second & ATTACHMENT_BITMASK; - return attachment == j && sampled_rt == &render_target; - }) != sampled_attachments.end(); + const bool is_sampled = std::ranges::find_if(sampled_attachments, [&render_target, j](auto &pair) { + // NOTE: if RT not set, default is the currently-active one + auto *sampled_rt = pair.first ? pair.first : &render_target; + // unpack attachment + uint32_t attachment = pair.second & ATTACHMENT_BITMASK; + return attachment == j && sampled_rt == &render_target; + }) != sampled_attachments.end(); const bool is_output = output_attachments.find(j) != output_attachments.end(); VkAttachmentLoadOp load; @@ -357,8 +352,7 @@ void PostProcessingRenderPass::transition_attachments(const AttachmentSet continue; } - ensure_src_access(prev_pass_barrier_info.image_write_access, prev_pass_barrier_info.pipeline_stage, - prev_layout); + ensure_src_access(prev_pass_barrier_info.image_write_access, prev_pass_barrier_info.pipeline_stage, prev_layout); vkb::ImageMemoryBarrier barrier; barrier.old_layout = render_target.get_layout(input); @@ -405,8 +399,7 @@ void PostProcessingRenderPass::transition_attachments(const AttachmentSet } else { - ensure_src_access(prev_pass_barrier_info.image_read_access, prev_pass_barrier_info.pipeline_stage, - prev_layout); + ensure_src_access(prev_pass_barrier_info.image_read_access, prev_pass_barrier_info.pipeline_stage, prev_layout); } vkb::ImageMemoryBarrier barrier; @@ -497,10 +490,8 @@ void PostProcessingRenderPass::prepare_draw(vkb::core::CommandBufferC &command_b } } - transition_attachments(input_attachments, sampled_attachments, output_attachments, - command_buffer, fallback_render_target); - update_load_stores(input_attachments, sampled_attachments, output_attachments, - fallback_render_target); + transition_attachments(input_attachments, sampled_attachments, output_attachments, command_buffer, fallback_render_target); + update_load_stores(input_attachments, sampled_attachments, output_attachments, fallback_render_target); } void PostProcessingRenderPass::draw(vkb::core::CommandBufferC &command_buffer, vkb::rendering::RenderTargetC &default_render_target) diff --git a/framework/rendering/postprocessing_renderpass.h b/framework/rendering/postprocessing_renderpass.h index f19e418146..9e7582e6e4 100644 --- a/framework/rendering/postprocessing_renderpass.h +++ b/framework/rendering/postprocessing_renderpass.h @@ -251,9 +251,9 @@ class PostProcessingRenderPass : public PostProcessingPass PostProcessingSubpass &add_subpass(ConstructorArgs &&...args) { - ShaderSource vs_copy = get_triangle_vs(); - auto new_subpass = std::make_unique(this, get_render_context(), std::move(vs_copy), std::forward(args)...); - auto &new_subpass_ref = *new_subpass; + ShaderSource vs_copy = get_triangle_vs(); + auto new_subpass = std::make_unique(this, get_render_context(), std::move(vs_copy), std::forward(args)...); + auto &new_subpass_ref = *new_subpass; pipeline.add_subpass(std::move(new_subpass)); diff --git a/framework/rendering/render_context.h b/framework/rendering/render_context.h index 664c2ae592..94e806a2da 100644 --- a/framework/rendering/render_context.h +++ b/framework/rendering/render_context.h @@ -69,17 +69,20 @@ class RenderContext using QueueType = typename std::conditional::type; using SwapchainType = typename std::conditional::type; - using Extent2DType = typename std::conditional::type; - using FormatType = typename std::conditional::type; - using ImageCompressionFixedRateFlagsType = typename std::conditional::type; - using ImageCompressionFlagsType = typename std::conditional::type; - using ImageUsageFlagBitsType = typename std::conditional::type; - using PipelineStageFlagsType = typename std::conditional::type; - using PresentModeType = typename std::conditional::type; - using SemaphoreType = typename std::conditional::type; - using SurfaceFormatType = typename std::conditional::type; - using SurfaceTransformFlagBitsType = typename std::conditional::type; - using SurfaceType = typename std::conditional::type; + using Extent2DType = typename std::conditional::type; + using FormatType = typename std::conditional::type; + using ImageCompressionFixedRateFlagsType = + typename std::conditional::type; + using ImageCompressionFlagsType = + typename std::conditional::type; + using ImageUsageFlagBitsType = typename std::conditional::type; + using PipelineStageFlagsType = typename std::conditional::type; + using PresentModeType = typename std::conditional::type; + using SemaphoreType = typename std::conditional::type; + using SurfaceFormatType = typename std::conditional::type; + using SurfaceTransformFlagBitsType = + typename std::conditional::type; + using SurfaceType = typename std::conditional::type; /** * @brief Constructor @@ -184,7 +187,9 @@ class RenderContext * @param thread_count The number of threads in the application, necessary to allocate this many resource pools for each RenderFrame * @param create_render_target_func A function delegate, used to create a RenderTarget */ - void prepare(size_t thread_count = 1, typename vkb::rendering::RenderTarget::CreateFunc create_render_target_func = vkb::rendering::RenderTarget::DEFAULT_CREATE_FUNC); + void prepare(size_t thread_count = 1, + typename vkb::rendering::RenderTarget::CreateFunc create_render_target_func = + vkb::rendering::RenderTarget::DEFAULT_CREATE_FUNC); /** * @brief Recreates the RenderFrames, called after every update @@ -260,7 +265,10 @@ class RenderContext virtual void wait_frame(); private: - void initialize_swapchain(vk::SurfaceKHR surface, vk::PresentModeKHR present_movde, std::vector const &present_mode_priority_list, std::vector const &surface_format_priority_list); + void initialize_swapchain(vk::SurfaceKHR surface, + vk::PresentModeKHR present_movde, + std::vector const &present_mode_priority_list, + std::vector const &surface_format_priority_list); void submit_impl(const std::vector> &command_buffers); vk::Semaphore submit_impl(vkb::core::HPPQueue const &queue, std::vector> const &command_buffers, @@ -278,12 +286,12 @@ class RenderContext std::vector> frames; vk::SurfaceTransformFlagBitsKHR pre_transform = vk::SurfaceTransformFlagBitsKHR::eIdentity; bool prepared = false; - const vkb::core::HPPQueue &queue; // If swapchain exists, then this will be a present supported queue, else a graphics queue - vk::Extent2D surface_extent; - std::unique_ptr swapchain; - vkb::core::HPPSwapchainProperties swapchain_properties; - size_t thread_count = 1; - const vkb::Window &window; + const vkb::core::HPPQueue &queue; // If swapchain exists, then this will be a present supported queue, else a graphics queue + vk::Extent2D surface_extent; + std::unique_ptr swapchain; + vkb::core::HPPSwapchainProperties swapchain_properties; + size_t thread_count = 1; + const vkb::Window &window; }; using RenderContextC = RenderContext; @@ -318,8 +326,7 @@ inline RenderContextC::RenderContext(vkb::core::DeviceC &devi queue(reinterpret_cast(device.get_queue_by_flags(VK_QUEUE_GRAPHICS_BIT, 0))), surface_extent{window.get_extent().width, window.get_extent().height} { - initialize_swapchain(static_cast(surface), - static_cast(present_mode), + initialize_swapchain(static_cast(surface), static_cast(present_mode), reinterpret_cast const &>(present_mode_priority_list), reinterpret_cast const &>(surface_format_priority_list)); } @@ -336,8 +343,8 @@ inline void RenderContext::initialize_swapchain(vk::SurfaceKHR if (surface_properties.currentExtent.width == 0xFFFFFFFF) { - swapchain = - std::make_unique(device, surface, present_mode, present_mode_priority_list, surface_format_priority_list, surface_extent); + swapchain = std::make_unique(device, surface, present_mode, present_mode_priority_list, surface_format_priority_list, + surface_extent); } else { @@ -666,11 +673,9 @@ inline void RenderContext::prepare(size_t thread_count, typename vk // Otherwise, create a single RenderFrame swapchain = nullptr; - auto color_image = vkb::core::HPPImage{device, - vk::Extent3D{surface_extent.width, surface_extent.height, 1}, + auto color_image = vkb::core::HPPImage{device, vk::Extent3D{surface_extent.width, surface_extent.height, 1}, DEFAULT_VK_FORMAT, // We can use any format here that we like - vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, - VMA_MEMORY_USAGE_GPU_ONLY}; + vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferSrc, VMA_MEMORY_USAGE_GPU_ONLY}; std::unique_ptr render_target = create_render_target_func(std::move(color_image)); frames.emplace_back(std::make_unique(device, std::move(render_target), thread_count)); @@ -806,8 +811,7 @@ inline typename RenderContext::SemaphoreType { return static_cast(submit_impl(reinterpret_cast(queue), reinterpret_cast> const &>(command_buffers), - static_cast(wait_semaphore), - static_cast(wait_pipeline_stage))); + static_cast(wait_semaphore), static_cast(wait_pipeline_stage))); } } diff --git a/framework/rendering/render_frame.h b/framework/rendering/render_frame.h index 59c6e53fdf..ad1229e6d5 100644 --- a/framework/rendering/render_frame.h +++ b/framework/rendering/render_frame.h @@ -66,10 +66,11 @@ class RenderFrame using FenceType = typename std::conditional::type; using SemaphoreType = typename std::conditional::type; - using DescriptorSetLayoutType = typename std::conditional::type; - using FencePoolType = typename std::conditional::type; - using QueueType = typename std::conditional::type; - using SemaphorePoolType = typename std::conditional::type; + using DescriptorSetLayoutType = + typename std::conditional::type; + using FencePoolType = typename std::conditional::type; + using QueueType = typename std::conditional::type; + using SemaphorePoolType = typename std::conditional::type; public: RenderFrame(vkb::core::Device &device, std::unique_ptr> &&render_target, size_t thread_count = 1); @@ -96,8 +97,8 @@ class RenderFrame * @param thread_index Selects the thread's command pool used to manage the buffer * @return The command pool related to the current active frame */ - vkb::core::CommandPool &get_command_pool( - QueueType const &queue, vkb::CommandBufferResetMode reset_mode = vkb::CommandBufferResetMode::ResetPool, size_t thread_index = 0); + vkb::core::CommandPool & + get_command_pool(QueueType const &queue, vkb::CommandBufferResetMode reset_mode = vkb::CommandBufferResetMode::ResetPool, size_t thread_index = 0); vkb::core::Device &get_device(); FencePoolType &get_fence_pool(); @@ -158,15 +159,15 @@ class RenderFrame private: vkb::core::DeviceCpp &device; std::map>> buffer_pools; - std::map> command_pools; // Commands pools per queue family index - std::vector> descriptor_pools; // Descriptor pools per thread - std::vector> descriptor_sets; // Descriptor sets per thread - vkb::HPPFencePool fence_pool; - vkb::HPPSemaphorePool semaphore_pool; - std::unique_ptr swapchain_render_target; - size_t thread_count; - BufferAllocationStrategy buffer_allocation_strategy = BufferAllocationStrategy::MultipleAllocationsPerBuffer; - DescriptorManagementStrategy descriptor_management_strategy = DescriptorManagementStrategy::StoreInCache; + std::map> command_pools; // Commands pools per queue family index + std::vector> descriptor_pools; // Descriptor pools per thread + std::vector> descriptor_sets; // Descriptor sets per thread + vkb::HPPFencePool fence_pool; + vkb::HPPSemaphorePool semaphore_pool; + std::unique_ptr swapchain_render_target; + size_t thread_count; + BufferAllocationStrategy buffer_allocation_strategy = BufferAllocationStrategy::MultipleAllocationsPerBuffer; + DescriptorManagementStrategy descriptor_management_strategy = DescriptorManagementStrategy::StoreInCache; }; using RenderFrameC = RenderFrame; @@ -176,14 +177,20 @@ template inline RenderFrame::RenderFrame(vkb::core::Device &device_, std::unique_ptr> &&render_target, size_t thread_count) : - device(reinterpret_cast(device_)), fence_pool{device}, semaphore_pool{device}, thread_count{thread_count}, descriptor_pools(thread_count), descriptor_sets(thread_count) + device(reinterpret_cast(device_)), + fence_pool{device}, + semaphore_pool{device}, + thread_count{thread_count}, + descriptor_pools(thread_count), + descriptor_sets(thread_count) { static constexpr uint32_t BUFFER_POOL_BLOCK_SIZE = 256; // Block size of a buffer pool in kilobytes // A map of the supported usages to a multiplier for the BUFFER_POOL_BLOCK_SIZE static const std::unordered_map supported_usage_map = { {vk::BufferUsageFlagBits::eUniformBuffer, 1}, - {vk::BufferUsageFlagBits::eStorageBuffer, 2}, // x2 the size of BUFFER_POOL_BLOCK_SIZE since SSBOs are normally much larger than other types of buffers + {vk::BufferUsageFlagBits::eStorageBuffer, + 2}, // x2 the size of BUFFER_POOL_BLOCK_SIZE since SSBOs are normally much larger than other types of buffers {vk::BufferUsageFlagBits::eVertexBuffer, 1}, {vk::BufferUsageFlagBits::eIndexBuffer, 1}}; @@ -325,8 +332,8 @@ inline vkb::core::CommandPoolCpp & auto &command_pools = get_command_pools(queue, reset_mode); - auto command_pool_it = std::ranges::find_if( - command_pools, [&thread_index](vkb::core::CommandPoolCpp &cmd_pool) { return cmd_pool.get_thread_index() == thread_index; }); + auto command_pool_it = + std::ranges::find_if(command_pools, [&thread_index](vkb::core::CommandPoolCpp &cmd_pool) { return cmd_pool.get_thread_index() == thread_index; }); assert(command_pool_it != command_pools.end()); return *command_pool_it; @@ -424,11 +431,12 @@ inline typename RenderFrame::SemaphorePoolType const &RenderFrame -inline typename RenderFrame::DescriptorSetType RenderFrame::request_descriptor_set(DescriptorSetLayoutType const &descriptor_set_layout, - BindingMap const &buffer_infos, - BindingMap const &image_infos, - bool update_after_bind, - size_t thread_index) +inline typename RenderFrame::DescriptorSetType + RenderFrame::request_descriptor_set(DescriptorSetLayoutType const &descriptor_set_layout, + BindingMap const &buffer_infos, + BindingMap const &image_infos, + bool update_after_bind, + size_t thread_index) { assert(thread_index < thread_count && "Thread index is out of bounds"); assert(thread_index < descriptor_pools.size()); @@ -442,8 +450,7 @@ inline typename RenderFrame::DescriptorSetType RenderFrame(request_descriptor_set_impl(reinterpret_cast(descriptor_set_layout), reinterpret_cast const &>(buffer_infos), reinterpret_cast const &>(image_infos), - update_after_bind, - thread_index)); + update_after_bind, thread_index)); } } diff --git a/framework/rendering/render_pipeline.h b/framework/rendering/render_pipeline.h index 2df95fd36f..54d6d411a8 100644 --- a/framework/rendering/render_pipeline.h +++ b/framework/rendering/render_pipeline.h @@ -67,7 +67,9 @@ class RenderPipeline /** * @brief Record draw commands for each Subpass */ - void draw(vkb::core::CommandBuffer &command_buffer, vkb::rendering::RenderTarget &render_target, SubpassContentsType contents = {}); + void draw(vkb::core::CommandBuffer &command_buffer, + vkb::rendering::RenderTarget &render_target, + SubpassContentsType contents = {}); /** * @return Subpass currently being recorded, or the first one if drawing has not started @@ -102,14 +104,15 @@ class RenderPipeline void set_load_store(const std::vector &load_store); private: - void draw_impl(vkb::core::CommandBufferCpp &command_buffer, - vkb::rendering::RenderTargetCpp &render_target, - vk::SubpassContents contents); + void draw_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::rendering::RenderTargetCpp &render_target, vk::SubpassContents contents); private: - size_t active_subpass_index = 0; - std::vector clear_value{vk::ClearColorValue{0.0f, 0.0f, 0.0f, 1.0f}, vk::ClearDepthStencilValue{0.0f, ~0U}}; // Defaults for swapchain and depth attachment - std::vector load_store{{vk::AttachmentLoadOp::eClear, vk::AttachmentStoreOp::eStore}, {vk::AttachmentLoadOp::eClear, vk::AttachmentStoreOp::eDontCare}}; // Defaults for swapchain and depth attachment + size_t active_subpass_index = 0; + std::vector clear_value{vk::ClearColorValue{0.0f, 0.0f, 0.0f, 1.0f}, + vk::ClearDepthStencilValue{0.0f, ~0U}}; // Defaults for swapchain and depth attachment + std::vector load_store{ + {vk::AttachmentLoadOp::eClear, vk::AttachmentStoreOp::eStore}, + {vk::AttachmentLoadOp::eClear, vk::AttachmentStoreOp::eDontCare}}; // Defaults for swapchain and depth attachment std::vector> subpasses; }; @@ -148,7 +151,9 @@ void RenderPipeline::add_subpass(std::unique_ptr -void RenderPipeline::draw(vkb::core::CommandBuffer &command_buffer, vkb::rendering::RenderTarget &render_target, SubpassContentsType contents) +void RenderPipeline::draw(vkb::core::CommandBuffer &command_buffer, + vkb::rendering::RenderTarget &render_target, + SubpassContentsType contents) { assert(!subpasses.empty() && "Render pipeline should contain at least one sub-pass"); @@ -164,8 +169,7 @@ void RenderPipeline::draw(vkb::core::CommandBuffer &co } else { - draw_impl(reinterpret_cast(command_buffer), - reinterpret_cast(render_target), + draw_impl(reinterpret_cast(command_buffer), reinterpret_cast(render_target), static_cast(contents)); } diff --git a/framework/rendering/render_target.h b/framework/rendering/render_target.h index 8ea9f395fc..df4261b346 100644 --- a/framework/rendering/render_target.h +++ b/framework/rendering/render_target.h @@ -98,12 +98,8 @@ struct Attachment ImageLayoutType initial_layout = default_image_layout(); Attachment() = default; - Attachment(FormatType format, SampleCountFlagBitsType samples, ImageUsageFlagsType usage) : - format{format}, - samples{samples}, - usage{usage} - { - } + Attachment(FormatType format, SampleCountFlagBitsType samples, ImageUsageFlagsType usage) : format{format}, samples{samples}, usage{usage} + {} }; using AttachmentC = Attachment; @@ -186,14 +182,16 @@ using RenderTargetCpp = RenderTarget; // Member function definitions template -inline typename RenderTarget::CreateFunc const RenderTarget::DEFAULT_CREATE_FUNC = [](ImageType &&swapchain_image) -> std::unique_ptr> { +inline typename RenderTarget::CreateFunc const RenderTarget::DEFAULT_CREATE_FUNC = + [](ImageType &&swapchain_image) -> std::unique_ptr> { if constexpr (bindingType == BindingType::Cpp) { return default_create_func_impl(std::move(swapchain_image)); } else { - return std::unique_ptr(reinterpret_cast(default_create_func_impl(std::move(reinterpret_cast(swapchain_image))).release())); + return std::unique_ptr( + reinterpret_cast(default_create_func_impl(std::move(reinterpret_cast(swapchain_image))).release())); } }; @@ -202,10 +200,8 @@ inline std::unique_ptr RenderTarget::default_creat { vk::Format depth_format = vkb::common::get_suitable_depth_format(swapchain_image.get_device().get_gpu().get_handle()); - vkb::core::HPPImage depth_image{swapchain_image.get_device(), swapchain_image.get_extent(), - depth_format, - vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment, - VMA_MEMORY_USAGE_GPU_ONLY}; + vkb::core::HPPImage depth_image{swapchain_image.get_device(), swapchain_image.get_extent(), depth_format, + vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment, VMA_MEMORY_USAGE_GPU_ONLY}; std::vector images; images.push_back(std::move(swapchain_image)); diff --git a/framework/rendering/subpass.h b/framework/rendering/subpass.h index 8efcce5d03..1c9e3c98ae 100644 --- a/framework/rendering/subpass.h +++ b/framework/rendering/subpass.h @@ -63,10 +63,9 @@ using LightingStateCpp = LightingState; */ glm::mat4 vulkan_style_projection(const glm::mat4 &proj); -inline const std::vector light_type_definitions = { - "DIRECTIONAL_LIGHT " + std::to_string(static_cast(sg::LightType::Directional)), - "POINT_LIGHT " + std::to_string(static_cast(sg::LightType::Point)), - "SPOT_LIGHT " + std::to_string(static_cast(sg::LightType::Spot))}; +inline const std::vector light_type_definitions = {"DIRECTIONAL_LIGHT " + std::to_string(static_cast(sg::LightType::Directional)), + "POINT_LIGHT " + std::to_string(static_cast(sg::LightType::Point)), + "SPOT_LIGHT " + std::to_string(static_cast(sg::LightType::Spot))}; /** * @brief This class defines an interface for subpasses @@ -79,8 +78,9 @@ class Subpass using ResolveModeFlagBitsType = typename std::conditional::type; using SampleCountflagBitsType = typename std::conditional::type; - using DepthStencilStateType = typename std::conditional::type; - using ShaderSourceType = typename std::conditional::type; + using DepthStencilStateType = + typename std::conditional::type; + using ShaderSourceType = typename std::conditional::type; public: Subpass(vkb::rendering::RenderContext &render_context, ShaderSourceType &&vertex_shader, ShaderSourceType &&fragment_shader); @@ -110,8 +110,7 @@ class Subpass * @param max_lights_per_type The maximum amount of lights allowed for any given type of light. */ template - void allocate_lights(const std::vector &scene_lights, - size_t max_lights_per_type); + void allocate_lights(const std::vector &scene_lights, size_t max_lights_per_type); const std::vector &get_color_resolve_attachments() const; const std::string &get_debug_name() const; @@ -297,8 +296,7 @@ inline const typename Subpass::ShaderSourceType &Subpass template -void Subpass::allocate_lights(const std::vector &scene_lights, - size_t max_lights_per_type) +void Subpass::allocate_lights(const std::vector &scene_lights, size_t max_lights_per_type) { lighting_state.directional_lights.clear(); lighting_state.point_lights.clear(); diff --git a/framework/rendering/subpasses/forward_subpass.h b/framework/rendering/subpasses/forward_subpass.h index d6fac5df9c..1a2b696cbf 100644 --- a/framework/rendering/subpasses/forward_subpass.h +++ b/framework/rendering/subpasses/forward_subpass.h @@ -112,7 +112,8 @@ inline void ForwardSubpass::prepare() { auto &variant = sub_mesh->get_mut_shader_variant(); auto &vert_module = device.get_resource_cache().request_shader_module(vk::ShaderStageFlagBits::eVertex, this->get_vertex_shader_impl(), variant); - auto &frag_module = device.get_resource_cache().request_shader_module(vk::ShaderStageFlagBits::eFragment, this->get_fragment_shader_impl(), variant); + auto &frag_module = + device.get_resource_cache().request_shader_module(vk::ShaderStageFlagBits::eFragment, this->get_fragment_shader_impl(), variant); } } } diff --git a/framework/rendering/subpasses/geometry_subpass.h b/framework/rendering/subpasses/geometry_subpass.h index 60f95545b9..f7167f2258 100644 --- a/framework/rendering/subpasses/geometry_subpass.h +++ b/framework/rendering/subpasses/geometry_subpass.h @@ -88,13 +88,14 @@ class GeometrySubpass : public vkb::rendering::Subpass public: using FrontFaceType = typename std::conditional::type; - using MeshType = typename std::conditional::type; - using PipelineLayoutType = typename std::conditional::type; - using RasterizationStateType = typename std::conditional::type; - using SceneType = typename std::conditional::type; - using ShaderModuleType = typename std::conditional::type; - using ShaderSourceType = typename std::conditional::type; - using SubMeshType = typename std::conditional::type; + using MeshType = typename std::conditional::type; + using PipelineLayoutType = typename std::conditional::type; + using RasterizationStateType = + typename std::conditional::type; + using SceneType = typename std::conditional::type; + using ShaderModuleType = typename std::conditional::type; + using ShaderSourceType = typename std::conditional::type; + using SubMeshType = typename std::conditional::type; public: /** @@ -127,7 +128,9 @@ class GeometrySubpass : public vkb::rendering::Subpass void set_thread_index(uint32_t index); protected: - void draw_submesh(vkb::core::CommandBuffer &command_buffer, SubMeshType &sub_mesh, FrontFaceType front_face = DefaultFrontFaceTypeValue::value); + void draw_submesh(vkb::core::CommandBuffer &command_buffer, + SubMeshType &sub_mesh, + FrontFaceType front_face = DefaultFrontFaceTypeValue::value); virtual void draw_submesh_command(vkb::core::CommandBuffer &command_buffer, SubMeshType &sub_mesh); vkb::sg::Camera const &get_camera() const; std::vector const &get_meshes() const; @@ -143,26 +146,27 @@ class GeometrySubpass : public vkb::rendering::Subpass uint32_t get_thread_index() const; void set_rasterization_state(const RasterizationStateType &rasterization_state); - virtual PipelineLayoutType &prepare_pipeline_layout(vkb::core::CommandBuffer &command_buffer, const std::vector &shader_modules); - virtual void prepare_pipeline_state(vkb::core::CommandBuffer &command_buffer, FrontFaceType front_face, bool double_sided_material); - virtual void prepare_push_constants(vkb::core::CommandBuffer &command_buffer, SubMeshType &sub_mesh); - virtual void update_uniform(vkb::core::CommandBuffer &command_buffer, vkb::scene_graph::Node &node, size_t thread_index); + virtual PipelineLayoutType &prepare_pipeline_layout(vkb::core::CommandBuffer &command_buffer, + const std::vector &shader_modules); + virtual void prepare_pipeline_state(vkb::core::CommandBuffer &command_buffer, FrontFaceType front_face, bool double_sided_material); + virtual void prepare_push_constants(vkb::core::CommandBuffer &command_buffer, SubMeshType &sub_mesh); + virtual void update_uniform(vkb::core::CommandBuffer &command_buffer, vkb::scene_graph::Node &node, size_t thread_index); protected: std::vector const &get_meshes_impl() const; private: - void draw_impl(vkb::core::CommandBufferCpp &command_buffer); - void draw_submesh_impl(vkb::core::CommandBufferCpp &command_buffer, - vkb::scene_graph::components::HPPSubMesh &sub_mesh, - vk::FrontFace front_face = vk::FrontFace::eCounterClockwise); - void get_sorted_nodes_impl(std::multimap> &opaque_nodes, - std::multimap> &transparent_nodes); + void draw_impl(vkb::core::CommandBufferCpp &command_buffer); + void draw_submesh_impl(vkb::core::CommandBufferCpp &command_buffer, + vkb::scene_graph::components::HPPSubMesh &sub_mesh, + vk::FrontFace front_face = vk::FrontFace::eCounterClockwise); + void get_sorted_nodes_impl(std::multimap> &opaque_nodes, + std::multimap> &transparent_nodes); vkb::core::HPPPipelineLayout &prepare_pipeline_layout_impl(vkb::core::CommandBufferCpp &command_buffer, const std::vector &shader_modules); - void prepare_pipeline_state_impl(vkb::core::CommandBufferCpp &command_buffer, vk::FrontFace front_face, bool double_sided_material); - virtual void prepare_push_constants_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::scene_graph::components::HPPSubMesh &sub_mesh); - void update_uniform_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::scene_graph::NodeCpp &node, size_t thread_index); + void prepare_pipeline_state_impl(vkb::core::CommandBufferCpp &command_buffer, vk::FrontFace front_face, bool double_sided_material); + virtual void prepare_push_constants_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::scene_graph::components::HPPSubMesh &sub_mesh); + void update_uniform_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::scene_graph::NodeCpp &node, size_t thread_index); private: vkb::rendering::HPPRasterizationState base_rasterization_state; @@ -230,8 +234,7 @@ inline void GeometrySubpass::draw_impl(vkb::core::CommandBufferCpp else { update_uniform(reinterpret_cast(command_buffer), - reinterpret_cast(*node_it->second.first), - thread_index); + reinterpret_cast(*node_it->second.first), thread_index); } // Invert the front face if the mesh was flipped @@ -270,8 +273,7 @@ inline void GeometrySubpass::draw_impl(vkb::core::CommandBufferCpp else { update_uniform(reinterpret_cast(command_buffer), - reinterpret_cast(*node_it->second.first), - thread_index); + reinterpret_cast(*node_it->second.first), thread_index); } draw_submesh_impl(command_buffer, *node_it->second.second); } @@ -302,8 +304,7 @@ inline void GeometrySubpass::set_thread_index(uint32_t index) } template -inline void - GeometrySubpass::draw_submesh(vkb::core::CommandBuffer &command_buffer, SubMeshType &sub_mesh, FrontFaceType front_face) +inline void GeometrySubpass::draw_submesh(vkb::core::CommandBuffer &command_buffer, SubMeshType &sub_mesh, FrontFaceType front_face) { if constexpr (bindingType == vkb::BindingType::Cpp) { @@ -312,8 +313,7 @@ inline void else { draw_submesh_impl(reinterpret_cast(command_buffer), - reinterpret_cast(sub_mesh), - static_cast(front_face)); + reinterpret_cast(sub_mesh), static_cast(front_face)); } } @@ -470,9 +470,8 @@ inline typename GeometrySubpass::PipelineLayoutType & } template -inline vkb::core::HPPPipelineLayout & - GeometrySubpass::prepare_pipeline_layout_impl(vkb::core::CommandBufferCpp &command_buffer, - const std::vector &shader_modules) +inline vkb::core::HPPPipelineLayout &GeometrySubpass::prepare_pipeline_layout_impl(vkb::core::CommandBufferCpp &command_buffer, + const std::vector &shader_modules) { // Sets any specified resource modes for (auto &shader_module : shader_modules) @@ -505,8 +504,8 @@ inline void GeometrySubpass::draw_submesh_impl(vkb::core::CommandBu } else { - prepare_pipeline_state( - reinterpret_cast(command_buffer), static_cast(front_face), sub_mesh.get_material()->is_double_sided()); + prepare_pipeline_state(reinterpret_cast(command_buffer), static_cast(front_face), + sub_mesh.get_material()->is_double_sided()); } vkb::rendering::HPPMultisampleState multisample_state{.rasterization_samples = this->get_sample_count_impl()}; @@ -542,8 +541,8 @@ inline void GeometrySubpass::draw_submesh_impl(vkb::core::CommandBu { if (auto layout_binding = descriptor_set_layout.get_layout_binding(texture.first)) { - command_buffer.bind_image( - texture.second->get_image()->get_vk_image_view(), texture.second->get_sampler()->get_core_sampler(), 0, layout_binding->binding, 0); + command_buffer.bind_image(texture.second->get_image()->get_vk_image_view(), texture.second->get_sampler()->get_core_sampler(), 0, + layout_binding->binding, 0); } } @@ -602,15 +601,14 @@ inline void GeometrySubpass::prepare_pipeline_state(vkb::core::Comm } else { - prepare_pipeline_state_impl( - reinterpret_cast(command_buffer), static_cast(front_face), double_sided_material); + prepare_pipeline_state_impl(reinterpret_cast(command_buffer), static_cast(front_face), + double_sided_material); } } template -inline void GeometrySubpass::prepare_pipeline_state_impl(vkb::core::CommandBufferCpp &command_buffer, - vk::FrontFace front_face, - bool double_sided_material) +inline void + GeometrySubpass::prepare_pipeline_state_impl(vkb::core::CommandBufferCpp &command_buffer, vk::FrontFace front_face, bool double_sided_material) { vkb::rendering::HPPRasterizationState rasterization_state = this->base_rasterization_state; rasterization_state.front_face = front_face; @@ -676,8 +674,7 @@ inline void GeometrySubpass::update_uniform(vkb::core::CommandBuffe } template -inline void - GeometrySubpass::update_uniform_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::scene_graph::NodeCpp &node, size_t thread_index) +inline void GeometrySubpass::update_uniform_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::scene_graph::NodeCpp &node, size_t thread_index) { GlobalUniform global_uniform; diff --git a/framework/rendering/subpasses/lighting_subpass.cpp b/framework/rendering/subpasses/lighting_subpass.cpp index 8f008f34f2..2784bb7a6c 100644 --- a/framework/rendering/subpasses/lighting_subpass.cpp +++ b/framework/rendering/subpasses/lighting_subpass.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -29,8 +29,7 @@ namespace vkb LightingSubpass::LightingSubpass( vkb::rendering::RenderContextC &render_context, ShaderSource &&vertex_shader, ShaderSource &&fragment_shader, sg::Camera &cam, sg::Scene &scene_) : Subpass{render_context, std::move(vertex_shader), std::move(fragment_shader)}, camera{cam}, scene{scene_} -{ -} +{} void LightingSubpass::prepare() { diff --git a/framework/resource_binding_state.cpp b/framework/resource_binding_state.cpp index 441bda57f6..3748d0786a 100644 --- a/framework/resource_binding_state.cpp +++ b/framework/resource_binding_state.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2024, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -41,7 +41,8 @@ void ResourceBindingState::clear_dirty(uint32_t set) resource_sets[set].clear_dirty(); } -void ResourceBindingState::bind_buffer(const vkb::core::BufferC &buffer, VkDeviceSize offset, VkDeviceSize range, uint32_t set, uint32_t binding, uint32_t array_element) +void ResourceBindingState::bind_buffer( + const vkb::core::BufferC &buffer, VkDeviceSize offset, VkDeviceSize range, uint32_t set, uint32_t binding, uint32_t array_element) { resource_sets[set].bind_buffer(buffer, offset, range, binding, array_element); diff --git a/framework/resource_cache.cpp b/framework/resource_cache.cpp index ea809672b4..80acd7e3fa 100644 --- a/framework/resource_cache.cpp +++ b/framework/resource_cache.cpp @@ -35,10 +35,8 @@ T &request_resource(vkb::core::DeviceC &device, ResourceRecord &recorder, std::m } } // namespace -ResourceCache::ResourceCache(vkb::core::DeviceC &device) : - device{device} -{ -} +ResourceCache::ResourceCache(vkb::core::DeviceC &device) : device{device} +{} void ResourceCache::warmup(const std::vector &data) { @@ -85,13 +83,17 @@ ComputePipeline &ResourceCache::request_compute_pipeline(PipelineState &pipeline return request_resource(device, recorder, compute_pipeline_mutex, state.compute_pipelines, pipeline_cache, pipeline_state); } -DescriptorSet &ResourceCache::request_descriptor_set(DescriptorSetLayout &descriptor_set_layout, const BindingMap &buffer_infos, const BindingMap &image_infos) +DescriptorSet &ResourceCache::request_descriptor_set(DescriptorSetLayout &descriptor_set_layout, + const BindingMap &buffer_infos, + const BindingMap &image_infos) { auto &descriptor_pool = request_resource(device, recorder, descriptor_set_mutex, state.descriptor_pools, descriptor_set_layout); return request_resource(device, recorder, descriptor_set_mutex, state.descriptor_sets, descriptor_set_layout, descriptor_pool, buffer_infos, image_infos); } -RenderPass &ResourceCache::request_render_pass(const std::vector &attachments, const std::vector &load_store_infos, const std::vector &subpasses) +RenderPass &ResourceCache::request_render_pass(const std::vector &attachments, + const std::vector &load_store_infos, + const std::vector &subpasses) { return request_resource(device, recorder, render_pass_mutex, state.render_passes, attachments, load_store_infos, subpasses); } @@ -171,8 +173,7 @@ void ResourceCache::update_descriptor_sets(const std::vector &o if (!set_updates.empty()) { - vkUpdateDescriptorSets(device.get_handle(), to_u32(set_updates.size()), set_updates.data(), - 0, nullptr); + vkUpdateDescriptorSets(device.get_handle(), to_u32(set_updates.size()), set_updates.data(), 0, nullptr); } // Delete old entries (moved out descriptor sets) diff --git a/framework/resource_cache.h b/framework/resource_cache.h index 8243a494cf..886014afe3 100644 --- a/framework/resource_cache.h +++ b/framework/resource_cache.h @@ -117,8 +117,7 @@ class ResourceCache const std::vector &load_store_infos, const std::vector &subpasses); - Framebuffer &request_framebuffer(const vkb::rendering::RenderTargetC &render_target, - const RenderPass &render_pass); + Framebuffer &request_framebuffer(const vkb::rendering::RenderTargetC &render_target, const RenderPass &render_pass); void clear_pipelines(); diff --git a/framework/resource_record.cpp b/framework/resource_record.cpp index 489ba126ff..b3bfae4692 100644 --- a/framework/resource_record.cpp +++ b/framework/resource_record.cpp @@ -55,7 +55,10 @@ const std::ostringstream &ResourceRecord::get_stream() return stream; } -size_t ResourceRecord::register_shader_module(VkShaderStageFlagBits stage, const ShaderSource &glsl_source, const std::string &entry_point, const ShaderVariant &shader_variant) +size_t ResourceRecord::register_shader_module(VkShaderStageFlagBits stage, + const ShaderSource &glsl_source, + const std::string &entry_point, + const ShaderVariant &shader_variant) { shader_module_indices.push_back(shader_module_indices.size()); @@ -72,21 +75,18 @@ size_t ResourceRecord::register_pipeline_layout(const std::vector &attachments, const std::vector &load_store_infos, const std::vector &subpasses) +size_t ResourceRecord::register_render_pass(const std::vector &attachments, + const std::vector &load_store_infos, + const std::vector &subpasses) { render_pass_indices.push_back(render_pass_indices.size()); - write(stream, - ResourceType::RenderPass, - attachments, - load_store_infos); + write(stream, ResourceType::RenderPass, attachments, load_store_infos); write_subpass_info(stream, subpasses); @@ -100,36 +100,23 @@ size_t ResourceRecord::register_graphics_pipeline(VkPipelineCache /*pipeline_cac auto &pipeline_layout = pipeline_state.get_pipeline_layout(); auto render_pass = pipeline_state.get_render_pass(); - write(stream, - ResourceType::GraphicsPipeline, - pipeline_layout_to_index.at(&pipeline_layout), - render_pass_to_index.at(render_pass), + write(stream, ResourceType::GraphicsPipeline, pipeline_layout_to_index.at(&pipeline_layout), render_pass_to_index.at(render_pass), pipeline_state.get_subpass_index()); auto &specialization_constant_state = pipeline_state.get_specialization_constant_state().get_specialization_constant_state(); - write(stream, - specialization_constant_state); + write(stream, specialization_constant_state); auto &vertex_input_state = pipeline_state.get_vertex_input_state(); - write(stream, - vertex_input_state.attributes, - vertex_input_state.bindings); + write(stream, vertex_input_state.attributes, vertex_input_state.bindings); - write(stream, - pipeline_state.get_input_assembly_state(), - pipeline_state.get_rasterization_state(), - pipeline_state.get_viewport_state(), - pipeline_state.get_multisample_state(), - pipeline_state.get_depth_stencil_state()); + write(stream, pipeline_state.get_input_assembly_state(), pipeline_state.get_rasterization_state(), pipeline_state.get_viewport_state(), + pipeline_state.get_multisample_state(), pipeline_state.get_depth_stencil_state()); auto &color_blend_state = pipeline_state.get_color_blend_state(); - write(stream, - color_blend_state.logic_op, - color_blend_state.logic_op_enable, - color_blend_state.attachments); + write(stream, color_blend_state.logic_op, color_blend_state.logic_op_enable, color_blend_state.attachments); return graphics_pipeline_indices.back(); } diff --git a/framework/resource_record.h b/framework/resource_record.h index a31832d53d..56f5239ab5 100644 --- a/framework/resource_record.h +++ b/framework/resource_record.h @@ -66,8 +66,7 @@ class ResourceRecord const std::vector &load_store_infos, const std::vector &subpasses); - size_t register_graphics_pipeline(VkPipelineCache pipeline_cache, - PipelineState &pipeline_state); + size_t register_graphics_pipeline(VkPipelineCache pipeline_cache, PipelineState &pipeline_state); void set_shader_module(size_t index, const ShaderModule &shader_module); diff --git a/framework/resource_replay.cpp b/framework/resource_replay.cpp index 6b39de5a00..5189814c9f 100644 --- a/framework/resource_replay.cpp +++ b/framework/resource_replay.cpp @@ -85,10 +85,7 @@ void ResourceReplay::create_shader_module(ResourceCache &resource_cache, std::is std::string glsl_source; std::string entry_point; - read(stream, - stage, - glsl_source, - entry_point); + read(stream, stage, glsl_source, entry_point); ShaderSource shader_source{}; shader_source.set_source(std::move(glsl_source)); @@ -103,17 +100,13 @@ void ResourceReplay::create_pipeline_layout(ResourceCache &resource_cache, std:: { std::vector shader_indices; - read(stream, - shader_indices); + read(stream, shader_indices); std::vector shader_stages(shader_indices.size()); - std::transform(shader_indices.begin(), - shader_indices.end(), - shader_stages.begin(), - [&](size_t shader_index) { - assert(shader_index < shader_modules.size()); - return shader_modules[shader_index]; - }); + std::transform(shader_indices.begin(), shader_indices.end(), shader_stages.begin(), [&](size_t shader_index) { + assert(shader_index < shader_modules.size()); + return shader_modules[shader_index]; + }); auto &pipeline_layout = resource_cache.request_pipeline_layout(shader_stages); @@ -126,9 +119,7 @@ void ResourceReplay::create_render_pass(ResourceCache &resource_cache, std::istr std::vector load_store_infos; std::vector subpasses; - read(stream, - attachments, - load_store_infos); + read(stream, attachments, load_store_infos); read_subpass_info(stream, subpasses); @@ -143,20 +134,14 @@ void ResourceReplay::create_graphics_pipeline(ResourceCache &resource_cache, std size_t render_pass_index{}; uint32_t subpass_index{}; - read(stream, - pipeline_layout_index, - render_pass_index, - subpass_index); + read(stream, pipeline_layout_index, render_pass_index, subpass_index); std::map> specialization_constant_state{}; - read(stream, - specialization_constant_state); + read(stream, specialization_constant_state); VertexInputState vertex_input_state{}; - read(stream, - vertex_input_state.attributes, - vertex_input_state.bindings); + read(stream, vertex_input_state.attributes, vertex_input_state.bindings); InputAssemblyState input_assembly_state{}; RasterizationState rasterization_state{}; @@ -164,19 +149,11 @@ void ResourceReplay::create_graphics_pipeline(ResourceCache &resource_cache, std MultisampleState multisample_state{}; DepthStencilState depth_stencil_state{}; - read(stream, - input_assembly_state, - rasterization_state, - viewport_state, - multisample_state, - depth_stencil_state); + read(stream, input_assembly_state, rasterization_state, viewport_state, multisample_state, depth_stencil_state); ColorBlendState color_blend_state{}; - read(stream, - color_blend_state.logic_op, - color_blend_state.logic_op_enable, - color_blend_state.attachments); + read(stream, color_blend_state.logic_op, color_blend_state.logic_op_enable, color_blend_state.attachments); PipelineState pipeline_state{}; assert(pipeline_layout_index < pipeline_layouts.size()); diff --git a/framework/scene_graph/component.cpp b/framework/scene_graph/component.cpp index 814110977d..574841ccdc 100644 --- a/framework/scene_graph/component.cpp +++ b/framework/scene_graph/component.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2019, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -25,8 +25,7 @@ namespace vkb { namespace sg { -Component::Component(const std::string &name) : - name{name} +Component::Component(const std::string &name) : name{name} {} const std::string &Component::get_name() const diff --git a/framework/scene_graph/components/aabb.cpp b/framework/scene_graph/components/aabb.cpp index 45420833da..7fcedaea47 100644 --- a/framework/scene_graph/components/aabb.cpp +++ b/framework/scene_graph/components/aabb.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2024, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -28,11 +28,8 @@ AABB::AABB() reset(); } -AABB::AABB(const glm::vec3 &min, const glm::vec3 &max) : - min{min}, - max{max} -{ -} +AABB::AABB(const glm::vec3 &min, const glm::vec3 &max) : min{min}, max{max} +{} std::type_index AABB::get_type() { diff --git a/framework/scene_graph/components/camera.cpp b/framework/scene_graph/components/camera.cpp index 4b3f9f74ca..c4e509337f 100644 --- a/framework/scene_graph/components/camera.cpp +++ b/framework/scene_graph/components/camera.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -24,8 +24,7 @@ namespace vkb { namespace sg { -Camera::Camera(const std::string &name) : - Component{name} +Camera::Camera(const std::string &name) : Component{name} {} std::type_index Camera::get_type() diff --git a/framework/scene_graph/components/hpp_image.cpp b/framework/scene_graph/components/hpp_image.cpp index e93348040b..51862e6e4d 100644 --- a/framework/scene_graph/components/hpp_image.cpp +++ b/framework/scene_graph/components/hpp_image.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -38,16 +38,12 @@ bool is_astc(const vk::Format format) } HPPImage::HPPImage(const std::string &name, std::vector &&d, std::vector &&m) : - Component{name}, - data{std::move(d)}, - format{vk::Format::eR8G8B8A8Unorm}, - mipmaps{std::move(m)} + Component{name}, data{std::move(d)}, format{vk::Format::eR8G8B8A8Unorm}, mipmaps{std::move(m)} { update_hash(); } -std::unique_ptr HPPImage::load(const std::string &name, const std::string &uri, - ContentType content_type) +std::unique_ptr HPPImage::load(const std::string &name, const std::string &uri, ContentType content_type) { std::unique_ptr image{nullptr}; @@ -204,16 +200,9 @@ void HPPImage::create_vk_image(vkb::core::DeviceCpp &device, vk::ImageViewType i { assert(!vk_image && !vk_image_view && "Vulkan HPPImage already constructed"); - vk_image = std::make_unique(device, - get_extent(), - format, - vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst, - VMA_MEMORY_USAGE_GPU_ONLY, - vk::SampleCountFlagBits::e1, - to_u32(mipmaps.size()), - layers, - vk::ImageTiling::eOptimal, - flags); + vk_image = std::make_unique(device, get_extent(), format, vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst, + VMA_MEMORY_USAGE_GPU_ONLY, vk::SampleCountFlagBits::e1, to_u32(mipmaps.size()), layers, + vk::ImageTiling::eOptimal, flags); vk_image->set_debug_name(get_name()); vk_image_view = std::make_unique(*vk_image, image_view_type); @@ -249,8 +238,8 @@ void HPPImage::generate_mipmaps() next_mipmap.extent = vk::Extent3D{next_width, next_height, 1u}; // Fill next mipmap memory - stbir_resize_uint8(data.data() + prev_mipmap.offset, prev_mipmap.extent.width, prev_mipmap.extent.height, 0, - data.data() + next_mipmap.offset, next_mipmap.extent.width, next_mipmap.extent.height, 0, channels); + stbir_resize_uint8(data.data() + prev_mipmap.offset, prev_mipmap.extent.width, prev_mipmap.extent.height, 0, data.data() + next_mipmap.offset, + next_mipmap.extent.width, next_mipmap.extent.height, 0, channels); mipmaps.emplace_back(std::move(next_mipmap)); diff --git a/framework/scene_graph/components/hpp_image.h b/framework/scene_graph/components/hpp_image.h index 86c59bd560..bc85b76ba2 100644 --- a/framework/scene_graph/components/hpp_image.h +++ b/framework/scene_graph/components/hpp_image.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -75,10 +75,10 @@ class HPPImage : public vkb::sg::Component // from Component virtual std::type_index get_type() override; - void clear_data(); - void coerce_format_to_srgb(); - void create_vk_image(vkb::core::DeviceCpp &device, vk::ImageViewType image_view_type = vk::ImageViewType::e2D, vk::ImageCreateFlags flags = {}); - void generate_mipmaps(); + void clear_data(); + void coerce_format_to_srgb(); + void create_vk_image(vkb::core::DeviceCpp &device, vk::ImageViewType image_view_type = vk::ImageViewType::e2D, vk::ImageCreateFlags flags = {}); + void generate_mipmaps(); const std::vector &get_data() const; const vk::Extent3D &get_extent() const; vk::Format get_format() const; diff --git a/framework/scene_graph/components/image.cpp b/framework/scene_graph/components/image.cpp index c67704855e..adaaf10cdd 100644 --- a/framework/scene_graph/components/image.cpp +++ b/framework/scene_graph/components/image.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -37,33 +37,15 @@ namespace sg { bool is_astc(const VkFormat format) { - return (format == VK_FORMAT_ASTC_4x4_UNORM_BLOCK || - format == VK_FORMAT_ASTC_4x4_SRGB_BLOCK || - format == VK_FORMAT_ASTC_5x4_UNORM_BLOCK || - format == VK_FORMAT_ASTC_5x4_SRGB_BLOCK || - format == VK_FORMAT_ASTC_5x5_UNORM_BLOCK || - format == VK_FORMAT_ASTC_5x5_SRGB_BLOCK || - format == VK_FORMAT_ASTC_6x5_UNORM_BLOCK || - format == VK_FORMAT_ASTC_6x5_SRGB_BLOCK || - format == VK_FORMAT_ASTC_6x6_UNORM_BLOCK || - format == VK_FORMAT_ASTC_6x6_SRGB_BLOCK || - format == VK_FORMAT_ASTC_8x5_UNORM_BLOCK || - format == VK_FORMAT_ASTC_8x5_SRGB_BLOCK || - format == VK_FORMAT_ASTC_8x6_UNORM_BLOCK || - format == VK_FORMAT_ASTC_8x6_SRGB_BLOCK || - format == VK_FORMAT_ASTC_8x8_UNORM_BLOCK || - format == VK_FORMAT_ASTC_8x8_SRGB_BLOCK || - format == VK_FORMAT_ASTC_10x5_UNORM_BLOCK || - format == VK_FORMAT_ASTC_10x5_SRGB_BLOCK || - format == VK_FORMAT_ASTC_10x6_UNORM_BLOCK || - format == VK_FORMAT_ASTC_10x6_SRGB_BLOCK || - format == VK_FORMAT_ASTC_10x8_UNORM_BLOCK || - format == VK_FORMAT_ASTC_10x8_SRGB_BLOCK || - format == VK_FORMAT_ASTC_10x10_UNORM_BLOCK || - format == VK_FORMAT_ASTC_10x10_SRGB_BLOCK || - format == VK_FORMAT_ASTC_12x10_UNORM_BLOCK || - format == VK_FORMAT_ASTC_12x10_SRGB_BLOCK || - format == VK_FORMAT_ASTC_12x12_UNORM_BLOCK || + return (format == VK_FORMAT_ASTC_4x4_UNORM_BLOCK || format == VK_FORMAT_ASTC_4x4_SRGB_BLOCK || format == VK_FORMAT_ASTC_5x4_UNORM_BLOCK || + format == VK_FORMAT_ASTC_5x4_SRGB_BLOCK || format == VK_FORMAT_ASTC_5x5_UNORM_BLOCK || format == VK_FORMAT_ASTC_5x5_SRGB_BLOCK || + format == VK_FORMAT_ASTC_6x5_UNORM_BLOCK || format == VK_FORMAT_ASTC_6x5_SRGB_BLOCK || format == VK_FORMAT_ASTC_6x6_UNORM_BLOCK || + format == VK_FORMAT_ASTC_6x6_SRGB_BLOCK || format == VK_FORMAT_ASTC_8x5_UNORM_BLOCK || format == VK_FORMAT_ASTC_8x5_SRGB_BLOCK || + format == VK_FORMAT_ASTC_8x6_UNORM_BLOCK || format == VK_FORMAT_ASTC_8x6_SRGB_BLOCK || format == VK_FORMAT_ASTC_8x8_UNORM_BLOCK || + format == VK_FORMAT_ASTC_8x8_SRGB_BLOCK || format == VK_FORMAT_ASTC_10x5_UNORM_BLOCK || format == VK_FORMAT_ASTC_10x5_SRGB_BLOCK || + format == VK_FORMAT_ASTC_10x6_UNORM_BLOCK || format == VK_FORMAT_ASTC_10x6_SRGB_BLOCK || format == VK_FORMAT_ASTC_10x8_UNORM_BLOCK || + format == VK_FORMAT_ASTC_10x8_SRGB_BLOCK || format == VK_FORMAT_ASTC_10x10_UNORM_BLOCK || format == VK_FORMAT_ASTC_10x10_SRGB_BLOCK || + format == VK_FORMAT_ASTC_12x10_UNORM_BLOCK || format == VK_FORMAT_ASTC_12x10_SRGB_BLOCK || format == VK_FORMAT_ASTC_12x12_UNORM_BLOCK || format == VK_FORMAT_ASTC_12x12_SRGB_BLOCK); } @@ -148,10 +130,7 @@ static VkFormat maybe_coerce_to_srgb(VkFormat fmt) } Image::Image(const std::string &name, std::vector &&d, std::vector &&m) : - Component{name}, - data{std::move(d)}, - format{VK_FORMAT_R8G8B8A8_UNORM}, - mipmaps{std::move(m)} + Component{name}, data{std::move(d)}, format{VK_FORMAT_R8G8B8A8_UNORM}, mipmaps{std::move(m)} { update_hash(); } @@ -207,16 +186,8 @@ void Image::create_vk_image(vkb::core::DeviceC &device, VkImageViewType image_vi { assert(!vk_image && !vk_image_view && "Vulkan image already constructed"); - vk_image = std::make_unique(device, - get_extent(), - format, - VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY, - VK_SAMPLE_COUNT_1_BIT, - to_u32(mipmaps.size()), - layers, - VK_IMAGE_TILING_OPTIMAL, - flags); + vk_image = std::make_unique(device, get_extent(), format, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + VMA_MEMORY_USAGE_GPU_ONLY, VK_SAMPLE_COUNT_1_BIT, to_u32(mipmaps.size()), layers, VK_IMAGE_TILING_OPTIMAL, flags); vk_image->set_debug_name(get_name()); vk_image_view = std::make_unique(*vk_image, image_view_type); @@ -292,8 +263,8 @@ void Image::generate_mipmaps() next_mipmap.extent = {next_width, next_height, 1u}; // Fill next mipmap memory - stbir_resize_uint8(data.data() + prev_mipmap.offset, prev_mipmap.extent.width, prev_mipmap.extent.height, 0, - data.data() + next_mipmap.offset, next_mipmap.extent.width, next_mipmap.extent.height, 0, channels); + stbir_resize_uint8(data.data() + prev_mipmap.offset, prev_mipmap.extent.width, prev_mipmap.extent.height, 0, data.data() + next_mipmap.offset, + next_mipmap.extent.width, next_mipmap.extent.height, 0, channels); mipmaps.emplace_back(std::move(next_mipmap)); @@ -374,8 +345,7 @@ void Image::coerce_format_to_srgb() format = maybe_coerce_to_srgb(format); } -std::unique_ptr Image::load(const std::string &name, const std::string &uri, - ContentType content_type) +std::unique_ptr Image::load(const std::string &name, const std::string &uri, ContentType content_type) { std::unique_ptr image{nullptr}; diff --git a/framework/scene_graph/components/image/astc.cpp b/framework/scene_graph/components/image/astc.cpp index 5395f5ccc2..dcef07385c 100644 --- a/framework/scene_graph/components/image/astc.cpp +++ b/framework/scene_graph/components/image/astc.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -147,8 +147,7 @@ struct AstcHeader }; void Astc::init() -{ -} +{} void Astc::decode(BlockDim blockdim, VkExtent3D extent, const uint8_t *compressed_data, uint32_t compressed_size) { @@ -158,14 +157,8 @@ void Astc::decode(BlockDim blockdim, VkExtent3D extent, const uint8_t *compresse astcenc_swizzle swizzle = {ASTCENC_SWZ_R, ASTCENC_SWZ_G, ASTCENC_SWZ_B, ASTCENC_SWZ_A}; // Configure the compressor run astcenc_config astc_config; - auto atscresult = astcenc_config_init( - ASTCENC_PRF_LDR_SRGB, - blockdim.x, - blockdim.y, - blockdim.z, - ASTCENC_PRE_FAST, - ASTCENC_FLG_DECOMPRESS_ONLY, - &astc_config); + auto atscresult = + astcenc_config_init(ASTCENC_PRF_LDR_SRGB, blockdim.x, blockdim.y, blockdim.z, ASTCENC_PRE_FAST, ASTCENC_FLG_DECOMPRESS_ONLY, &astc_config); if (atscresult != ASTCENC_SUCCESS) { @@ -208,8 +201,7 @@ void Astc::decode(BlockDim blockdim, VkExtent3D extent, const uint8_t *compresse set_depth(decoded.dim_z); } -Astc::Astc(const Image &image) : - Image{image.get_name()} +Astc::Astc(const Image &image) : Image{image.get_name()} { init(); @@ -223,7 +215,8 @@ Astc::Astc(const Image &image) : constexpr const char file_cache_header[ASTC_CACHE_HEADER_SIZE] = "ASTCConvertedDataV01"; const auto profile = to_profile(image.get_format()); - auto can_load_from_file = [this, profile, fs, file_cache_header, bytes_per_pixel, use_cache](const Path &path, std::vector &dst_data, uint32_t width, uint32_t height, uint32_t depth) { + auto can_load_from_file = [this, profile, fs, file_cache_header, bytes_per_pixel, use_cache](const Path &path, std::vector &dst_data, + uint32_t width, uint32_t height, uint32_t depth) { if (!use_cache) { LOGD("Device does not support ASTC format and cache is disabled. ASTC image {} will be decoded.", get_name()) @@ -260,9 +253,7 @@ Astc::Astc(const Image &image) : copy_from_file(&file_height, &offset, sizeof(std::uint32_t)); copy_from_file(&file_depth, &offset, sizeof(std::uint32_t)); - if (file_width != width || width == 0 || - file_height != height || height == 0 || - file_depth != depth || depth == 0) + if (file_width != width || width == 0 || file_height != height || height == 0 || file_depth != depth || depth == 0) { return false; } @@ -288,7 +279,8 @@ Astc::Astc(const Image &image) : } }; - auto save_to_file = [fs, file_cache_header, bytes_per_pixel, use_cache](const Path &path, uint8_t *dst_data, uint32_t width, uint32_t height, uint32_t depth) { + auto save_to_file = [fs, file_cache_header, bytes_per_pixel, use_cache](const Path &path, uint8_t *dst_data, uint32_t width, uint32_t height, + uint32_t depth) { if (!use_cache) { return; @@ -321,8 +313,7 @@ Astc::Astc(const Image &image) : }; // Locate mip #0 in the KTX. This is the first one in the data array for KTX1s, but the last one in KTX2s! - auto mip_it = std::ranges::find_if(image.get_mipmaps(), - [](auto &mip) { return mip.level == 0; }); + auto mip_it = std::ranges::find_if(image.get_mipmaps(), [](auto &mip) { return mip.level == 0; }); assert(mip_it != image.get_mipmaps().end() && "Mip #0 not found"); const std::string path = fmt::format("{}/{}.bin", ASTC_CACHE_DIRECTORY, uint64_t(key)); @@ -344,8 +335,7 @@ Astc::Astc(const Image &image) : update_hash(image.get_data_hash()); } -Astc::Astc(const std::string &name, const std::vector &data) : - Image{name} +Astc::Astc(const std::string &name, const std::vector &data) : Image{name} { init(); @@ -356,21 +346,20 @@ Astc::Astc(const std::string &name, const std::vector &data) : } AstcHeader header{}; std::memcpy(&header, data.data(), sizeof(AstcHeader)); - uint32_t magicval = header.magic[0] + 256 * static_cast(header.magic[1]) + 65536 * static_cast(header.magic[2]) + 16777216 * static_cast(header.magic[3]); + uint32_t magicval = header.magic[0] + 256 * static_cast(header.magic[1]) + 65536 * static_cast(header.magic[2]) + + 16777216 * static_cast(header.magic[3]); if (magicval != MAGIC_FILE_CONSTANT) { throw std::runtime_error{"Error reading astc: invalid magic"}; } - BlockDim blockdim = { - /* xdim = */ header.blockdim_x, - /* ydim = */ header.blockdim_y, - /* zdim = */ header.blockdim_z}; + BlockDim blockdim = {/* xdim = */ header.blockdim_x, + /* ydim = */ header.blockdim_y, + /* zdim = */ header.blockdim_z}; - VkExtent3D extent = { - /* width = */ static_cast(header.xsize[0] + 256 * header.xsize[1] + 65536 * header.xsize[2]), - /* height = */ static_cast(header.ysize[0] + 256 * header.ysize[1] + 65536 * header.ysize[2]), - /* depth = */ static_cast(header.zsize[0] + 256 * header.zsize[1] + 65536 * header.zsize[2])}; + VkExtent3D extent = {/* width = */ static_cast(header.xsize[0] + 256 * header.xsize[1] + 65536 * header.xsize[2]), + /* height = */ static_cast(header.ysize[0] + 256 * header.ysize[1] + 65536 * header.ysize[2]), + /* depth = */ static_cast(header.zsize[0] + 256 * header.zsize[1] + 65536 * header.zsize[2])}; decode(blockdim, extent, data.data() + sizeof(AstcHeader), to_u32(data.size() - sizeof(AstcHeader))); diff --git a/framework/scene_graph/components/image/ktx.cpp b/framework/scene_graph/components/image/ktx.cpp index 2420c6c5b2..aca4809a0c 100644 --- a/framework/scene_graph/components/image/ktx.cpp +++ b/framework/scene_graph/components/image/ktx.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors - * Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Arm Limited and Contributors + * Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -36,14 +36,8 @@ struct CallbackData final /// Row padding is different between KTX (pad to 4) and Vulkan (none). /// Also region->bufferOffset, i.e. the start of each image, has /// to be a multiple of 4 and also a multiple of the element size. -static ktx_error_code_e KTX_APIENTRY optimal_tiling_callback(int mip_level, - int face, - int width, - int height, - int depth, - ktx_uint64_t face_lod_size, - void *pixels, - void *user_data) +static ktx_error_code_e KTX_APIENTRY + optimal_tiling_callback(int mip_level, int face, int width, int height, int depth, ktx_uint64_t face_lod_size, void *pixels, void *user_data) { auto *callback_data = reinterpret_cast(user_data); assert(static_cast(mip_level) < callback_data->mipmaps->size() && "Not enough space in the mipmap vector"); @@ -65,17 +59,13 @@ static ktx_error_code_e KTX_APIENTRY optimal_tiling_callback(int mip_le return KTX_SUCCESS; } -Ktx::Ktx(const std::string &name, const std::vector &data, ContentType content_type) : - Image{name} +Ktx::Ktx(const std::string &name, const std::vector &data, ContentType content_type) : Image{name} { auto data_buffer = reinterpret_cast(data.data()); auto data_size = static_cast(data.size()); ktxTexture *texture; - auto load_ktx_result = ktxTexture_CreateFromMemory(data_buffer, - data_size, - KTX_TEXTURE_CREATE_NO_FLAGS, - &texture); + auto load_ktx_result = ktxTexture_CreateFromMemory(data_buffer, data_size, KTX_TEXTURE_CREATE_NO_FLAGS, &texture); if (load_ktx_result != KTX_SUCCESS) { throw std::runtime_error{"Error loading KTX texture: " + name}; diff --git a/framework/scene_graph/components/image/stb.cpp b/framework/scene_graph/components/image/stb.cpp index 7cf5519221..fc726d5397 100644 --- a/framework/scene_graph/components/image/stb.cpp +++ b/framework/scene_graph/components/image/stb.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2022, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -24,8 +24,7 @@ namespace vkb { namespace sg { -Stb::Stb(const std::string &name, const std::vector &data, ContentType content_type) : - Image{name} +Stb::Stb(const std::string &name, const std::vector &data, ContentType content_type) : Image{name} { int width; int height; diff --git a/framework/scene_graph/components/light.cpp b/framework/scene_graph/components/light.cpp index 28fb97c76b..e3ec037425 100644 --- a/framework/scene_graph/components/light.cpp +++ b/framework/scene_graph/components/light.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -22,8 +22,7 @@ namespace vkb { namespace sg { -Light::Light(const std::string &name) : - Component{name} +Light::Light(const std::string &name) : Component{name} {} std::type_index Light::get_type() diff --git a/framework/scene_graph/components/material.cpp b/framework/scene_graph/components/material.cpp index d9e07de2fe..35201282e3 100644 --- a/framework/scene_graph/components/material.cpp +++ b/framework/scene_graph/components/material.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2019, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,8 +21,7 @@ namespace vkb { namespace sg { -Material::Material(const std::string &name) : - Component{name} +Material::Material(const std::string &name) : Component{name} {} std::type_index Material::get_type() diff --git a/framework/scene_graph/components/mesh.cpp b/framework/scene_graph/components/mesh.cpp index 79430d9b91..be35703a68 100644 --- a/framework/scene_graph/components/mesh.cpp +++ b/framework/scene_graph/components/mesh.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,8 +21,7 @@ namespace vkb { namespace sg { -Mesh::Mesh(const std::string &name) : - Component{name} +Mesh::Mesh(const std::string &name) : Component{name} {} void Mesh::update_bounds(const std::vector &vertex_data, const std::vector &index_data) diff --git a/framework/scene_graph/components/orthographic_camera.cpp b/framework/scene_graph/components/orthographic_camera.cpp index 2fead0aa69..148acb500c 100644 --- a/framework/scene_graph/components/orthographic_camera.cpp +++ b/framework/scene_graph/components/orthographic_camera.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Arm Limited and Contributors +/* Copyright (c) 2023-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -23,20 +23,12 @@ namespace vkb { namespace sg { -OrthographicCamera::OrthographicCamera(const std::string &name) : - Camera{name} +OrthographicCamera::OrthographicCamera(const std::string &name) : Camera{name} {} OrthographicCamera::OrthographicCamera(const std::string &name, float left, float right, float bottom, float top, float near_plane, float far_plane) : - Camera{name}, - left{left}, - right{right}, - top{top}, - bottom{bottom}, - near_plane{near_plane}, - far_plane{far_plane} -{ -} + Camera{name}, left{left}, right{right}, top{top}, bottom{bottom}, near_plane{near_plane}, far_plane{far_plane} +{} void OrthographicCamera::set_left(float new_left) { diff --git a/framework/scene_graph/components/pbr_material.cpp b/framework/scene_graph/components/pbr_material.cpp index bf27f0830f..9f7db8bd05 100644 --- a/framework/scene_graph/components/pbr_material.cpp +++ b/framework/scene_graph/components/pbr_material.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2019, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,8 +21,7 @@ namespace vkb { namespace sg { -PBRMaterial::PBRMaterial(const std::string &name) : - Material{name} +PBRMaterial::PBRMaterial(const std::string &name) : Material{name} {} std::type_index PBRMaterial::get_type() diff --git a/framework/scene_graph/components/perspective_camera.cpp b/framework/scene_graph/components/perspective_camera.cpp index a743ce73c9..4a04a6b448 100644 --- a/framework/scene_graph/components/perspective_camera.cpp +++ b/framework/scene_graph/components/perspective_camera.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -23,8 +23,7 @@ namespace vkb { namespace sg { -PerspectiveCamera::PerspectiveCamera(const std::string &name) : - Camera{name} +PerspectiveCamera::PerspectiveCamera(const std::string &name) : Camera{name} {} void PerspectiveCamera::set_field_of_view(float new_fov) diff --git a/framework/scene_graph/components/sampler.h b/framework/scene_graph/components/sampler.h index 411c41848a..6e89927de0 100644 --- a/framework/scene_graph/components/sampler.h +++ b/framework/scene_graph/components/sampler.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -55,17 +55,13 @@ using SamplerCpp = Sampler; template <> inline Sampler::Sampler(std::string const &name, vkb::core::HPPSampler &&core_sampler_) : - Component{name}, - core_sampler{std::move(core_sampler_)} -{ -} + Component{name}, core_sampler{std::move(core_sampler_)} +{} template <> inline Sampler::Sampler(std::string const &name, vkb::core::Sampler &&core_sampler_) : - Component{name}, - core_sampler{std::move(reinterpret_cast(core_sampler_))} -{ -} + Component{name}, core_sampler{std::move(reinterpret_cast(core_sampler_))} +{} template inline typename Sampler::CoreSamplerType const &Sampler::get_core_sampler() const diff --git a/framework/scene_graph/components/sub_mesh.cpp b/framework/scene_graph/components/sub_mesh.cpp index 04b84c0535..dc864ecf9c 100644 --- a/framework/scene_graph/components/sub_mesh.cpp +++ b/framework/scene_graph/components/sub_mesh.cpp @@ -24,8 +24,7 @@ namespace vkb { namespace sg { -SubMesh::SubMesh(const std::string &name) : - Component{name} +SubMesh::SubMesh(const std::string &name) : Component{name} {} vkb::core::BufferC const &SubMesh::get_index_buffer() const diff --git a/framework/scene_graph/components/texture.cpp b/framework/scene_graph/components/texture.cpp index ec64ff351e..ff5491f8f4 100644 --- a/framework/scene_graph/components/texture.cpp +++ b/framework/scene_graph/components/texture.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -24,8 +24,7 @@ namespace vkb { namespace sg { -Texture::Texture(const std::string &name) : - Component{name} +Texture::Texture(const std::string &name) : Component{name} {} std::type_index Texture::get_type() diff --git a/framework/scene_graph/components/transform.cpp b/framework/scene_graph/components/transform.cpp index beb0eff2e9..3e5b154f5e 100644 --- a/framework/scene_graph/components/transform.cpp +++ b/framework/scene_graph/components/transform.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -26,10 +26,8 @@ namespace vkb { namespace sg { -Transform::Transform(vkb::scene_graph::NodeC &n) : - node{n} -{ -} +Transform::Transform(vkb::scene_graph::NodeC &n) : node{n} +{} vkb::scene_graph::NodeC &Transform::get_node() { @@ -88,9 +86,7 @@ void Transform::set_matrix(const glm::mat4 &matrix) glm::mat4 Transform::get_matrix() const { - return glm::translate(glm::mat4(1.0), translation) * - glm::mat4_cast(rotation) * - glm::scale(glm::mat4(1.0), scale); + return glm::translate(glm::mat4(1.0), translation) * glm::mat4_cast(rotation) * glm::scale(glm::mat4(1.0), scale); } glm::mat4 Transform::get_world_matrix() diff --git a/framework/scene_graph/hpp_scene.h b/framework/scene_graph/hpp_scene.h index 4bcbae4288..4380a0debc 100644 --- a/framework/scene_graph/hpp_scene.h +++ b/framework/scene_graph/hpp_scene.h @@ -38,12 +38,8 @@ class HPPScene : private vkb::sg::Scene template std::vector get_components() const { - if constexpr (std::is_same::value || - std::is_same::value || - std::is_same::value || - std::is_same::value || - std::is_same::value || - std::is_same::value) + if constexpr (std::is_same::value || std::is_same::value || std::is_same::value || + std::is_same::value || std::is_same::value || std::is_same::value) { return vkb::sg::Scene::get_components(); } @@ -62,12 +58,8 @@ class HPPScene : private vkb::sg::Scene template bool has_component() const { - if constexpr (std::is_same::value || - std::is_same::value || - std::is_same::value || - std::is_same::value || - std::is_same::value || - std::is_same::value) + if constexpr (std::is_same::value || std::is_same::value || std::is_same::value || + std::is_same::value || std::is_same::value || std::is_same::value) { return vkb::sg::Scene::has_component(typeid(T)); } diff --git a/framework/scene_graph/node.h b/framework/scene_graph/node.h index c25ef98eed..bdb716d836 100644 --- a/framework/scene_graph/node.h +++ b/framework/scene_graph/node.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -64,8 +64,7 @@ using NodeCpp = Node; // Member function definitions template -inline Node::Node(size_t id_, std::string const &name_) : - id{id_}, name{name_}, transform{*this} +inline Node::Node(size_t id_, std::string const &name_) : id{id_}, name{name_}, transform{*this} { set_component(transform); } diff --git a/framework/scene_graph/scene.cpp b/framework/scene_graph/scene.cpp index 4705ef78c3..8f4862b78e 100644 --- a/framework/scene_graph/scene.cpp +++ b/framework/scene_graph/scene.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -27,8 +27,7 @@ namespace vkb { namespace sg { -Scene::Scene(const std::string &name) : - name{name} +Scene::Scene(const std::string &name) : name{name} {} void Scene::set_name(const std::string &new_name) diff --git a/framework/scene_graph/scene.h b/framework/scene_graph/scene.h index 0a1e4caad5..5d8c6ec01f 100644 --- a/framework/scene_graph/scene.h +++ b/framework/scene_graph/scene.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors +/* Copyright (c) 2018-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -75,9 +75,7 @@ class Scene { std::vector> result(components.size()); std::transform(components.begin(), components.end(), result.begin(), - [](std::unique_ptr &component) -> std::unique_ptr { - return std::unique_ptr(std::move(component)); - }); + [](std::unique_ptr &component) -> std::unique_ptr { return std::unique_ptr(std::move(component)); }); set_components(typeid(T), std::move(result)); } @@ -103,9 +101,7 @@ class Scene result.resize(scene_components.size()); std::transform(scene_components.begin(), scene_components.end(), result.begin(), - [](const std::unique_ptr &component) -> T * { - return dynamic_cast(component.get()); - }); + [](const std::unique_ptr &component) -> T * { return dynamic_cast(component.get()); }); } return result; diff --git a/framework/scene_graph/script.cpp b/framework/scene_graph/script.cpp index 3ffbb50f9a..dc11ce9ffe 100644 --- a/framework/scene_graph/script.cpp +++ b/framework/scene_graph/script.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,8 +21,7 @@ namespace vkb { namespace sg { -Script::Script(const std::string &name) : - Component{name} +Script::Script(const std::string &name) : Component{name} {} std::type_index Script::get_type() @@ -31,18 +30,13 @@ std::type_index Script::get_type() } void Script::input_event(const InputEvent & /*input_event*/) -{ -} +{} void Script::resize(uint32_t /*width*/, uint32_t /*height*/) -{ -} +{} -NodeScript::NodeScript(vkb::scene_graph::NodeC &node, const std::string &name) : - Script{name}, - node{node} -{ -} +NodeScript::NodeScript(vkb::scene_graph::NodeC &node, const std::string &name) : Script{name}, node{node} +{} vkb::scene_graph::NodeC &NodeScript::get_node() { diff --git a/framework/scene_graph/scripts/animation.cpp b/framework/scene_graph/scripts/animation.cpp index 7b1e8b0a1b..fbd95970f9 100644 --- a/framework/scene_graph/scripts/animation.cpp +++ b/framework/scene_graph/scripts/animation.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Arm Limited and Contributors +/* Copyright (c) 2020-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -23,15 +23,11 @@ namespace vkb { namespace sg { -Animation::Animation(const std::string &name) : - Script{name} -{ -} +Animation::Animation(const std::string &name) : Script{name} +{} -Animation::Animation(const Animation &other) : - channels{other.channels} -{ -} +Animation::Animation(const Animation &other) : channels{other.channels} +{} void Animation::add_channel(vkb::scene_graph::NodeC &node, const AnimationTarget &target, const AnimationSampler &sampler) { @@ -62,9 +58,7 @@ void Animation::update(float delta_time) { case Translation: { - transform.set_translation(glm::vec3(glm::mix(channel.sampler.outputs[i], - channel.sampler.outputs[i + 1], - time))); + transform.set_translation(glm::vec3(glm::mix(channel.sampler.outputs[i], channel.sampler.outputs[i + 1], time))); break; } case Rotation: @@ -87,9 +81,7 @@ void Animation::update(float delta_time) case Scale: { - transform.set_scale(glm::vec3(glm::mix(channel.sampler.outputs[i], - channel.sampler.outputs[i + 1], - time))); + transform.set_scale(glm::vec3(glm::mix(channel.sampler.outputs[i], channel.sampler.outputs[i + 1], time))); } } } @@ -130,8 +122,11 @@ void Animation::update(float delta_time) glm::vec4 m0 = delta * channel.sampler.outputs[i * 3 + 2]; // Delta time * out tangent glm::vec4 m1 = delta * channel.sampler.outputs[(i + 1) * 3 + 0]; // Delta time * in tangent of next point - // This equation is taken from the GLTF 2.0 specification Appendix C (https://github.com/KhronosGroup/glTF/tree/main/specification/2.0#appendix-c-spline-interpolation) - glm::vec4 result = (2.0f * glm::pow(time, 3.0f) - 3.0f * glm::pow(time, 2.0f) + 1.0f) * p0 + (glm::pow(time, 3.0f) - 2.0f * glm::pow(time, 2.0f) + time) * m0 + (-2.0f * glm::pow(time, 3.0f) + 3.0f * glm::pow(time, 2.0f)) * p1 + (glm::pow(time, 3.0f) - glm::pow(time, 2.0f)) * m1; + // This equation is taken from the GLTF 2.0 specification Appendix C + // (https://github.com/KhronosGroup/glTF/tree/main/specification/2.0#appendix-c-spline-interpolation) + glm::vec4 result = (2.0f * glm::pow(time, 3.0f) - 3.0f * glm::pow(time, 2.0f) + 1.0f) * p0 + + (glm::pow(time, 3.0f) - 2.0f * glm::pow(time, 2.0f) + time) * m0 + + (-2.0f * glm::pow(time, 3.0f) + 3.0f * glm::pow(time, 2.0f)) * p1 + (glm::pow(time, 3.0f) - glm::pow(time, 2.0f)) * m1; auto &transform = channel.node.get_transform(); diff --git a/framework/scene_graph/scripts/free_camera.cpp b/framework/scene_graph/scripts/free_camera.cpp index e2ff16a424..297e58a9e9 100644 --- a/framework/scene_graph/scripts/free_camera.cpp +++ b/framework/scene_graph/scripts/free_camera.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors - * Copyright (c) 2020-2025, Andrew Cox, Huawei Technologies Research & Development (UK) Limited +/* Copyright (c) 2019-2026, Arm Limited and Contributors + * Copyright (c) 2020-2026, Andrew Cox, Huawei Technologies Research & Development (UK) Limited * * SPDX-License-Identifier: Apache-2.0 * @@ -44,8 +44,7 @@ const float FreeCamera::TRANSLATION_MOVE_STEP = 50.0f; const uint32_t FreeCamera::TRANSLATION_MOVE_SPEED = 4; -FreeCamera::FreeCamera(vkb::scene_graph::NodeC &node) : - NodeScript{node, "FreeCamera"} +FreeCamera::FreeCamera(vkb::scene_graph::NodeC &node) : NodeScript{node, "FreeCamera"} {} void FreeCamera::update(float delta_time) @@ -162,8 +161,7 @@ void FreeCamera::input_event(const InputEvent &input_event) { const auto &key_event = static_cast(input_event); - if (key_event.get_action() == KeyAction::Down || - key_event.get_action() == KeyAction::Repeat) + if (key_event.get_action() == KeyAction::Down || key_event.get_action() == KeyAction::Repeat) { key_pressed[key_event.get_code()] = true; } diff --git a/framework/scene_graph/scripts/node_animation.cpp b/framework/scene_graph/scripts/node_animation.cpp index ee1944de71..0d17a4de1a 100644 --- a/framework/scene_graph/scripts/node_animation.cpp +++ b/framework/scene_graph/scripts/node_animation.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -31,11 +31,8 @@ namespace vkb { namespace sg { -NodeAnimation::NodeAnimation(vkb::scene_graph::NodeC &node, TransformAnimFn animation_fn) : - NodeScript{node, ""}, - animation_fn{animation_fn} -{ -} +NodeAnimation::NodeAnimation(vkb::scene_graph::NodeC &node, TransformAnimFn animation_fn) : NodeScript{node, ""}, animation_fn{animation_fn} +{} void NodeAnimation::update(float delta_time) { diff --git a/framework/semaphore_pool.cpp b/framework/semaphore_pool.cpp index 1157fdd037..2bfdcdfec1 100644 --- a/framework/semaphore_pool.cpp +++ b/framework/semaphore_pool.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -21,10 +21,8 @@ namespace vkb { -SemaphorePool::SemaphorePool(vkb::core::DeviceC &device) : - device{device} -{ -} +SemaphorePool::SemaphorePool(vkb::core::DeviceC &device) : device{device} +{} SemaphorePool::~SemaphorePool() { diff --git a/framework/spirv_reflection.cpp b/framework/spirv_reflection.cpp index 83912fb17a..38097587b7 100644 --- a/framework/spirv_reflection.cpp +++ b/framework/spirv_reflection.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2020, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -25,7 +25,7 @@ template inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { LOGE("Not implemented! Read shader resources of type."); } @@ -42,8 +42,8 @@ inline void read_resource_decoration(const spirv_cross::Compiler & /*compiler*/, template <> inline void read_resource_decoration(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { shader_resource.location = compiler.get_decoration(resource.id, spv::DecorationLocation); } @@ -51,8 +51,8 @@ inline void read_resource_decoration(const spirv_cross: template <> inline void read_resource_decoration(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { shader_resource.set = compiler.get_decoration(resource.id, spv::DecorationDescriptorSet); } @@ -60,8 +60,8 @@ inline void read_resource_decoration(const spirv_c template <> inline void read_resource_decoration(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { shader_resource.binding = compiler.get_decoration(resource.id, spv::DecorationBinding); } @@ -69,8 +69,8 @@ inline void read_resource_decoration(const spirv_cross:: template <> inline void read_resource_decoration(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { shader_resource.input_attachment_index = compiler.get_decoration(resource.id, spv::DecorationInputAttachmentIndex); } @@ -78,8 +78,8 @@ inline void read_resource_decoration(const template <> inline void read_resource_decoration(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { shader_resource.qualifiers |= ShaderResourceQualifiers::NonWritable; } @@ -87,16 +87,16 @@ inline void read_resource_decoration(const spirv_cro template <> inline void read_resource_decoration(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { shader_resource.qualifiers |= ShaderResourceQualifiers::NonReadable; } inline void read_resource_vec_size(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { const auto &spirv_type = compiler.get_type_from_variable(resource.id); @@ -106,8 +106,8 @@ inline void read_resource_vec_size(const spirv_cross::Compiler &compiler, inline void read_resource_array_size(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { const auto &spirv_type = compiler.get_type_from_variable(resource.id); @@ -116,8 +116,8 @@ inline void read_resource_array_size(const spirv_cross::Compiler &compiler, inline void read_resource_size(const spirv_cross::Compiler &compiler, const spirv_cross::Resource &resource, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { const auto &spirv_type = compiler.get_type_from_variable(resource.id); @@ -130,10 +130,10 @@ inline void read_resource_size(const spirv_cross::Compiler &compiler, shader_resource.size = to_u32(compiler.get_declared_struct_size_runtime_array(spirv_type, array_size)); } -inline void read_resource_size(const spirv_cross::Compiler & compiler, +inline void read_resource_size(const spirv_cross::Compiler &compiler, const spirv_cross::SPIRConstant &constant, - ShaderResource & shader_resource, - const ShaderVariant & variant) + ShaderResource &shader_resource, + const ShaderVariant &variant) { auto spirv_type = compiler.get_type(constant.constant_type); @@ -161,7 +161,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto input_resources = compiler.get_shader_resources().stage_inputs; @@ -184,7 +184,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits /*stage*/, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto subpass_resources = compiler.get_shader_resources().subpass_inputs; @@ -208,7 +208,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto output_resources = compiler.get_shader_resources().stage_outputs; @@ -231,7 +231,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto image_resources = compiler.get_shader_resources().separate_images; @@ -254,7 +254,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto image_resources = compiler.get_shader_resources().sampled_images; @@ -277,7 +277,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto storage_resources = compiler.get_shader_resources().storage_images; @@ -302,7 +302,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto sampler_resources = compiler.get_shader_resources().separate_samplers; @@ -325,7 +325,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto uniform_resources = compiler.get_shader_resources().uniform_buffers; @@ -349,7 +349,7 @@ template <> inline void read_shader_resource(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, - const ShaderVariant & variant) + const ShaderVariant &variant) { auto storage_resources = compiler.get_shader_resources().storage_buffers; @@ -372,7 +372,10 @@ inline void read_shader_resource(const spirv_ } } // namespace -bool SPIRVReflection::reflect_shader_resources(VkShaderStageFlagBits stage, const std::vector &spirv, std::vector &resources, const ShaderVariant &variant) +bool SPIRVReflection::reflect_shader_resources(VkShaderStageFlagBits stage, + const std::vector &spirv, + std::vector &resources, + const ShaderVariant &variant) { spirv_cross::CompilerGLSL compiler{spirv}; @@ -388,7 +391,10 @@ bool SPIRVReflection::reflect_shader_resources(VkShaderStageFlagBits stage, cons return true; } -void SPIRVReflection::parse_shader_resources(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, const ShaderVariant &variant) +void SPIRVReflection::parse_shader_resources(const spirv_cross::Compiler &compiler, + VkShaderStageFlagBits stage, + std::vector &resources, + const ShaderVariant &variant) { read_shader_resource(compiler, stage, resources, variant); read_shader_resource(compiler, stage, resources, variant); @@ -401,7 +407,10 @@ void SPIRVReflection::parse_shader_resources(const spirv_cross::Compiler &compil read_shader_resource(compiler, stage, resources, variant); } -void SPIRVReflection::parse_push_constants(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, const ShaderVariant &variant) +void SPIRVReflection::parse_push_constants(const spirv_cross::Compiler &compiler, + VkShaderStageFlagBits stage, + std::vector &resources, + const ShaderVariant &variant) { auto shader_resources = compiler.get_shader_resources(); @@ -432,7 +441,10 @@ void SPIRVReflection::parse_push_constants(const spirv_cross::Compiler &compiler } } -void SPIRVReflection::parse_specialization_constants(const spirv_cross::Compiler &compiler, VkShaderStageFlagBits stage, std::vector &resources, const ShaderVariant &variant) +void SPIRVReflection::parse_specialization_constants(const spirv_cross::Compiler &compiler, + VkShaderStageFlagBits stage, + std::vector &resources, + const ShaderVariant &variant) { auto specialization_constants = compiler.get_specialization_constants(); diff --git a/framework/stats/stats.cpp b/framework/stats/stats.cpp index 088e9f5973..ad5e24d709 100644 --- a/framework/stats/stats.cpp +++ b/framework/stats/stats.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors - * Copyright (c) 2020-2025, Broadcom Inc. +/* Copyright (c) 2018-2026, Arm Limited and Contributors + * Copyright (c) 2020-2026, Broadcom Inc. * * SPDX-License-Identifier: Apache-2.0 * @@ -33,9 +33,7 @@ namespace vkb { -Stats::Stats(vkb::rendering::RenderContextC &render_context, size_t buffer_size) : - render_context(render_context), - buffer_size(buffer_size) +Stats::Stats(vkb::rendering::RenderContextC &render_context, size_t buffer_size) : render_context(render_context), buffer_size(buffer_size) { assert(buffer_size >= 2 && "Buffers size should be greater than 2"); } @@ -53,8 +51,7 @@ Stats::~Stats() } } -void Stats::request_stats(const std::set &wanted_stats, - CounterSamplingConfig config) +void Stats::request_stats(const std::set &wanted_stats, CounterSamplingConfig config) { if (providers.size() != 0) { @@ -90,9 +87,7 @@ void Stats::request_stats(const std::set &wanted_stats, // Start a thread for continuous sample capture stop_worker = std::make_unique>(); - worker_thread = std::thread([this] { - continuous_sampling_worker(stop_worker->get_future()); - }); + worker_thread = std::thread([this] { continuous_sampling_worker(stop_worker->get_future()); }); // Reduce smoothing for continuous sampling alpha_smoothing = 0.6f; @@ -460,17 +455,8 @@ const StatGraphData &Stats::get_graph_data(StatIndex index) const return StatsProvider::default_graph_data(index); } -StatGraphData::StatGraphData(const std::string &name, - const std::string &graph_label_format, - float scale_factor, - bool has_fixed_max, - float max_value) : - name(name), - format{graph_label_format}, - scale_factor{scale_factor}, - has_fixed_max{has_fixed_max}, - max_value{max_value} -{ -} +StatGraphData::StatGraphData(const std::string &name, const std::string &graph_label_format, float scale_factor, bool has_fixed_max, float max_value) : + name(name), format{graph_label_format}, scale_factor{scale_factor}, has_fixed_max{has_fixed_max}, max_value{max_value} +{} } // namespace vkb diff --git a/framework/stats/stats.h b/framework/stats/stats.h index 5ecb75ae8f..11e2a85570 100644 --- a/framework/stats/stats.h +++ b/framework/stats/stats.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2018-2025, Arm Limited and Contributors - * Copyright (c) 2020-2025, Broadcom Inc. +/* Copyright (c) 2018-2026, Arm Limited and Contributors + * Copyright (c) 2020-2026, Broadcom Inc. * * SPDX-License-Identifier: Apache-2.0 * @@ -69,8 +69,7 @@ class Stats * @param requested_stats Set of stats to be collected if available * @param sampling_config Sampling mode configuration (polling or continuous) */ - void request_stats(const std::set &requested_stats, - CounterSamplingConfig sampling_config = {CounterSamplingMode::Polling}); + void request_stats(const std::set &requested_stats, CounterSamplingConfig sampling_config = {CounterSamplingMode::Polling}); /** * @brief Resizes the stats buffers according to the width of the screen diff --git a/framework/stats/stats_common.h b/framework/stats/stats_common.h index 60751f7699..ac489e3263 100644 --- a/framework/stats/stats_common.h +++ b/framework/stats/stats_common.h @@ -1,5 +1,5 @@ -/* Copyright (c) 2018-2022, Arm Limited and Contributors - * Copyright (c) 2020-2022, Broadcom Inc. +/* Copyright (c) 2018-2026, Arm Limited and Contributors + * Copyright (c) 2020-2026, Broadcom Inc. * * SPDX-License-Identifier: Apache-2.0 * @@ -119,11 +119,7 @@ class StatGraphData * @param has_fixed_max Whether the data should have a fixed max value * @param max_value The maximum value to use */ - StatGraphData(const std::string &name, - const std::string &format, - float scale_factor = 1.0f, - bool has_fixed_max = false, - float max_value = 0.0f); + StatGraphData(const std::string &name, const std::string &format, float scale_factor = 1.0f, bool has_fixed_max = false, float max_value = 0.0f); StatGraphData() = default; diff --git a/framework/stats/vulkan_stats_provider.cpp b/framework/stats/vulkan_stats_provider.cpp index 2094bb9b7f..573d950773 100644 --- a/framework/stats/vulkan_stats_provider.cpp +++ b/framework/stats/vulkan_stats_provider.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Broadcom Inc. and Contributors +/* Copyright (c) 2020-2026, Broadcom Inc. and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -111,8 +111,7 @@ VulkanStatsProvider::VulkanStatsProvider(std::set &request else { counter_indices.emplace_back(div_idx); - stat_data[index] = StatData(ctr_idx, counters[ctr_idx].storage, init.scaling, - div_idx, counters[div_idx].storage); + stat_data[index] = StatData(ctr_idx, counters[ctr_idx].storage, init.scaling, div_idx, counters[div_idx].storage); } } } @@ -328,8 +327,7 @@ void VulkanStatsProvider::begin_sampling(vkb::core::CommandBufferC &cb) // delta time is a frame-to-frame s/w measure. A timestamp query in the the cmd // buffer gives the actual elapsed time where the counters were measured. cb.reset_query_pool(*timestamp_pool, active_frame_idx * 2, 1); - cb.write_timestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, *timestamp_pool, - active_frame_idx * 2); + cb.write_timestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, *timestamp_pool, active_frame_idx * 2); } if (query_pool) @@ -347,10 +345,8 @@ void VulkanStatsProvider::end_sampling(vkb::core::CommandBufferC &cb) // Perform a barrier to ensure all previous commands complete before ending the query // This does not block later commands from executing as we use BOTTOM_OF_PIPE in the // dst stage mask - vkCmdPipelineBarrier(cb.get_handle(), - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, nullptr, 0, nullptr, 0, nullptr); + vkCmdPipelineBarrier(cb.get_handle(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 0, + nullptr); cb.end_query(*query_pool, active_frame_idx); ++queries_ready; @@ -359,13 +355,11 @@ void VulkanStatsProvider::end_sampling(vkb::core::CommandBufferC &cb) if (timestamp_pool) { cb.reset_query_pool(*timestamp_pool, active_frame_idx * 2 + 1, 1); - cb.write_timestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, *timestamp_pool, - active_frame_idx * 2 + 1); + cb.write_timestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, *timestamp_pool, active_frame_idx * 2 + 1); } } -static double get_counter_value(const VkPerformanceCounterResultKHR &result, - VkPerformanceCounterStorageKHR storage) +static double get_counter_value(const VkPerformanceCounterResultKHR &result, VkPerformanceCounterStorageKHR storage) { switch (storage) { @@ -401,9 +395,7 @@ float VulkanStatsProvider::get_best_delta_time(float sw_delta_time) const uint32_t active_frame_idx = render_context.get_active_frame_index(); - VkResult r = timestamp_pool->get_results(active_frame_idx * 2, 2, - timestamps.size() * sizeof(uint64_t), - timestamps.data(), sizeof(uint64_t), + VkResult r = timestamp_pool->get_results(active_frame_idx * 2, 2, timestamps.size() * sizeof(uint64_t), timestamps.data(), sizeof(uint64_t), VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT); if (r == VK_SUCCESS) { @@ -428,9 +420,8 @@ StatsProvider::Counters VulkanStatsProvider::sample(float delta_time) std::vector results(counter_indices.size()); - VkResult r = query_pool->get_results(active_frame_idx, 1, - results.size() * sizeof(VkPerformanceCounterResultKHR), - results.data(), stride, VK_QUERY_RESULT_WAIT_BIT); + VkResult r = + query_pool->get_results(active_frame_idx, 1, results.size() * sizeof(VkPerformanceCounterResultKHR), results.data(), stride, VK_QUERY_RESULT_WAIT_BIT); if (r != VK_SUCCESS) { return out; diff --git a/framework/stats/vulkan_stats_provider.h b/framework/stats/vulkan_stats_provider.h index f18888b167..f009eacf95 100644 --- a/framework/stats/vulkan_stats_provider.h +++ b/framework/stats/vulkan_stats_provider.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2020-2025, Broadcom Inc. and Contributors +/* Copyright (c) 2020-2026, Broadcom Inc. and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -43,23 +43,18 @@ class VulkanStatsProvider : public StatsProvider StatData() = default; - StatData(uint32_t counter_index, VkPerformanceCounterStorageKHR storage, + StatData(uint32_t counter_index, + VkPerformanceCounterStorageKHR storage, StatScaling stat_scaling = StatScaling::ByDeltaTime, uint32_t divisor_index = std::numeric_limits::max(), VkPerformanceCounterStorageKHR divisor_storage = VK_PERFORMANCE_COUNTER_STORAGE_FLOAT64_KHR) : - scaling(stat_scaling), - counter_index(counter_index), - divisor_counter_index(divisor_index), - storage(storage), - divisor_storage(divisor_storage) + scaling(stat_scaling), counter_index(counter_index), divisor_counter_index(divisor_index), storage(storage), divisor_storage(divisor_storage) {} }; struct VendorStat { - VendorStat(const std::string &name, const std::string &divisor_name = "") : - name(name), - divisor_name(divisor_name) + VendorStat(const std::string &name, const std::string &divisor_name = "") : name(name), divisor_name(divisor_name) { if (divisor_name != "") scaling = StatScaling::ByCounter; diff --git a/framework/timer.cpp b/framework/timer.cpp index d2583c06db..228c794244 100644 --- a/framework/timer.cpp +++ b/framework/timer.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -19,11 +19,8 @@ namespace vkb { -Timer::Timer() : - start_time{Clock::now()}, - previous_tick{Clock::now()} -{ -} +Timer::Timer() : start_time{Clock::now()}, previous_tick{Clock::now()} +{} void Timer::start() { diff --git a/framework/vulkan_sample.h b/framework/vulkan_sample.h index d5b90c52b0..30a2c6b9a9 100644 --- a/framework/vulkan_sample.h +++ b/framework/vulkan_sample.h @@ -136,15 +136,18 @@ class VulkanSample : public vkb::Application using SceneType = typename std::conditional::type; using StatsType = typename std::conditional::type; - using Extent2DType = typename std::conditional::type; - using DebugReportCallbackCreateInfoType = typename std::conditional::type; - using DebugUtilsMessengerCreateInfoType = typename std::conditional::type; - using InstanceCreateFlagsType = typename std::conditional::type; - using LayerSettingType = typename std::conditional::type; - using PhysicalDeviceType = typename std::conditional::type; - using SurfaceFormatType = typename std::conditional::type; - using SurfaceType = typename std::conditional::type; - using ValidationFeatureEnableType = typename std::conditional::type; + using Extent2DType = typename std::conditional::type; + using DebugReportCallbackCreateInfoType = + typename std::conditional::type; + using DebugUtilsMessengerCreateInfoType = + typename std::conditional::type; + using InstanceCreateFlagsType = typename std::conditional::type; + using LayerSettingType = typename std::conditional::type; + using PhysicalDeviceType = typename std::conditional::type; + using SurfaceFormatType = typename std::conditional::type; + using SurfaceType = typename std::conditional::type; + using ValidationFeatureEnableType = + typename std::conditional::type; Configuration &get_configuration(); vkb::rendering::RenderContext &get_render_context(); @@ -202,7 +205,8 @@ class VulkanSample : public vkb::Application virtual DebugReportCallbackCreateInfoType const *get_debug_report_callback_create_info() const; virtual DebugUtilsMessengerCreateInfoType const *get_debug_utils_messenger_create_info() const; virtual InstanceCreateFlagsType get_instance_create_flags(std::vector const &enabled_extensions) const; - virtual void const *get_instance_create_info_extensions(std::vector const &enabled_layers, std::vector const &enabled_extensions) const; + virtual void const *get_instance_create_info_extensions(std::vector const &enabled_layers, + std::vector const &enabled_extensions) const; /** * @brief Override this to customise the creation of the swapchain and render_context @@ -398,9 +402,8 @@ class VulkanSample : public vkb::Application /** * @brief A list of surface formats in order of priority (vector[0] has high priority, vector[size-1] has low priority) */ - std::vector surface_priority_list = { - {vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}, - {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}}; + std::vector surface_priority_list = {{vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}, + {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear}}; /** * @brief The configuration of the sample @@ -464,21 +467,18 @@ inline void VulkanSample::add_device_extension(const char *extensio } template -inline std::unique_ptr> - VulkanSample::create_device(vkb::core::PhysicalDevice &gpu) +inline std::unique_ptr> VulkanSample::create_device(vkb::core::PhysicalDevice &gpu) { if constexpr (bindingType == BindingType::Cpp) { - return std::make_unique( - gpu, surface, std::move(debug_utils), get_device_extensions(), [this](vkb::core::PhysicalDeviceCpp &gpu) { request_gpu_features(gpu); }); + return std::make_unique(gpu, surface, std::move(debug_utils), get_device_extensions(), + [this](vkb::core::PhysicalDeviceCpp &gpu) { request_gpu_features(gpu); }); } else { - return std::make_unique(gpu, - static_cast(surface), + return std::make_unique(gpu, static_cast(surface), std::unique_ptr(reinterpret_cast(debug_utils.release())), - get_device_extensions(), - [this](vkb::core::PhysicalDeviceC &gpu) { request_gpu_features(gpu); }); + get_device_extensions(), [this](vkb::core::PhysicalDeviceC &gpu) { request_gpu_features(gpu); }); } } @@ -490,11 +490,10 @@ inline std::unique_ptr> VulkanSample>( - get_name(), - get_api_version(), - requested_layers, - requested_extensions, - [this](std::vector const &enabled_layers, std::vector const &enabled_extensions) { return get_instance_create_info_extensions(enabled_layers, enabled_extensions); }, + get_name(), get_api_version(), requested_layers, requested_extensions, + [this](std::vector const &enabled_layers, std::vector const &enabled_extensions) { + return get_instance_create_info_extensions(enabled_layers, enabled_extensions); + }, [this](std::vector const &enabled_extensions) { if constexpr (bindingType == BindingType::Cpp) { @@ -530,11 +529,11 @@ template void VulkanSample::create_render_context_impl(const std::vector &surface_priority_list) { #ifdef VK_USE_PLATFORM_ANDROID_KHR - vk::PresentModeKHR present_mode = (window->get_properties().vsync == Window::Vsync::OFF) ? vk::PresentModeKHR::eMailbox : vk::PresentModeKHR::eFifo; + vk::PresentModeKHR present_mode = (window->get_properties().vsync == Window::Vsync::OFF) ? vk::PresentModeKHR::eMailbox : vk::PresentModeKHR::eFifo; std::vector present_mode_priority_list{vk::PresentModeKHR::eFifo, vk::PresentModeKHR::eMailbox, vk::PresentModeKHR::eImmediate}; #else - vk::PresentModeKHR present_mode = (window->get_properties().vsync == Window::Vsync::ON) ? vk::PresentModeKHR::eFifo : vk::PresentModeKHR::eMailbox; - std::vector present_mode_priority_list{vk::PresentModeKHR::eMailbox, vk::PresentModeKHR::eImmediate, vk::PresentModeKHR::eFifo}; + vk::PresentModeKHR present_mode = (window->get_properties().vsync == Window::Vsync::ON) ? vk::PresentModeKHR::eFifo : vk::PresentModeKHR::eMailbox; + std::vector present_mode_priority_list{vk::PresentModeKHR::eMailbox, vk::PresentModeKHR::eImmediate, vk::PresentModeKHR::eFifo}; #endif render_context = @@ -580,14 +579,12 @@ inline void VulkanSample::draw(vkb::core::CommandBuffer(command_buffer), - reinterpret_cast(render_target)); + draw_impl(reinterpret_cast(command_buffer), reinterpret_cast(render_target)); } } template -inline void VulkanSample::draw_impl(vkb::core::CommandBufferCpp &command_buffer, - vkb::rendering::RenderTargetCpp &render_target) +inline void VulkanSample::draw_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::rendering::RenderTargetCpp &render_target) { auto &views = render_target.get_views(); @@ -650,11 +647,11 @@ inline void VulkanSample::draw_impl(vkb::core::CommandBufferCpp template inline void VulkanSample::draw_gui() -{ -} +{} template -inline void VulkanSample::draw_renderpass(vkb::core::CommandBuffer &command_buffer, vkb::rendering::RenderTarget &render_target) +inline void VulkanSample::draw_renderpass(vkb::core::CommandBuffer &command_buffer, + vkb::rendering::RenderTarget &render_target) { if constexpr (bindingType == BindingType::Cpp) { @@ -668,8 +665,7 @@ inline void VulkanSample::draw_renderpass(vkb::core::CommandBuffer< } template -inline void VulkanSample::draw_renderpass_impl(vkb::core::CommandBufferCpp &command_buffer, - vkb::rendering::RenderTargetCpp &render_target) +inline void VulkanSample::draw_renderpass_impl(vkb::core::CommandBufferCpp &command_buffer, vkb::rendering::RenderTargetCpp &render_target) { set_viewport_and_scissor_impl(command_buffer, render_target.get_extent()); @@ -723,8 +719,9 @@ inline bool enable_layer_setting(vk::LayerSettingEXT const &requested_lay { // Check for VK_EXT_layer_settings extension in the driver which indicates MoltenVK vs. KosmicKrisp (note: VK_MVK_moltenvk extension is deprecated). std::vector available_instance_extensions = vk::enumerateInstanceExtensionProperties(); - if (std::ranges::any_of(available_instance_extensions, - [](vk::ExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_EXT_LAYER_SETTINGS_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(available_instance_extensions, [](vk::ExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_EXT_LAYER_SETTINGS_EXTENSION_NAME) == 0; + })) { is_available = true; } @@ -737,11 +734,10 @@ inline bool enable_layer_setting(vk::LayerSettingEXT const &requested_lay return false; } - bool is_already_enabled = std::ranges::any_of(enabled_layer_settings, - [&requested_layer_setting](vk::LayerSettingEXT const &enabled_layer_setting) { - return (strcmp(requested_layer_setting.pLayerName, enabled_layer_setting.pLayerName) == 0) && - (strcmp(requested_layer_setting.pSettingName, enabled_layer_setting.pSettingName) == 0); - }); + bool is_already_enabled = std::ranges::any_of(enabled_layer_settings, [&requested_layer_setting](vk::LayerSettingEXT const &enabled_layer_setting) { + return (strcmp(requested_layer_setting.pLayerName, enabled_layer_setting.pLayerName) == 0) && + (strcmp(requested_layer_setting.pSettingName, enabled_layer_setting.pSettingName) == 0); + }); if (is_already_enabled) { @@ -765,8 +761,9 @@ template inline typename VulkanSample::DebugReportCallbackCreateInfoType const *VulkanSample::get_debug_report_callback_create_info() const { #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) - static vk::DebugReportCallbackCreateInfoEXT debug_report_callback_createInfo{.flags = vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::eWarning | vk::DebugReportFlagBitsEXT::ePerformanceWarning, - .pfnCallback = vkb::core::debug_callback}; + static vk::DebugReportCallbackCreateInfoEXT debug_report_callback_createInfo{ + .flags = vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::eWarning | vk::DebugReportFlagBitsEXT::ePerformanceWarning, + .pfnCallback = vkb::core::debug_callback}; if constexpr (bindingType == vkb::BindingType::Cpp) { return &debug_report_callback_createInfo; @@ -784,9 +781,10 @@ template inline typename VulkanSample::DebugUtilsMessengerCreateInfoType const *VulkanSample::get_debug_utils_messenger_create_info() const { #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) - static vk::DebugUtilsMessengerCreateInfoEXT debug_utils_messenger_create_info{.messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eError | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning, - .messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance, - .pfnUserCallback = vkb::core::debug_utils_messenger_callback}; + static vk::DebugUtilsMessengerCreateInfoEXT debug_utils_messenger_create_info{ + .messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eError | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning, + .messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance, + .pfnUserCallback = vkb::core::debug_utils_messenger_callback}; if constexpr (bindingType == vkb::BindingType::Cpp) { return &debug_utils_messenger_create_info; @@ -801,7 +799,8 @@ inline typename VulkanSample::DebugUtilsMessengerCreateInfoType con } template -inline typename VulkanSample::InstanceCreateFlagsType VulkanSample::get_instance_create_flags(std::vector const &enabled_extensions) const +inline typename VulkanSample::InstanceCreateFlagsType + VulkanSample::get_instance_create_flags(std::vector const &enabled_extensions) const { vk::InstanceCreateFlags flags; #if defined(VKB_ENABLE_PORTABILITY) @@ -852,9 +851,8 @@ inline void const *VulkanSample::get_instance_create_info_extension if (!enabled_layer_settings.empty()) { // If layer settings are defined, then activate the sample's required layer settings during instance creation - static vk::LayerSettingsCreateInfoEXT layer_settings_create_info_ext{.pNext = pNext, - .settingCount = static_cast(enabled_layer_settings.size()), - .pSettings = enabled_layer_settings.data()}; + static vk::LayerSettingsCreateInfoEXT layer_settings_create_info_ext{ + .pNext = pNext, .settingCount = static_cast(enabled_layer_settings.size()), .pSettings = enabled_layer_settings.data()}; pNext = &layer_settings_create_info_ext; } } @@ -1152,8 +1150,7 @@ inline void VulkanSample::input_event(const InputEvent &input_event if (input_event.get_source() == EventSource::Keyboard) { const auto &key_event = static_cast(input_event); - if (key_event.get_action() == KeyAction::Down && - (key_event.get_code() == KeyCode::PrintScreen || key_event.get_code() == KeyCode::F12)) + if (key_event.get_action() == KeyAction::Down && (key_event.get_code() == KeyCode::PrintScreen || key_event.get_code() == KeyCode::F12)) { vkb::common::screenshot(*render_context, "screenshot-" + get_name()); } @@ -1204,9 +1201,8 @@ inline bool VulkanSample::prepare(const ApplicationOptions &options #ifdef VKB_VULKAN_DEBUG { std::vector available_instance_extensions = vk::enumerateInstanceExtensionProperties(); - auto debugExtensionIt = - std::ranges::find_if(available_instance_extensions, - [](vk::ExtensionProperties const &ep) { return strcmp(ep.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0; }); + auto debugExtensionIt = std::ranges::find_if( + available_instance_extensions, [](vk::ExtensionProperties const &ep) { return strcmp(ep.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0; }); if (debugExtensionIt != available_instance_extensions.end()) { LOGI("Vulkan debug utils enabled ({})", VK_EXT_DEBUG_UTILS_EXTENSION_NAME); @@ -1237,7 +1233,8 @@ inline bool VulkanSample::prepare(const ApplicationOptions &options } else { - debug_utils_messenger = instance->get_handle().createDebugUtilsMessengerEXT(*reinterpret_cast(debug_utils_messenger_create_info)); + debug_utils_messenger = instance->get_handle().createDebugUtilsMessengerEXT( + *reinterpret_cast(debug_utils_messenger_create_info)); } } } @@ -1252,7 +1249,8 @@ inline bool VulkanSample::prepare(const ApplicationOptions &options } else { - debug_report_callback = instance->get_handle().createDebugReportCallbackEXT(*reinterpret_cast(debug_report_callback_create_info)); + debug_report_callback = instance->get_handle().createDebugReportCallbackEXT( + *reinterpret_cast(debug_report_callback_create_info)); } } } @@ -1285,7 +1283,8 @@ inline bool VulkanSample::prepare(const ApplicationOptions &options } } - // Shaders generated by Slang require a certain SPIR-V environment that can't be satisfied by Vulkan 1.0, so we need to expliclity up that to at least 1.1 and enable some required extensions + // Shaders generated by Slang require a certain SPIR-V environment that can't be satisfied by Vulkan 1.0, so we need to expliclity up that to at least 1.1 + // and enable some required extensions if (get_shading_language() == ShadingLanguage::SLANG) { assert(VK_API_VERSION_1_1 <= get_api_version()); @@ -1303,9 +1302,8 @@ inline bool VulkanSample::prepare(const ApplicationOptions &options if (!debug_utils) { std::vector available_device_extensions = physical_device->get_handle().enumerateDeviceExtensionProperties(); - auto debugExtensionIt = - std::ranges::find_if(available_device_extensions, - [](vk::ExtensionProperties const &ep) { return strcmp(ep.extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME) == 0; }); + auto debugExtensionIt = std::ranges::find_if( + available_device_extensions, [](vk::ExtensionProperties const &ep) { return strcmp(ep.extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME) == 0; }); if (debugExtensionIt != available_device_extensions.end()) { LOGI("Vulkan debug utils enabled ({})", VK_EXT_DEBUG_MARKER_EXTENSION_NAME); @@ -1358,11 +1356,8 @@ inline void VulkanSample::create_gui(const Window &window, StatsTyp } else { - gui = std::make_unique(reinterpret_cast(get_render_context()), - window, - reinterpret_cast(stats), - font_size, - explicit_update); + gui = std::make_unique(reinterpret_cast(get_render_context()), window, + reinterpret_cast(stats), font_size, explicit_update); } } @@ -1431,7 +1426,8 @@ inline void VulkanSample::request_instance_extensions(std::unordere requested_extensions[VK_EXT_DEBUG_REPORT_EXTENSION_NAME] = vkb::RequestMode::Optional; #endif -#if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) && (defined(VKB_VALIDATION_LAYERS_GPU_ASSISTED) || defined(VKB_VALIDATION_LAYERS_BEST_PRACTICES) || defined(VKB_VALIDATION_LAYERS_SYNCHRONIZATION)) +#if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) && (defined(VKB_VALIDATION_LAYERS_GPU_ASSISTED) || defined(VKB_VALIDATION_LAYERS_BEST_PRACTICES) || \ + defined(VKB_VALIDATION_LAYERS_SYNCHRONIZATION)) requested_extensions[VK_EXT_LAYER_SETTINGS_EXTENSION_NAME] = vkb::RequestMode::Optional; #endif } @@ -1494,13 +1490,11 @@ inline void VulkanSample::request_layer_settings_impl(std::vector inline void VulkanSample::request_validation_feature_enables(std::vector &requested_layer_settings) const -{ -} +{} template inline void VulkanSample::reset_stats_view() -{ -} +{} template inline bool VulkanSample::resize(uint32_t width, uint32_t height) @@ -1617,14 +1611,12 @@ inline void VulkanSample::set_viewport_and_scissor(vkb::core::Comma } else { - set_viewport_and_scissor_impl(reinterpret_cast(command_buffer), - reinterpret_cast(extent)); + set_viewport_and_scissor_impl(reinterpret_cast(command_buffer), reinterpret_cast(extent)); } } template -inline void VulkanSample::set_viewport_and_scissor_impl(vkb::core::CommandBufferCpp const &command_buffer, - vk::Extent2D const &extent) +inline void VulkanSample::set_viewport_and_scissor_impl(vkb::core::CommandBufferCpp const &command_buffer, vk::Extent2D const &extent) { command_buffer.get_handle().setViewport(0, {{0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}}); command_buffer.get_handle().setScissor(0, vk::Rect2D{{}, extent}); @@ -1672,10 +1664,9 @@ inline void VulkanSample::update_debug_window() get_debug_info().template insert("driver_version", driver_version_str); get_debug_info().template insert("resolution", to_string(static_cast(render_context->get_swapchain().get_extent()))); - get_debug_info().template insert("surface_format", - to_string(render_context->get_swapchain().get_format()) + " (" + - to_string(vkb::common::get_bits_per_pixel(render_context->get_swapchain().get_format())) + - "bpp)"); + get_debug_info().template insert( + "surface_format", to_string(render_context->get_swapchain().get_format()) + " (" + + to_string(vkb::common::get_bits_per_pixel(render_context->get_swapchain().get_format())) + "bpp)"); if (scene != nullptr) { diff --git a/framework/vulkan_type_mapping.h b/framework/vulkan_type_mapping.h index 7a6c59204c..717ee5812b 100644 --- a/framework/vulkan_type_mapping.h +++ b/framework/vulkan_type_mapping.h @@ -25,8 +25,7 @@ namespace vkb { template struct VulkanTypeMapping -{ -}; +{}; template struct VulkanTypeMapping diff --git a/samples/api/compute_nbody/compute_nbody.cpp b/samples/api/compute_nbody/compute_nbody.cpp index 333377b68a..a7a16562c4 100644 --- a/samples/api/compute_nbody/compute_nbody.cpp +++ b/samples/api/compute_nbody/compute_nbody.cpp @@ -104,26 +104,18 @@ void ComputeNBody::build_command_buffers() // Acquire if (graphics.queue_family_index != compute.queue_family_index) { - VkBufferMemoryBarrier buffer_barrier = - { - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - nullptr, - 0, - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, - compute.queue_family_index, - graphics.queue_family_index, - compute.storage_buffer->get_handle(), - 0, - compute.storage_buffer->get_size()}; - - vkCmdPipelineBarrier( - draw_cmd_buffers[i], - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, - 0, - 0, nullptr, - 1, &buffer_barrier, - 0, nullptr); + VkBufferMemoryBarrier buffer_barrier = {VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + nullptr, + 0, + VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, + compute.queue_family_index, + graphics.queue_family_index, + compute.storage_buffer->get_handle(), + 0, + compute.storage_buffer->get_size()}; + + vkCmdPipelineBarrier(draw_cmd_buffers[i], VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, 0, 0, nullptr, 1, + &buffer_barrier, 0, nullptr); } // Draw the particle system using the update vertex buffer @@ -143,26 +135,18 @@ void ComputeNBody::build_command_buffers() // Release barrier if (graphics.queue_family_index != compute.queue_family_index) { - VkBufferMemoryBarrier buffer_barrier = - { - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - nullptr, - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, - 0, - graphics.queue_family_index, - compute.queue_family_index, - compute.storage_buffer->get_handle(), - 0, - compute.storage_buffer->get_size()}; - - vkCmdPipelineBarrier( - draw_cmd_buffers[i], - VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - 0, - 0, nullptr, - 1, &buffer_barrier, - 0, nullptr); + VkBufferMemoryBarrier buffer_barrier = {VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + nullptr, + VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, + 0, + graphics.queue_family_index, + compute.queue_family_index, + compute.storage_buffer->get_handle(), + 0, + compute.storage_buffer->get_size()}; + + vkCmdPipelineBarrier(draw_cmd_buffers[i], VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, + &buffer_barrier, 0, nullptr); } VK_CHECK(vkEndCommandBuffer(draw_cmd_buffers[i])); @@ -178,26 +162,18 @@ void ComputeNBody::build_compute_command_buffer() // Acquire if (graphics.queue_family_index != compute.queue_family_index) { - VkBufferMemoryBarrier buffer_barrier = - { - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - nullptr, - 0, - VK_ACCESS_SHADER_WRITE_BIT, - graphics.queue_family_index, - compute.queue_family_index, - compute.storage_buffer->get_handle(), - 0, - compute.storage_buffer->get_size()}; - - vkCmdPipelineBarrier( - compute.command_buffer, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - 0, - 0, nullptr, - 1, &buffer_barrier, - 0, nullptr); + VkBufferMemoryBarrier buffer_barrier = {VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + nullptr, + 0, + VK_ACCESS_SHADER_WRITE_BIT, + graphics.queue_family_index, + compute.queue_family_index, + compute.storage_buffer->get_handle(), + 0, + compute.storage_buffer->get_size()}; + + vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, &buffer_barrier, 0, + nullptr); } // First pass: Calculate particle movement @@ -215,14 +191,8 @@ void ComputeNBody::build_compute_command_buffer() memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - vkCmdPipelineBarrier( - compute.command_buffer, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_FLAGS_NONE, - 0, nullptr, - 1, &memory_barrier, - 0, nullptr); + vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_FLAGS_NONE, 0, nullptr, 1, + &memory_barrier, 0, nullptr); // Second pass: Integrate particles // ------------------------------------------------------------------------------------------------------- @@ -232,26 +202,12 @@ void ComputeNBody::build_compute_command_buffer() // Release if (graphics.queue_family_index != compute.queue_family_index) { - VkBufferMemoryBarrier buffer_barrier = - { - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - nullptr, - VK_ACCESS_SHADER_WRITE_BIT, - 0, - compute.queue_family_index, - graphics.queue_family_index, - compute.storage_buffer->get_handle(), - 0, - compute.storage_buffer->get_size()}; - - vkCmdPipelineBarrier( - compute.command_buffer, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, - 0, nullptr, - 1, &buffer_barrier, - 0, nullptr); + VkBufferMemoryBarrier buffer_barrier = { + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT, 0, compute.queue_family_index, graphics.queue_family_index, + compute.storage_buffer->get_handle(), 0, compute.storage_buffer->get_size()}; + + vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, &buffer_barrier, 0, + nullptr); } vkEndCommandBuffer(compute.command_buffer); @@ -267,12 +223,8 @@ void ComputeNBody::prepare_storage_buffers() }; #else std::vector attractors = { - glm::vec3(5.0f, 0.0f, 0.0f), - glm::vec3(-5.0f, 0.0f, 0.0f), - glm::vec3(0.0f, 0.0f, 5.0f), - glm::vec3(0.0f, 0.0f, -5.0f), - glm::vec3(0.0f, 4.0f, 0.0f), - glm::vec3(0.0f, -8.0f, 0.0f), + glm::vec3(5.0f, 0.0f, 0.0f), glm::vec3(-5.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 5.0f), + glm::vec3(0.0f, 0.0f, -5.0f), glm::vec3(0.0f, 4.0f, 0.0f), glm::vec3(0.0f, -8.0f, 0.0f), }; #endif @@ -305,7 +257,8 @@ void ComputeNBody::prepare_storage_buffers() // Velocity glm::vec3 angular = glm::vec3(0.5f, 1.5f, 0.5f) * (((i % 2) == 0) ? 1.0f : -1.0f); - glm::vec3 velocity = glm::cross((position - attractors[i]), angular) + glm::vec3(rnd_distribution(rnd_engine), rnd_distribution(rnd_engine), rnd_distribution(rnd_engine) * 0.025f); + glm::vec3 velocity = glm::cross((position - attractors[i]), angular) + + glm::vec3(rnd_distribution(rnd_engine), rnd_distribution(rnd_engine), rnd_distribution(rnd_engine) * 0.025f); float mass = (rnd_distribution(rnd_engine) * 0.5f + 0.5f) * 75.0f; particle.pos = glm::vec4(position, mass); @@ -325,10 +278,9 @@ void ComputeNBody::prepare_storage_buffers() // SSBO won't be changed on the host after upload so copy to device local memory vkb::core::BufferC staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), particle_buffer); - compute.storage_buffer = std::make_unique(get_device(), - storage_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + compute.storage_buffer = std::make_unique( + get_device(), storage_buffer_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VMA_MEMORY_USAGE_GPU_ONLY); // Copy from staging buffer to storage buffer VkCommandBuffer copy_command = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); @@ -338,26 +290,12 @@ void ComputeNBody::prepare_storage_buffers() // Execute a transfer to the compute queue, if necessary if (graphics.queue_family_index != compute.queue_family_index) { - VkBufferMemoryBarrier buffer_barrier = - { - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - nullptr, - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, - 0, - graphics.queue_family_index, - compute.queue_family_index, - compute.storage_buffer->get_handle(), - 0, - compute.storage_buffer->get_size()}; - - vkCmdPipelineBarrier( - copy_command, - VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - 0, - 0, nullptr, - 1, &buffer_barrier, - 0, nullptr); + VkBufferMemoryBarrier buffer_barrier = { + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, nullptr, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, 0, graphics.queue_family_index, compute.queue_family_index, + compute.storage_buffer->get_handle(), 0, compute.storage_buffer->get_size()}; + + vkCmdPipelineBarrier(copy_command, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, &buffer_barrier, 0, + nullptr); } get_device().flush_command_buffer(copy_command, queue, true); @@ -365,17 +303,12 @@ void ComputeNBody::prepare_storage_buffers() void ComputeNBody::setup_descriptor_pool() { - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -390,27 +323,18 @@ void ComputeNBody::setup_descriptor_set_layout() }; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &graphics.descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &graphics.descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&graphics.descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &graphics.pipeline_layout)); } void ComputeNBody::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &graphics.descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &graphics.descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &graphics.descriptor_set)); @@ -429,50 +353,25 @@ void ComputeNBody::setup_descriptor_set() void ComputeNBody::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_POINT_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_POINT_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_ALWAYS); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_ALWAYS); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamicState = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Rendering pipeline // Load shaders @@ -494,11 +393,7 @@ void ComputeNBody::prepare_pipelines() vertex_input_state.vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - graphics.pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(graphics.pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -548,57 +443,34 @@ void ComputeNBody::prepare_compute() std::vector set_layout_bindings = { // Binding 0 : Particle position storage buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, - VK_SHADER_STAGE_COMPUTE_BIT, - 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 0), // Binding 1 : Uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_COMPUTE_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 1), }; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &compute.descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &compute.descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&compute.descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &compute.pipeline_layout)); - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &compute.descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &compute.descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &compute.descriptor_set)); - VkDescriptorBufferInfo storage_buffer_descriptor = create_descriptor(*compute.storage_buffer); - VkDescriptorBufferInfo uniform_buffer_descriptor = create_descriptor(*compute.uniform_buffer); - std::vector compute_write_descriptor_sets = - { - // Binding 0 : Particle position storage buffer - vkb::initializers::write_descriptor_set( - compute.descriptor_set, - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, - 0, - &storage_buffer_descriptor), - // Binding 1 : Uniform buffer - vkb::initializers::write_descriptor_set( - compute.descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 1, - &uniform_buffer_descriptor)}; - - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(compute_write_descriptor_sets.size()), compute_write_descriptor_sets.data(), 0, NULL); + VkDescriptorBufferInfo storage_buffer_descriptor = create_descriptor(*compute.storage_buffer); + VkDescriptorBufferInfo uniform_buffer_descriptor = create_descriptor(*compute.uniform_buffer); + std::vector compute_write_descriptor_sets = { + // Binding 0 : Particle position storage buffer + vkb::initializers::write_descriptor_set(compute.descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, &storage_buffer_descriptor), + // Binding 1 : Uniform buffer + vkb::initializers::write_descriptor_set(compute.descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &uniform_buffer_descriptor)}; + + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(compute_write_descriptor_sets.size()), compute_write_descriptor_sets.data(), 0, + NULL); // Create pipelines VkComputePipelineCreateInfo compute_pipeline_create_info = vkb::initializers::compute_pipeline_create_info(compute.pipeline_layout, 0); @@ -629,8 +501,8 @@ void ComputeNBody::prepare_compute() specialization_data.power = 0.75f; specialization_data.soften = 0.05f; - VkSpecializationInfo specialization_info = - vkb::initializers::specialization_info(static_cast(specialization_map_entries.size()), specialization_map_entries.data(), sizeof(specialization_data), &specialization_data); + VkSpecializationInfo specialization_info = vkb::initializers::specialization_info( + static_cast(specialization_map_entries.size()), specialization_map_entries.data(), sizeof(specialization_data), &specialization_data); compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info; VK_CHECK(vkCreateComputePipelines(get_device().get_handle(), pipeline_cache, 1, &compute_pipeline_create_info, nullptr, &compute.pipeline_calculate)); @@ -640,8 +512,7 @@ void ComputeNBody::prepare_compute() specialization_map_entries.clear(); specialization_map_entries.push_back(vkb::initializers::specialization_map_entry(0, 0, sizeof(uint32_t))); - specialization_info = - vkb::initializers::specialization_info(1, specialization_map_entries.data(), sizeof(work_group_size), &work_group_size); + specialization_info = vkb::initializers::specialization_info(1, specialization_map_entries.data(), sizeof(work_group_size), &work_group_size); compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info; VK_CHECK(vkCreateComputePipelines(get_device().get_handle(), pipeline_cache, 1, &compute_pipeline_create_info, nullptr, &compute.pipeline_integrate)); @@ -654,10 +525,7 @@ void ComputeNBody::prepare_compute() // Create a command buffer for compute operations VkCommandBufferAllocateInfo command_buffer_allocate_info = - vkb::initializers::command_buffer_allocate_info( - compute.command_pool, - VK_COMMAND_BUFFER_LEVEL_PRIMARY, - 1); + vkb::initializers::command_buffer_allocate_info(compute.command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK(vkAllocateCommandBuffers(get_device().get_handle(), &command_buffer_allocate_info, &compute.command_buffer)); @@ -688,10 +556,7 @@ void ComputeNBody::prepare_compute() // Create a transient command buffer for setting up the initial buffer transfer state VkCommandBufferAllocateInfo command_buffer_allocate_info = - vkb::initializers::command_buffer_allocate_info( - compute.command_pool, - VK_COMMAND_BUFFER_LEVEL_PRIMARY, - 1); + vkb::initializers::command_buffer_allocate_info(compute.command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK(vkAllocateCommandBuffers(get_device().get_handle(), &command_buffer_allocate_info, &transfer_command)); @@ -699,45 +564,23 @@ void ComputeNBody::prepare_compute() command_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; VK_CHECK(vkBeginCommandBuffer(transfer_command, &command_buffer_info)); - VkBufferMemoryBarrier acquire_buffer_barrier = - { - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - nullptr, - 0, - VK_ACCESS_SHADER_WRITE_BIT, - graphics.queue_family_index, - compute.queue_family_index, - compute.storage_buffer->get_handle(), - 0, - compute.storage_buffer->get_size()}; - vkCmdPipelineBarrier( - transfer_command, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - 0, - 0, nullptr, - 1, &acquire_buffer_barrier, - 0, nullptr); - - VkBufferMemoryBarrier release_buffer_barrier = - { - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, - nullptr, - VK_ACCESS_SHADER_WRITE_BIT, - 0, - compute.queue_family_index, - graphics.queue_family_index, - compute.storage_buffer->get_handle(), - 0, - compute.storage_buffer->get_size()}; - vkCmdPipelineBarrier( - transfer_command, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, - 0, nullptr, - 1, &release_buffer_barrier, - 0, nullptr); + VkBufferMemoryBarrier acquire_buffer_barrier = {VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, + nullptr, + 0, + VK_ACCESS_SHADER_WRITE_BIT, + graphics.queue_family_index, + compute.queue_family_index, + compute.storage_buffer->get_handle(), + 0, + compute.storage_buffer->get_size()}; + vkCmdPipelineBarrier(transfer_command, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, &acquire_buffer_barrier, + 0, nullptr); + + VkBufferMemoryBarrier release_buffer_barrier = { + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT, 0, compute.queue_family_index, graphics.queue_family_index, + compute.storage_buffer->get_handle(), 0, compute.storage_buffer->get_size()}; + vkCmdPipelineBarrier(transfer_command, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 1, &release_buffer_barrier, + 0, nullptr); // Copied from Device::flush_command_buffer, which we can't use because it would be // working with the wrong command pool @@ -770,16 +613,12 @@ void ComputeNBody::prepare_compute() void ComputeNBody::prepare_uniform_buffers() { // Compute shader uniform buffer block - compute.uniform_buffer = std::make_unique(get_device(), - sizeof(compute.ubo), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + compute.uniform_buffer = + std::make_unique(get_device(), sizeof(compute.ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); // Vertex shader uniform buffer block - graphics.uniform_buffer = std::make_unique(get_device(), - sizeof(graphics.ubo), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + graphics.uniform_buffer = + std::make_unique(get_device(), sizeof(graphics.ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_compute_uniform_buffers(1.0f); update_graphics_uniform_buffers(); @@ -848,7 +687,8 @@ bool ComputeNBody::prepare(const vkb::ApplicationOptions &options) // Not all implementations support a work group size of 256, so we need to check with the device limits work_group_size = std::min(static_cast(256), get_device().get_gpu().get_properties().limits.maxComputeWorkGroupSize[0]); // Same for shared data size for passing data between shader invocations - shared_data_size = std::min(static_cast(1024), static_cast(get_device().get_gpu().get_properties().limits.maxComputeSharedMemorySize / sizeof(glm::vec4))); + shared_data_size = std::min(static_cast(1024), + static_cast(get_device().get_gpu().get_properties().limits.maxComputeSharedMemorySize / sizeof(glm::vec4))); load_assets(); setup_descriptor_pool(); diff --git a/samples/api/compute_nbody/compute_nbody.h b/samples/api/compute_nbody/compute_nbody.h index 355c8730bb..74930c623f 100644 --- a/samples/api/compute_nbody/compute_nbody.h +++ b/samples/api/compute_nbody/compute_nbody.h @@ -64,10 +64,10 @@ class ComputeNBody : public ApiVulkanSample // Resources for the compute part of the example struct { - std::unique_ptr storage_buffer; // (Shader) storage buffer object containing the particles - std::unique_ptr uniform_buffer; // Uniform buffer object containing particle system parameters - VkQueue queue; // Separate queue for compute commands (queue family may differ from the one used for graphics) - VkCommandPool command_pool; // Use a separate command pool (queue family may differ from the one used for graphics) + std::unique_ptr storage_buffer; // (Shader) storage buffer object containing the particles + std::unique_ptr uniform_buffer; // Uniform buffer object containing particle system parameters + VkQueue queue; // Separate queue for compute commands (queue family may differ from the one used for graphics) + VkCommandPool command_pool; // Use a separate command pool (queue family may differ from the one used for graphics) VkCommandBuffer command_buffer; // Command buffer storing the dispatch commands and barriers VkFence fence; // Fence to wait for compute dispatch completion before UBO update VkSemaphore semaphore; // Execution dependency between compute & graphic submission diff --git a/samples/api/dynamic_uniform_buffers/dynamic_uniform_buffers.cpp b/samples/api/dynamic_uniform_buffers/dynamic_uniform_buffers.cpp index 096d09d028..6b88833c8c 100644 --- a/samples/api/dynamic_uniform_buffers/dynamic_uniform_buffers.cpp +++ b/samples/api/dynamic_uniform_buffers/dynamic_uniform_buffers.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -153,53 +153,13 @@ void DynamicUniformBuffers::generate_cube() { // Setup vertices indices for a colored cube std::vector vertices = { - {{-1.0f, -1.0f, 1.0f}, {1.0f, 0.0f, 0.0f}}, - {{1.0f, -1.0f, 1.0f}, {0.0f, 1.0f, 0.0f}}, - {{1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 0.0f}}, - {{-1.0f, -1.0f, -1.0f}, {1.0f, 0.0f, 0.0f}}, - {{1.0f, -1.0f, -1.0f}, {0.0f, 1.0f, 0.0f}}, - {{1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 0.0f}}, + {{-1.0f, -1.0f, 1.0f}, {1.0f, 0.0f, 0.0f}}, {{1.0f, -1.0f, 1.0f}, {0.0f, 1.0f, 0.0f}}, {{1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 0.0f}}, {{-1.0f, -1.0f, -1.0f}, {1.0f, 0.0f, 0.0f}}, {{1.0f, -1.0f, -1.0f}, {0.0f, 1.0f, 0.0f}}, + {{1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 1.0f}}, {{-1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 0.0f}}, }; std::vector indices = { - 0, - 1, - 2, - 2, - 3, - 0, - 1, - 5, - 6, - 6, - 2, - 1, - 7, - 6, - 5, - 5, - 4, - 7, - 4, - 0, - 3, - 3, - 7, - 4, - 4, - 5, - 1, - 1, - 0, - 4, - 3, - 2, - 6, - 6, - 7, - 3, + 0, 1, 2, 2, 3, 0, 1, 5, 6, 6, 2, 1, 7, 6, 5, 5, 4, 7, 4, 0, 3, 3, 7, 4, 4, 5, 1, 1, 0, 4, 3, 2, 6, 6, 7, 3, }; index_count = static_cast(indices.size()); @@ -210,67 +170,46 @@ void DynamicUniformBuffers::generate_cube() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory // Vertex buffer - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); } void DynamicUniformBuffers::setup_descriptor_pool() { // Example uses one ubo and one image sampler - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void DynamicUniformBuffers::setup_descriptor_set_layout() { - std::vector set_layout_bindings = - { - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_SHADER_STAGE_VERTEX_BIT, 1), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2)}; + std::vector set_layout_bindings = { + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_SHADER_STAGE_VERTEX_BIT, 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2)}; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void DynamicUniformBuffers::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -292,51 +231,26 @@ void DynamicUniformBuffers::setup_descriptor_set() void DynamicUniformBuffers::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages; @@ -358,11 +272,7 @@ void DynamicUniformBuffers::prepare_pipelines() vertex_input_state.vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -403,15 +313,9 @@ void DynamicUniformBuffers::prepare_uniform_buffers() // Vertex shader uniform buffer block // Static shared uniform buffer object with projection and view matrix - uniform_buffers.view = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.view = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); - uniform_buffers.dynamic = std::make_unique(get_device(), - buffer_size, - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.dynamic = std::make_unique(get_device(), buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); // Prepare per-object matrices with offsets and random rotations std::default_random_engine rnd_engine(lock_simulation_speed ? 0 : static_cast(time(nullptr))); @@ -467,8 +371,7 @@ void DynamicUniformBuffers::update_dynamic_uniform_buffer(float delta_time, bool rotations[index] += animation_timer * rotation_speeds[index]; // Update matrices - glm::vec3 pos(-((fdim * offset.x) / 2.0f) + offset.x / 2.0f + fx * offset.x, - -((fdim * offset.y) / 2.0f) + offset.y / 2.0f + fy * offset.y, + glm::vec3 pos(-((fdim * offset.x) / 2.0f) + offset.x / 2.0f + fx * offset.x, -((fdim * offset.y) / 2.0f) + offset.y / 2.0f + fy * offset.y, -((fdim * offset.z) / 2.0f) + offset.z / 2.0f + fz * offset.z); *model_mat = glm::translate(glm::mat4(1.0f), pos); *model_mat = glm::rotate(*model_mat, rotations[index].x, glm::vec3(1.0f, 1.0f, 0.0f)); diff --git a/samples/api/hdr/hdr.cpp b/samples/api/hdr/hdr.cpp index d9c562b13e..a9de03641a 100644 --- a/samples/api/hdr/hdr.cpp +++ b/samples/api/hdr/hdr.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -165,7 +165,8 @@ void HDR::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(filter_pass.width, filter_pass.height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, NULL); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, + NULL); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.bloom[1]); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); @@ -202,7 +203,8 @@ void HDR::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, NULL); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, + NULL); // Scene vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.composition); @@ -554,11 +556,10 @@ void HDR::load_assets() void HDR::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; - uint32_t num_descriptor_sets = 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; + uint32_t num_descriptor_sets = 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -576,10 +577,7 @@ void HDR::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.models)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.models, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.models, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.models)); @@ -589,7 +587,8 @@ void HDR::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.bloom_filter)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.bloom_filter, 1); @@ -601,7 +600,8 @@ void HDR::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.composition)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.composition, 1); @@ -610,11 +610,7 @@ void HDR::setup_descriptor_set_layout() void HDR::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.models, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.models, 1); // 3D object descriptor set VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.object)); @@ -676,57 +672,28 @@ void HDR::setup_descriptor_sets() void HDR::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layouts.models, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layouts.models, render_pass, 0); std::vector blend_attachment_states = { vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), @@ -847,16 +814,12 @@ void HDR::prepare_pipelines() void HDR::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffers.matrices = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.matrices = + std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); // Params - uniform_buffers.params = std::make_unique(get_device(), - sizeof(ubo_params), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.params = + std::make_unique(get_device(), sizeof(ubo_params), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); update_params(); diff --git a/samples/api/hello_triangle/hello_triangle.cpp b/samples/api/hello_triangle/hello_triangle.cpp index 9956c50874..c8cc0859d2 100644 --- a/samples/api/hello_triangle/hello_triangle.cpp +++ b/samples/api/hello_triangle/hello_triangle.cpp @@ -25,7 +25,8 @@ #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) /// @brief A debug callback used to report messages from the validation layers. See instance creation for details on how this is set up -static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, VkDebugUtilsMessageTypeFlagsEXT message_type, +static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, + VkDebugUtilsMessageTypeFlagsEXT message_type, const VkDebugUtilsMessengerCallbackDataEXT *callback_data, void *user_data) { @@ -59,8 +60,7 @@ static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(VkDebugUtilsMessageSeverity * @return true if all required extensions are available * @return false otherwise */ -bool HelloTriangle::validate_extensions(const std::vector &required, - const std::vector &available) +bool HelloTriangle::validate_extensions(const std::vector &required, const std::vector &available) { for (auto extension : required) { @@ -126,8 +126,9 @@ void HelloTriangle::init_instance() #if (defined(VKB_ENABLE_PORTABILITY)) required_instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); bool portability_enumeration_available = false; - if (std::ranges::any_of(available_instance_extensions, - [](VkExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(available_instance_extensions, [](VkExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; + })) { required_instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); portability_enumeration_available = true; @@ -180,18 +181,14 @@ void HelloTriangle::init_instance() #endif VkApplicationInfo app{ - .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, - .pApplicationName = "Hello Triangle", - .pEngineName = "Vulkan Samples", - .apiVersion = VK_API_VERSION_1_1}; - - VkInstanceCreateInfo instance_info{ - .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, - .pApplicationInfo = &app, - .enabledLayerCount = static_cast(requested_instance_layers.size()), - .ppEnabledLayerNames = requested_instance_layers.data(), - .enabledExtensionCount = static_cast(required_instance_extensions.size()), - .ppEnabledExtensionNames = required_instance_extensions.data()}; + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "Hello Triangle", .pEngineName = "Vulkan Samples", .apiVersion = VK_API_VERSION_1_1}; + + VkInstanceCreateInfo instance_info{.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pApplicationInfo = &app, + .enabledLayerCount = static_cast(requested_instance_layers.size()), + .ppEnabledLayerNames = requested_instance_layers.data(), + .enabledExtensionCount = static_cast(required_instance_extensions.size()), + .ppEnabledExtensionNames = required_instance_extensions.data()}; #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) // Validation layers help finding wrong api usage, we enable them when explicitly requested or in debug builds @@ -287,7 +284,8 @@ void HelloTriangle::init_device() // Since this sample has visual output, the device needs to support the swapchain extension std::vector required_device_extensions{VK_KHR_SWAPCHAIN_EXTENSION_NAME}; - // Shaders generated by Slang require a certain SPIR-V environment that can't be satisfied by Vulkan 1.0, so we need to expliclity up that to at least 1.1 and enable some required extensions + // Shaders generated by Slang require a certain SPIR-V environment that can't be satisfied by Vulkan 1.0, so we need to expliclity up that to at least 1.1 + // and enable some required extensions if (get_shading_language() == vkb::ShadingLanguage::SLANG) { required_device_extensions.push_back(VK_KHR_SPIRV_1_4_EXTENSION_NAME); @@ -302,8 +300,9 @@ void HelloTriangle::init_device() #if (defined(VKB_ENABLE_PORTABILITY)) // VK_KHR_portability_subset must be enabled if present in the implementation (e.g on macOS/iOS using MoltenVK with beta extensions enabled) - if (std::ranges::any_of(device_extensions, - [](VkExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(device_extensions, [](VkExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME) == 0; + })) { required_device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME); } @@ -312,18 +311,16 @@ void HelloTriangle::init_device() // The sample uses a single graphics queue const float queue_priority = 0.5f; - VkDeviceQueueCreateInfo queue_info{ - .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, - .queueFamilyIndex = static_cast(context.graphics_queue_index), - .queueCount = 1, - .pQueuePriorities = &queue_priority}; + VkDeviceQueueCreateInfo queue_info{.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .queueFamilyIndex = static_cast(context.graphics_queue_index), + .queueCount = 1, + .pQueuePriorities = &queue_priority}; - VkDeviceCreateInfo device_info{ - .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, - .queueCreateInfoCount = 1, - .pQueueCreateInfos = &queue_info, - .enabledExtensionCount = static_cast(required_device_extensions.size()), - .ppEnabledExtensionNames = required_device_extensions.data()}; + VkDeviceCreateInfo device_info{.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &queue_info, + .enabledExtensionCount = static_cast(required_device_extensions.size()), + .ppEnabledExtensionNames = required_device_extensions.data()}; VK_CHECK(vkCreateDevice(context.gpu, &device_info, nullptr, &context.device)); volkLoadDevice(context.device); @@ -331,15 +328,10 @@ void HelloTriangle::init_device() vkGetDeviceQueue(context.device, context.graphics_queue_index, 0, &context.queue); // This sample uses the Vulkan Memory Alloctor (VMA), which needs to be set up - VmaVulkanFunctions vma_vulkan_func{ - .vkGetInstanceProcAddr = vkGetInstanceProcAddr, - .vkGetDeviceProcAddr = vkGetDeviceProcAddr}; + VmaVulkanFunctions vma_vulkan_func{.vkGetInstanceProcAddr = vkGetInstanceProcAddr, .vkGetDeviceProcAddr = vkGetDeviceProcAddr}; VmaAllocatorCreateInfo allocator_info{ - .physicalDevice = context.gpu, - .device = context.device, - .pVulkanFunctions = &vma_vulkan_func, - .instance = context.instance}; + .physicalDevice = context.gpu, .device = context.device, .pVulkanFunctions = &vma_vulkan_func, .instance = context.instance}; VkResult result = vmaCreateAllocator(&allocator_info, &context.vma_allocator); if (result != VK_SUCCESS) @@ -357,25 +349,19 @@ void HelloTriangle::init_vertex_buffer() { // Vertex data for a single colored triangle const std::vector vertices = { - {{0.5f, -0.5f, 0.5f}, {1.0f, 0.0f, 0.0f}}, - {{0.5f, 0.5f, 0.5f}, {0.0f, 1.0f, 0.0f}}, - {{-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}}}; + {{0.5f, -0.5f, 0.5f}, {1.0f, 0.0f, 0.0f}}, {{0.5f, 0.5f, 0.5f}, {0.0f, 1.0f, 0.0f}}, {{-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}}}; const VkDeviceSize buffer_size = sizeof(vertices[0]) * vertices.size(); // Copy Vertex data to a buffer accessible by the device - VkBufferCreateInfo buffer_info{ - .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .size = buffer_size, - .usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT}; + VkBufferCreateInfo buffer_info{.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = buffer_size, .usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT}; // We use the Vulkan Memory Allocator to find a memory type that can be written and mapped from the host // On most setups this will return a memory type that resides in VRAM and is accessible from the host - VmaAllocationCreateInfo buffer_alloc_ci{ - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - .requiredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}; + VmaAllocationCreateInfo buffer_alloc_ci{.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}; VmaAllocationInfo buffer_alloc_info{}; vmaCreateBuffer(context.vma_allocator, &buffer_info, &buffer_alloc_ci, &vertex_buffer, &vertex_buffer_allocation, &buffer_alloc_info); @@ -395,22 +381,18 @@ void HelloTriangle::init_vertex_buffer() */ void HelloTriangle::init_per_frame(PerFrame &per_frame) { - VkFenceCreateInfo info{ - .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, - .flags = VK_FENCE_CREATE_SIGNALED_BIT}; + VkFenceCreateInfo info{.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .flags = VK_FENCE_CREATE_SIGNALED_BIT}; VK_CHECK(vkCreateFence(context.device, &info, nullptr, &per_frame.queue_submit_fence)); - VkCommandPoolCreateInfo cmd_pool_info{ - .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, - .flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, - .queueFamilyIndex = static_cast(context.graphics_queue_index)}; + VkCommandPoolCreateInfo cmd_pool_info{.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, + .flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, + .queueFamilyIndex = static_cast(context.graphics_queue_index)}; VK_CHECK(vkCreateCommandPool(context.device, &cmd_pool_info, nullptr, &per_frame.primary_command_pool)); - VkCommandBufferAllocateInfo cmd_buf_info{ - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, - .commandPool = per_frame.primary_command_pool, - .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, - .commandBufferCount = 1}; + VkCommandBufferAllocateInfo cmd_buf_info{.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + .commandPool = per_frame.primary_command_pool, + .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, + .commandBufferCount = 1}; VK_CHECK(vkAllocateCommandBuffers(context.device, &cmd_buf_info, &per_frame.primary_command_buffer)); } @@ -522,21 +504,20 @@ void HelloTriangle::init_swapchain() composite = VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR; } - VkSwapchainCreateInfoKHR info{ - .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, - .surface = context.surface, - .minImageCount = desired_swapchain_images, - .imageFormat = format.format, - .imageColorSpace = format.colorSpace, - .imageExtent = swapchain_size, - .imageArrayLayers = 1, - .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, - .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, - .preTransform = pre_transform, - .compositeAlpha = composite, - .presentMode = swapchain_present_mode, - .clipped = true, - .oldSwapchain = old_swapchain}; + VkSwapchainCreateInfoKHR info{.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, + .surface = context.surface, + .minImageCount = desired_swapchain_images, + .imageFormat = format.format, + .imageColorSpace = format.colorSpace, + .imageExtent = swapchain_size, + .imageArrayLayers = 1, + .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, + .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, + .preTransform = pre_transform, + .compositeAlpha = composite, + .presentMode = swapchain_present_mode, + .clipped = true, + .oldSwapchain = old_swapchain}; VK_CHECK(vkCreateSwapchainKHR(context.device, &info, nullptr, &context.swapchain)); @@ -629,11 +610,10 @@ void HelloTriangle::init_render_pass() // We need to wait for the WSI semaphore to signal. // Only pipeline stages which depend on COLOR_ATTACHMENT_OUTPUT_BIT will // actually wait for the semaphore, so we must also wait for that pipeline stage. - VkSubpassDependency dependency{ - .srcSubpass = VK_SUBPASS_EXTERNAL, - .dstSubpass = 0, - .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; + VkSubpassDependency dependency{.srcSubpass = VK_SUBPASS_EXTERNAL, + .dstSubpass = 0, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; // Since we changed the image layout, we need to make the memory visible to // color attachment to modify. @@ -641,14 +621,13 @@ void HelloTriangle::init_render_pass() dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; // Finally, create the renderpass. - VkRenderPassCreateInfo rp_info{ - .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, - .attachmentCount = 1, - .pAttachments = &attachment, - .subpassCount = 1, - .pSubpasses = &subpass, - .dependencyCount = 1, - .pDependencies = &dependency}; + VkRenderPassCreateInfo rp_info{.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, + .attachmentCount = 1, + .pAttachments = &attachment, + .subpassCount = 1, + .pSubpasses = &subpass, + .dependencyCount = 1, + .pDependencies = &dependency}; VK_CHECK(vkCreateRenderPass(context.device, &rp_info, nullptr, &context.render_pass)); } @@ -663,9 +642,7 @@ VkShaderModule HelloTriangle::load_shader_module(const std::string &path) auto spirv = vkb::fs::read_shader_binary_u32(path); VkShaderModuleCreateInfo module_info{ - .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, - .codeSize = spirv.size() * sizeof(uint32_t), - .pCode = spirv.data()}; + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = spirv.size() * sizeof(uint32_t), .pCode = spirv.data()}; VkShaderModule shader_module; VK_CHECK(vkCreateShaderModule(context.device, &module_info, nullptr, &shader_module)); @@ -680,22 +657,17 @@ void HelloTriangle::init_pipeline() { // Create a blank pipeline layout. // We are not binding any resources to the pipeline in this first sample. - VkPipelineLayoutCreateInfo layout_info{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + VkPipelineLayoutCreateInfo layout_info{.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; VK_CHECK(vkCreatePipelineLayout(context.device, &layout_info, nullptr, &context.pipeline_layout)); // The Vertex input properties define the interface between the vertex buffer and the vertex shader. // Specify we will use triangle lists to draw geometry. - VkPipelineInputAssemblyStateCreateInfo input_assembly{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, - .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST}; + VkPipelineInputAssemblyStateCreateInfo input_assembly{.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, + .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST}; // Define the vertex input binding. - VkVertexInputBindingDescription binding_description{ - .binding = 0, - .stride = sizeof(Vertex), - .inputRate = VK_VERTEX_INPUT_RATE_VERTEX}; + VkVertexInputBindingDescription binding_description{.binding = 0, .stride = sizeof(Vertex), .inputRate = VK_VERTEX_INPUT_RATE_VERTEX}; // Define the vertex input attribute. std::array attribute_descriptions{ @@ -703,51 +675,41 @@ void HelloTriangle::init_pipeline() {.location = 1, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(Vertex, color)}}}; // Define the pipeline vertex input. - VkPipelineVertexInputStateCreateInfo vertex_input{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, - .vertexBindingDescriptionCount = 1, - .pVertexBindingDescriptions = &binding_description, - .vertexAttributeDescriptionCount = static_cast(attribute_descriptions.size()), - .pVertexAttributeDescriptions = attribute_descriptions.data()}; + VkPipelineVertexInputStateCreateInfo vertex_input{.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, + .vertexBindingDescriptionCount = 1, + .pVertexBindingDescriptions = &binding_description, + .vertexAttributeDescriptionCount = static_cast(attribute_descriptions.size()), + .pVertexAttributeDescriptions = attribute_descriptions.data()}; // Specify rasterization state. - VkPipelineRasterizationStateCreateInfo raster{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, - .cullMode = VK_CULL_MODE_BACK_BIT, - .frontFace = VK_FRONT_FACE_CLOCKWISE, - .lineWidth = 1.0f}; + VkPipelineRasterizationStateCreateInfo raster{.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, + .cullMode = VK_CULL_MODE_BACK_BIT, + .frontFace = VK_FRONT_FACE_CLOCKWISE, + .lineWidth = 1.0f}; // Our attachment will write to all color channels, but no blending is enabled. - VkPipelineColorBlendAttachmentState blend_attachment{ - .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT}; + VkPipelineColorBlendAttachmentState blend_attachment{.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT}; VkPipelineColorBlendStateCreateInfo blend{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, - .attachmentCount = 1, - .pAttachments = &blend_attachment}; + .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .attachmentCount = 1, .pAttachments = &blend_attachment}; // We will have one viewport and scissor box. - VkPipelineViewportStateCreateInfo viewport{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, - .viewportCount = 1, - .scissorCount = 1}; + VkPipelineViewportStateCreateInfo viewport{.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .viewportCount = 1, .scissorCount = 1}; // Disable all depth testing. - VkPipelineDepthStencilStateCreateInfo depth_stencil{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; + VkPipelineDepthStencilStateCreateInfo depth_stencil{.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; // No multisampling. - VkPipelineMultisampleStateCreateInfo multisample{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, - .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}; + VkPipelineMultisampleStateCreateInfo multisample{.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, + .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}; // Specify that these states will be dynamic, i.e. not part of pipeline state object. std::array dynamics{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, - .dynamicStateCount = static_cast(dynamics.size()), - .pDynamicStates = dynamics.data()}; + VkPipelineDynamicStateCreateInfo dynamic{.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, + .dynamicStateCount = static_cast(dynamics.size()), + .pDynamicStates = dynamics.data()}; // Load our SPIR-V shaders. @@ -769,18 +731,16 @@ void HelloTriangle::init_pipeline() std::array shader_stages{}; // Vertex stage of the pipeline - shader_stages[0] = { - .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .stage = VK_SHADER_STAGE_VERTEX_BIT, - .module = load_shader_module("hello_triangle/" + shader_folder + "/triangle.vert.spv"), - .pName = "main"}; + shader_stages[0] = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_VERTEX_BIT, + .module = load_shader_module("hello_triangle/" + shader_folder + "/triangle.vert.spv"), + .pName = "main"}; // Fragment stage of the pipeline - shader_stages[1] = { - .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .stage = VK_SHADER_STAGE_FRAGMENT_BIT, - .module = load_shader_module("hello_triangle/" + shader_folder + "/triangle.frag.spv"), - .pName = "main"}; + shader_stages[1] = {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .module = load_shader_module("hello_triangle/" + shader_folder + "/triangle.frag.spv"), + .pName = "main"}; VkGraphicsPipelineCreateInfo pipe{ .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, @@ -815,8 +775,7 @@ VkResult HelloTriangle::acquire_next_image(uint32_t *image) VkSemaphore acquire_semaphore; if (context.recycled_semaphores.empty()) { - VkSemaphoreCreateInfo info = { - .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; + VkSemaphoreCreateInfo info = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; VK_CHECK(vkCreateSemaphore(context.device, &info, nullptr, &acquire_semaphore)); } else @@ -878,40 +837,34 @@ void HelloTriangle::render_triangle(uint32_t swapchain_index) VkCommandBuffer cmd = context.per_frame[swapchain_index].primary_command_buffer; // We will only submit this once before it's recycled. - VkCommandBufferBeginInfo begin_info{ - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, - .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; + VkCommandBufferBeginInfo begin_info{.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; // Begin command recording vkBeginCommandBuffer(cmd, &begin_info); // Set clear color values. - VkClearValue clear_value{ - .color = {{0.01f, 0.01f, 0.033f, 1.0f}}}; + VkClearValue clear_value{.color = {{0.01f, 0.01f, 0.033f, 1.0f}}}; // Begin the render pass. - VkRenderPassBeginInfo rp_begin{ - .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, - .renderPass = context.render_pass, - .framebuffer = framebuffer, - .renderArea = {.extent = {.width = context.swapchain_dimensions.width, .height = context.swapchain_dimensions.height}}, - .clearValueCount = 1, - .pClearValues = &clear_value}; + VkRenderPassBeginInfo rp_begin{.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, + .renderPass = context.render_pass, + .framebuffer = framebuffer, + .renderArea = {.extent = {.width = context.swapchain_dimensions.width, .height = context.swapchain_dimensions.height}}, + .clearValueCount = 1, + .pClearValues = &clear_value}; // We will add draw commands in the same command buffer. vkCmdBeginRenderPass(cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); // Bind the graphics pipeline. vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, context.pipeline); - VkViewport vp{ - .width = static_cast(context.swapchain_dimensions.width), - .height = static_cast(context.swapchain_dimensions.height), - .minDepth = 0.0f, - .maxDepth = 1.0f}; + VkViewport vp{.width = static_cast(context.swapchain_dimensions.width), + .height = static_cast(context.swapchain_dimensions.height), + .minDepth = 0.0f, + .maxDepth = 1.0f}; // Set viewport dynamically vkCmdSetViewport(cmd, 0, 1, &vp); - VkRect2D scissor{ - .extent = {.width = context.swapchain_dimensions.width, .height = context.swapchain_dimensions.height}}; + VkRect2D scissor{.extent = {.width = context.swapchain_dimensions.width, .height = context.swapchain_dimensions.height}}; // Set scissor dynamically vkCmdSetScissor(cmd, 0, 1, &scissor); @@ -931,22 +884,20 @@ void HelloTriangle::render_triangle(uint32_t swapchain_index) // Submit it to the queue with a release semaphore. if (context.per_frame[swapchain_index].swapchain_release_semaphore == VK_NULL_HANDLE) { - VkSemaphoreCreateInfo semaphore_info{ - .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; + VkSemaphoreCreateInfo semaphore_info{.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; VK_CHECK(vkCreateSemaphore(context.device, &semaphore_info, nullptr, &context.per_frame[swapchain_index].swapchain_release_semaphore)); } VkPipelineStageFlags wait_stage{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; - VkSubmitInfo info{ - .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, - .waitSemaphoreCount = 1, - .pWaitSemaphores = &context.per_frame[swapchain_index].swapchain_acquire_semaphore, - .pWaitDstStageMask = &wait_stage, - .commandBufferCount = 1, - .pCommandBuffers = &cmd, - .signalSemaphoreCount = 1, - .pSignalSemaphores = &context.per_frame[swapchain_index].swapchain_release_semaphore}; + VkSubmitInfo info{.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .waitSemaphoreCount = 1, + .pWaitSemaphores = &context.per_frame[swapchain_index].swapchain_acquire_semaphore, + .pWaitDstStageMask = &wait_stage, + .commandBufferCount = 1, + .pCommandBuffers = &cmd, + .signalSemaphoreCount = 1, + .pSignalSemaphores = &context.per_frame[swapchain_index].swapchain_release_semaphore}; // Submit command buffer to graphics queue VK_CHECK(vkQueueSubmit(context.queue, 1, &info, context.per_frame[swapchain_index].queue_submit_fence)); } @@ -981,14 +932,13 @@ void HelloTriangle::init_framebuffers() for (auto &image_view : context.swapchain_image_views) { // Build the framebuffer. - VkFramebufferCreateInfo fb_info{ - .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, - .renderPass = context.render_pass, - .attachmentCount = 1, - .pAttachments = &image_view, - .width = context.swapchain_dimensions.width, - .height = context.swapchain_dimensions.height, - .layers = 1}; + VkFramebufferCreateInfo fb_info{.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, + .renderPass = context.render_pass, + .attachmentCount = 1, + .pAttachments = &image_view, + .width = context.swapchain_dimensions.width, + .height = context.swapchain_dimensions.height, + .layers = 1}; VkFramebuffer framebuffer; VK_CHECK(vkCreateFramebuffer(context.device, &fb_info, nullptr, &framebuffer)); @@ -998,8 +948,7 @@ void HelloTriangle::init_framebuffers() } HelloTriangle::HelloTriangle() -{ -} +{} HelloTriangle::~HelloTriangle() { diff --git a/samples/api/hello_triangle/hello_triangle.h b/samples/api/hello_triangle/hello_triangle.h index f8d4e2c8c2..8cbb4ca0d9 100644 --- a/samples/api/hello_triangle/hello_triangle.h +++ b/samples/api/hello_triangle/hello_triangle.h @@ -141,8 +141,7 @@ class HelloTriangle : public vkb::Application virtual bool resize(const uint32_t width, const uint32_t height) override; - bool validate_extensions(const std::vector &required, - const std::vector &available); + bool validate_extensions(const std::vector &required, const std::vector &available); void init_instance(); diff --git a/samples/api/hello_triangle_1_3/hello_triangle_1_3.cpp b/samples/api/hello_triangle_1_3/hello_triangle_1_3.cpp index 1ba709e06a..efb32039e6 100644 --- a/samples/api/hello_triangle_1_3/hello_triangle_1_3.cpp +++ b/samples/api/hello_triangle_1_3/hello_triangle_1_3.cpp @@ -61,8 +61,7 @@ static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(VkDebugUtilsMessageSeverity * @return true if all required extensions are available * @return false otherwise */ -bool HelloTriangleV13::validate_extensions(const std::vector &required, - const std::vector &available) +bool HelloTriangleV13::validate_extensions(const std::vector &required, const std::vector &available) { bool all_found = true; @@ -132,8 +131,9 @@ void HelloTriangleV13::init_instance() #if (defined(VKB_ENABLE_PORTABILITY)) required_instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); bool portability_enumeration_available = false; - if (std::ranges::any_of(available_instance_extensions, - [](VkExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(available_instance_extensions, [](VkExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; + })) { required_instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); portability_enumeration_available = true; @@ -185,19 +185,17 @@ void HelloTriangleV13::init_instance() } #endif - VkApplicationInfo app{ - .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, - .pApplicationName = "Hello Triangle V1.3", - .pEngineName = "Vulkan Samples", - .apiVersion = VK_API_VERSION_1_3}; + VkApplicationInfo app{.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .pApplicationName = "Hello Triangle V1.3", + .pEngineName = "Vulkan Samples", + .apiVersion = VK_API_VERSION_1_3}; - VkInstanceCreateInfo instance_info{ - .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, - .pApplicationInfo = &app, - .enabledLayerCount = vkb::to_u32(requested_instance_layers.size()), - .ppEnabledLayerNames = requested_instance_layers.data(), - .enabledExtensionCount = vkb::to_u32(required_instance_extensions.size()), - .ppEnabledExtensionNames = required_instance_extensions.data()}; + VkInstanceCreateInfo instance_info{.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pApplicationInfo = &app, + .enabledLayerCount = vkb::to_u32(requested_instance_layers.size()), + .ppEnabledLayerNames = requested_instance_layers.data(), + .enabledExtensionCount = vkb::to_u32(required_instance_extensions.size()), + .ppEnabledExtensionNames = required_instance_extensions.data()}; #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) VkDebugUtilsMessengerCreateInfoEXT debug_messenger_create_info = {VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; @@ -310,8 +308,9 @@ void HelloTriangleV13::init_device() #if (defined(VKB_ENABLE_PORTABILITY)) // VK_KHR_portability_subset must be enabled if present in the implementation (e.g on macOS/iOS using MoltenVK with beta extensions enabled) - if (std::ranges::any_of(device_extensions, - [](VkExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(device_extensions, [](VkExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME) == 0; + })) { required_device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME); } @@ -320,7 +319,8 @@ void HelloTriangleV13::init_device() // Query for Vulkan 1.3 features VkPhysicalDeviceFeatures2 query_device_features2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; VkPhysicalDeviceVulkan13Features query_vulkan13_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - VkPhysicalDeviceExtendedDynamicStateFeaturesEXT query_extended_dynamic_state_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT}; + VkPhysicalDeviceExtendedDynamicStateFeaturesEXT query_extended_dynamic_state_features{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT}; query_device_features2.pNext = &query_vulkan13_features; query_vulkan13_features.pNext = &query_extended_dynamic_state_features; @@ -345,8 +345,7 @@ void HelloTriangleV13::init_device() // Enable only specific Vulkan 1.3 features VkPhysicalDeviceExtendedDynamicStateFeaturesEXT enable_extended_dynamic_state_features = { - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT, - .extendedDynamicState = VK_TRUE}; + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT, .extendedDynamicState = VK_TRUE}; VkPhysicalDeviceVulkan13Features enable_vulkan13_features = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, @@ -355,27 +354,23 @@ void HelloTriangleV13::init_device() .dynamicRendering = VK_TRUE, }; - VkPhysicalDeviceFeatures2 enable_device_features2{ - .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, - .pNext = &enable_vulkan13_features}; + VkPhysicalDeviceFeatures2 enable_device_features2{.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, .pNext = &enable_vulkan13_features}; // Create the logical device float queue_priority = 0.5f; // Create one queue - VkDeviceQueueCreateInfo queue_info{ - .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, - .queueFamilyIndex = static_cast(context.graphics_queue_index), - .queueCount = 1, - .pQueuePriorities = &queue_priority}; - - VkDeviceCreateInfo device_info{ - .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, - .pNext = &enable_device_features2, - .queueCreateInfoCount = 1, - .pQueueCreateInfos = &queue_info, - .enabledExtensionCount = vkb::to_u32(required_device_extensions.size()), - .ppEnabledExtensionNames = required_device_extensions.data()}; + VkDeviceQueueCreateInfo queue_info{.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .queueFamilyIndex = static_cast(context.graphics_queue_index), + .queueCount = 1, + .pQueuePriorities = &queue_priority}; + + VkDeviceCreateInfo device_info{.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = &enable_device_features2, + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &queue_info, + .enabledExtensionCount = vkb::to_u32(required_device_extensions.size()), + .ppEnabledExtensionNames = required_device_extensions.data()}; VK_CHECK(vkCreateDevice(context.gpu, &device_info, nullptr, &context.device)); volkLoadDevice(context.device); @@ -393,12 +388,11 @@ void HelloTriangleV13::init_vertex_buffer() VkDeviceSize buffer_size = sizeof(vertices[0]) * vertices.size(); // Create the vertex buffer - VkBufferCreateInfo vertext_buffer_info{ - .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, - .flags = 0, - .size = buffer_size, - .usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, - .sharingMode = VK_SHARING_MODE_EXCLUSIVE}; + VkBufferCreateInfo vertext_buffer_info{.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .flags = 0, + .size = buffer_size, + .usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE}; VK_CHECK(vkCreateBuffer(context.device, &vertext_buffer_info, nullptr, &context.vertex_buffer)); @@ -407,11 +401,10 @@ void HelloTriangleV13::init_vertex_buffer() vkGetBufferMemoryRequirements(context.device, context.vertex_buffer, &memory_requirements); // Allocate memory for the buffer - VkMemoryAllocateInfo alloc_info{ - .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - .allocationSize = memory_requirements.size, - .memoryTypeIndex = find_memory_type(context.gpu, memory_requirements.memoryTypeBits, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)}; + VkMemoryAllocateInfo alloc_info{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = memory_requirements.size, + .memoryTypeIndex = find_memory_type(context.gpu, memory_requirements.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)}; VK_CHECK(vkAllocateMemory(context.device, &alloc_info, nullptr, &context.vertex_buffer_memory)); @@ -472,22 +465,18 @@ uint32_t HelloTriangleV13::find_memory_type(VkPhysicalDevice physical_device, ui */ void HelloTriangleV13::init_per_frame(PerFrame &per_frame) { - VkFenceCreateInfo info{ - .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, - .flags = VK_FENCE_CREATE_SIGNALED_BIT}; + VkFenceCreateInfo info{.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .flags = VK_FENCE_CREATE_SIGNALED_BIT}; VK_CHECK(vkCreateFence(context.device, &info, nullptr, &per_frame.queue_submit_fence)); - VkCommandPoolCreateInfo cmd_pool_info{ - .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, - .flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, - .queueFamilyIndex = static_cast(context.graphics_queue_index)}; + VkCommandPoolCreateInfo cmd_pool_info{.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, + .flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, + .queueFamilyIndex = static_cast(context.graphics_queue_index)}; VK_CHECK(vkCreateCommandPool(context.device, &cmd_pool_info, nullptr, &per_frame.primary_command_pool)); - VkCommandBufferAllocateInfo cmd_buf_info{ - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, - .commandPool = per_frame.primary_command_pool, - .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, - .commandBufferCount = 1}; + VkCommandBufferAllocateInfo cmd_buf_info{.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + .commandPool = per_frame.primary_command_pool, + .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, + .commandBufferCount = 1}; VK_CHECK(vkAllocateCommandBuffers(context.device, &cmd_buf_info, &per_frame.primary_command_buffer)); } @@ -687,9 +676,7 @@ VkShaderModule HelloTriangleV13::load_shader_module(const std::string &path, VkS auto spirv = vkb::fs::read_shader_binary_u32(path); VkShaderModuleCreateInfo module_info{ - .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, - .codeSize = spirv.size() * sizeof(uint32_t), - .pCode = spirv.data()}; + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = spirv.size() * sizeof(uint32_t), .pCode = spirv.data()}; VkShaderModule shader_module; VK_CHECK(vkCreateShaderModule(context.device, &module_info, nullptr, &shader_module)); @@ -708,10 +695,7 @@ void HelloTriangleV13::init_pipeline() VK_CHECK(vkCreatePipelineLayout(context.device, &layout_info, nullptr, &context.pipeline_layout)); // Define the vertex input binding description - VkVertexInputBindingDescription binding_description{ - .binding = 0, - .stride = sizeof(Vertex), - .inputRate = VK_VERTEX_INPUT_RATE_VERTEX}; + VkVertexInputBindingDescription binding_description{.binding = 0, .stride = sizeof(Vertex), .inputRate = VK_VERTEX_INPUT_RATE_VERTEX}; // Define the vertex input attribute descriptions std::array attribute_descriptions = {{ @@ -727,57 +711,43 @@ void HelloTriangleV13::init_pipeline() .pVertexAttributeDescriptions = attribute_descriptions.data()}; // Specify we will use triangle lists to draw geometry. - VkPipelineInputAssemblyStateCreateInfo input_assembly{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, - .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - .primitiveRestartEnable = VK_FALSE}; + VkPipelineInputAssemblyStateCreateInfo input_assembly{.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, + .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, + .primitiveRestartEnable = VK_FALSE}; // Specify rasterization state. - VkPipelineRasterizationStateCreateInfo raster{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, - .depthClampEnable = VK_FALSE, - .rasterizerDiscardEnable = VK_FALSE, - .polygonMode = VK_POLYGON_MODE_FILL, - .depthBiasEnable = VK_FALSE, - .lineWidth = 1.0f}; + VkPipelineRasterizationStateCreateInfo raster{.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, + .depthClampEnable = VK_FALSE, + .rasterizerDiscardEnable = VK_FALSE, + .polygonMode = VK_POLYGON_MODE_FILL, + .depthBiasEnable = VK_FALSE, + .lineWidth = 1.0f}; // Specify that these states will be dynamic, i.e. not part of pipeline state object. - std::vector dynamic_states = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_CULL_MODE, - VK_DYNAMIC_STATE_FRONT_FACE, - VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY}; + std::vector dynamic_states = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_CULL_MODE, VK_DYNAMIC_STATE_FRONT_FACE, + VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY}; // Our attachment will write to all color channels, but no blending is enabled. - VkPipelineColorBlendAttachmentState blend_attachment{ - .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT}; + VkPipelineColorBlendAttachmentState blend_attachment{.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT}; VkPipelineColorBlendStateCreateInfo blend{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, - .attachmentCount = 1, - .pAttachments = &blend_attachment}; + .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .attachmentCount = 1, .pAttachments = &blend_attachment}; // We will have one viewport and scissor box. - VkPipelineViewportStateCreateInfo viewport{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, - .viewportCount = 1, - .scissorCount = 1}; + VkPipelineViewportStateCreateInfo viewport{.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .viewportCount = 1, .scissorCount = 1}; // Disable all depth testing. - VkPipelineDepthStencilStateCreateInfo depth_stencil{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, - .depthCompareOp = VK_COMPARE_OP_ALWAYS}; + VkPipelineDepthStencilStateCreateInfo depth_stencil{.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, + .depthCompareOp = VK_COMPARE_OP_ALWAYS}; // No multisampling. - VkPipelineMultisampleStateCreateInfo multisample{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, - .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}; + VkPipelineMultisampleStateCreateInfo multisample{.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, + .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}; - VkPipelineDynamicStateCreateInfo dynamic_state_info{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, - .dynamicStateCount = static_cast(dynamic_states.size()), - .pDynamicStates = dynamic_states.data()}; + VkPipelineDynamicStateCreateInfo dynamic_state_info{.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, + .dynamicStateCount = static_cast(dynamic_states.size()), + .pDynamicStates = dynamic_states.data()}; // Load our SPIR-V shaders. @@ -801,18 +771,15 @@ void HelloTriangleV13::init_pipeline() .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = load_shader_module("hello_triangle_1_3/" + shader_folder + "/triangle.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), .pName = "main"}, // Vertex shader stage - { - .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .stage = VK_SHADER_STAGE_FRAGMENT_BIT, - .module = load_shader_module("hello_triangle_1_3/" + shader_folder + "/triangle.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT), - .pName = "main"} // Fragment shader stage + {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .module = load_shader_module("hello_triangle_1_3/" + shader_folder + "/triangle.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT), + .pName = "main"} // Fragment shader stage }}; // Pipeline rendering info (for dynamic rendering). VkPipelineRenderingCreateInfo pipeline_rendering_info{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO, - .colorAttachmentCount = 1, - .pColorAttachmentFormats = &context.swapchain_dimensions.format}; + .sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO, .colorAttachmentCount = 1, .pColorAttachmentFormats = &context.swapchain_dimensions.format}; // Create the graphics pipeline. VkGraphicsPipelineCreateInfo pipe{ @@ -909,48 +876,41 @@ void HelloTriangleV13::render_triangle(uint32_t swapchain_index) VkCommandBuffer cmd = context.per_frame[swapchain_index].primary_command_buffer; // We will only submit this once before it's recycled. - VkCommandBufferBeginInfo begin_info{ - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, - .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; + VkCommandBufferBeginInfo begin_info{.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; // Begin command recording VK_CHECK(vkBeginCommandBuffer(cmd, &begin_info)); // Before starting rendering, transition the swapchain image to COLOR_ATTACHMENT_OPTIMAL - transition_image_layout( - cmd, - context.swapchain_images[swapchain_index], - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - 0, // srcAccessMask (no need to wait for previous operations) - VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, // dstAccessMask - VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT, // srcStage - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT // dstStage + transition_image_layout(cmd, context.swapchain_images[swapchain_index], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + 0, // srcAccessMask (no need to wait for previous operations) + VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, // dstAccessMask + VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT, // srcStage + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT // dstStage ); // Set clear color values. - VkClearValue clear_value{ - .color = {{0.01f, 0.01f, 0.033f, 1.0f}}}; + VkClearValue clear_value{.color = {{0.01f, 0.01f, 0.033f, 1.0f}}}; // Set up the rendering attachment info - VkRenderingAttachmentInfo color_attachment{ - .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, - .imageView = context.swapchain_image_views[swapchain_index], - .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .clearValue = clear_value}; + VkRenderingAttachmentInfo color_attachment{.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, + .imageView = context.swapchain_image_views[swapchain_index], + .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .clearValue = clear_value}; // Begin rendering - VkRenderingInfo rendering_info{ - .sType = VK_STRUCTURE_TYPE_RENDERING_INFO_KHR, - .renderArea = { // Initialize the nested `VkRect2D` structure - .offset = {0, 0}, // Initialize the `VkOffset2D` inside `renderArea` - .extent = { // Initialize the `VkExtent2D` inside `renderArea` - .width = context.swapchain_dimensions.width, - .height = context.swapchain_dimensions.height}}, - .layerCount = 1, - .colorAttachmentCount = 1, - .pColorAttachments = &color_attachment}; + VkRenderingInfo rendering_info{.sType = VK_STRUCTURE_TYPE_RENDERING_INFO_KHR, + .renderArea = + { // Initialize the nested `VkRect2D` structure + .offset = {0, 0}, // Initialize the `VkOffset2D` inside `renderArea` + .extent = + {// Initialize the `VkExtent2D` inside `renderArea` + .width = context.swapchain_dimensions.width, + .height = context.swapchain_dimensions.height}}, + .layerCount = 1, + .colorAttachmentCount = 1, + .pColorAttachments = &color_attachment}; vkCmdBeginRendering(cmd, &rendering_info); @@ -960,19 +920,15 @@ void HelloTriangleV13::render_triangle(uint32_t swapchain_index) // Set dynamic states // Set viewport dynamically - VkViewport vp{ - .width = static_cast(context.swapchain_dimensions.width), - .height = static_cast(context.swapchain_dimensions.height), - .minDepth = 0.0f, - .maxDepth = 1.0f}; + VkViewport vp{.width = static_cast(context.swapchain_dimensions.width), + .height = static_cast(context.swapchain_dimensions.height), + .minDepth = 0.0f, + .maxDepth = 1.0f}; vkCmdSetViewport(cmd, 0, 1, &vp); // Set scissor dynamically - VkRect2D scissor{ - .extent = { - .width = context.swapchain_dimensions.width, - .height = context.swapchain_dimensions.height}}; + VkRect2D scissor{.extent = {.width = context.swapchain_dimensions.width, .height = context.swapchain_dimensions.height}}; vkCmdSetScissor(cmd, 0, 1, &scissor); @@ -1003,15 +959,11 @@ void HelloTriangleV13::render_triangle(uint32_t swapchain_index) vkCmdEndRendering(cmd); // After rendering , transition the swapchain image to PRESENT_SRC - transition_image_layout( - cmd, - context.swapchain_images[swapchain_index], - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, // srcAccessMask - 0, // dstAccessMask - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, // srcStage - VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT // dstStage + transition_image_layout(cmd, context.swapchain_images[swapchain_index], VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, // srcAccessMask + 0, // dstAccessMask + VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, // srcStage + VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT // dstStage ); // Complete the command buffer. @@ -1021,8 +973,7 @@ void HelloTriangleV13::render_triangle(uint32_t swapchain_index) if (context.per_frame[swapchain_index].swapchain_release_semaphore == VK_NULL_HANDLE) { VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; - VK_CHECK(vkCreateSemaphore(context.device, &semaphore_info, nullptr, - &context.per_frame[swapchain_index].swapchain_release_semaphore)); + VK_CHECK(vkCreateSemaphore(context.device, &semaphore_info, nullptr, &context.per_frame[swapchain_index].swapchain_release_semaphore)); } // Using TOP_OF_PIPE here to ensure that the command buffer does not begin executing any pipeline stages @@ -1031,15 +982,14 @@ void HelloTriangleV13::render_triangle(uint32_t swapchain_index) // before any rendering commands run. VkPipelineStageFlags wait_stage{VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT}; - VkSubmitInfo info{ - .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, - .waitSemaphoreCount = 1, - .pWaitSemaphores = &context.per_frame[swapchain_index].swapchain_acquire_semaphore, - .pWaitDstStageMask = &wait_stage, - .commandBufferCount = 1, - .pCommandBuffers = &cmd, - .signalSemaphoreCount = 1, - .pSignalSemaphores = &context.per_frame[swapchain_index].swapchain_release_semaphore}; + VkSubmitInfo info{.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .waitSemaphoreCount = 1, + .pWaitSemaphores = &context.per_frame[swapchain_index].swapchain_acquire_semaphore, + .pWaitDstStageMask = &wait_stage, + .commandBufferCount = 1, + .pCommandBuffers = &cmd, + .signalSemaphoreCount = 1, + .pSignalSemaphores = &context.per_frame[swapchain_index].swapchain_release_semaphore}; // Submit command buffer to graphics queue VK_CHECK(vkQueueSubmit(context.queue, 1, &info, context.per_frame[swapchain_index].queue_submit_fence)); @@ -1076,45 +1026,43 @@ VkResult HelloTriangleV13::present_image(uint32_t index) * @param srcStage The pipeline stage that must happen before the transition. * @param dstStage The pipeline stage that must happen after the transition. */ -void HelloTriangleV13::transition_image_layout( - VkCommandBuffer cmd, - VkImage image, - VkImageLayout oldLayout, - VkImageLayout newLayout, - VkAccessFlags2 srcAccessMask, - VkAccessFlags2 dstAccessMask, - VkPipelineStageFlags2 srcStage, - VkPipelineStageFlags2 dstStage) +void HelloTriangleV13::transition_image_layout(VkCommandBuffer cmd, + VkImage image, + VkImageLayout oldLayout, + VkImageLayout newLayout, + VkAccessFlags2 srcAccessMask, + VkAccessFlags2 dstAccessMask, + VkPipelineStageFlags2 srcStage, + VkPipelineStageFlags2 dstStage) { // Initialize the VkImageMemoryBarrier2 structure - VkImageMemoryBarrier2 image_barrier{ - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, - - // Specify the pipeline stages and access masks for the barrier - .srcStageMask = srcStage, // Source pipeline stage mask - .srcAccessMask = srcAccessMask, // Source access mask - .dstStageMask = dstStage, // Destination pipeline stage mask - .dstAccessMask = dstAccessMask, // Destination access mask - - // Specify the old and new layouts of the image - .oldLayout = oldLayout, // Current layout of the image - .newLayout = newLayout, // Target layout of the image - - // We are not changing the ownership between queues - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - - // Specify the image to be affected by this barrier - .image = image, - - // Define the subresource range (which parts of the image are affected) - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, // Affects the color aspect of the image - .baseMipLevel = 0, // Start at mip level 0 - .levelCount = 1, // Number of mip levels affected - .baseArrayLayer = 0, // Start at array layer 0 - .layerCount = 1 // Number of array layers affected - }}; + VkImageMemoryBarrier2 image_barrier{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, + + // Specify the pipeline stages and access masks for the barrier + .srcStageMask = srcStage, // Source pipeline stage mask + .srcAccessMask = srcAccessMask, // Source access mask + .dstStageMask = dstStage, // Destination pipeline stage mask + .dstAccessMask = dstAccessMask, // Destination access mask + + // Specify the old and new layouts of the image + .oldLayout = oldLayout, // Current layout of the image + .newLayout = newLayout, // Target layout of the image + + // We are not changing the ownership between queues + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + + // Specify the image to be affected by this barrier + .image = image, + + // Define the subresource range (which parts of the image are affected) + .subresourceRange = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, // Affects the color aspect of the image + .baseMipLevel = 0, // Start at mip level 0 + .levelCount = 1, // Number of mip levels affected + .baseArrayLayer = 0, // Start at array layer 0 + .layerCount = 1 // Number of array layers affected + }}; // Initialize the VkDependencyInfo structure VkDependencyInfo dependency_info{ diff --git a/samples/api/hello_triangle_1_3/hello_triangle_1_3.h b/samples/api/hello_triangle_1_3/hello_triangle_1_3.h index 9e8ba1f515..028a53f195 100644 --- a/samples/api/hello_triangle_1_3/hello_triangle_1_3.h +++ b/samples/api/hello_triangle_1_3/hello_triangle_1_3.h @@ -139,8 +139,7 @@ class HelloTriangleV13 : public vkb::Application virtual bool resize(const uint32_t width, const uint32_t height) override; - bool validate_extensions(const std::vector &required, - const std::vector &available); + bool validate_extensions(const std::vector &required, const std::vector &available); void init_instance(); @@ -164,7 +163,14 @@ class HelloTriangleV13 : public vkb::Application VkResult present_image(uint32_t index); - void transition_image_layout(VkCommandBuffer cmd, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, VkAccessFlags2 srcAccessMask, VkAccessFlags2 dstAccessMask, VkPipelineStageFlags2 srcStage, VkPipelineStageFlags2 dstStage); + void transition_image_layout(VkCommandBuffer cmd, + VkImage image, + VkImageLayout oldLayout, + VkImageLayout newLayout, + VkAccessFlags2 srcAccessMask, + VkAccessFlags2 dstAccessMask, + VkPipelineStageFlags2 srcStage, + VkPipelineStageFlags2 dstStage); uint32_t find_memory_type(VkPhysicalDevice physical_device, uint32_t type_filter, VkMemoryPropertyFlags properties); diff --git a/samples/api/hpp_compute_nbody/hpp_compute_nbody.cpp b/samples/api/hpp_compute_nbody/hpp_compute_nbody.cpp index 974ce38a7c..ef5068b45a 100644 --- a/samples/api/hpp_compute_nbody/hpp_compute_nbody.cpp +++ b/samples/api/hpp_compute_nbody/hpp_compute_nbody.cpp @@ -78,8 +78,7 @@ void HPPComputeNBody::request_gpu_features(vkb::core::PhysicalDeviceCpp &gpu) void HPPComputeNBody::build_command_buffers() { - std::array clear_values = {{vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 1.0f}})), - vk::ClearDepthStencilValue{0.0f, 0}}}; + std::array clear_values = {{vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 1.0f}})), vk::ClearDepthStencilValue{0.0f, 0}}}; vk::RenderPassBeginInfo render_pass_begin_info{.renderPass = render_pass, .renderArea = {{0, 0}, extent}, @@ -103,8 +102,8 @@ void HPPComputeNBody::build_command_buffers() .buffer = compute.storage_buffer->get_handle(), .size = compute.storage_buffer->get_size()}; - command_buffer.pipelineBarrier( - vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eVertexInput, {}, nullptr, buffer_barrier, nullptr); + command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eVertexInput, {}, nullptr, buffer_barrier, + nullptr); } // Draw the particle system using the update vertex buffer @@ -127,8 +126,8 @@ void HPPComputeNBody::build_command_buffers() .buffer = compute.storage_buffer->get_handle(), .size = compute.storage_buffer->get_size()}; - command_buffer.pipelineBarrier( - vk::PipelineStageFlagBits::eVertexInput, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, buffer_barrier, nullptr); + command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eVertexInput, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, buffer_barrier, + nullptr); } command_buffer.end(); @@ -168,8 +167,8 @@ void HPPComputeNBody::build_compute_command_buffer() .buffer = compute.storage_buffer->get_handle(), .size = compute.storage_buffer->get_size()}; - compute.command_buffer.pipelineBarrier( - vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, buffer_barrier, nullptr); + compute.command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, buffer_barrier, + nullptr); } // First pass: Calculate particle movement @@ -186,8 +185,8 @@ void HPPComputeNBody::build_compute_command_buffer() .buffer = compute.storage_buffer->get_handle(), .size = compute.storage_buffer->get_size()}; - compute.command_buffer.pipelineBarrier( - vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, memory_barrier, nullptr); + compute.command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, memory_barrier, + nullptr); // Second pass: Integrate particles // ------------------------------------------------------------------------------------------------------- @@ -203,8 +202,8 @@ void HPPComputeNBody::build_compute_command_buffer() .buffer = compute.storage_buffer->get_handle(), .size = compute.storage_buffer->get_size()}; - compute.command_buffer.pipelineBarrier( - vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, buffer_barrier, nullptr); + compute.command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, buffer_barrier, + nullptr); } compute.command_buffer.end(); @@ -219,16 +218,16 @@ void HPPComputeNBody::build_compute_transfer_command_buffer(vk::CommandBuffer co .dstQueueFamilyIndex = compute.queue_family_index, .buffer = compute.storage_buffer->get_handle(), .size = compute.storage_buffer->get_size()}; - command_buffer.pipelineBarrier( - vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, acquire_buffer_barrier, nullptr); + command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, acquire_buffer_barrier, + nullptr); vk::BufferMemoryBarrier release_buffer_barrier{.srcAccessMask = vk::AccessFlagBits::eShaderWrite, .srcQueueFamilyIndex = compute.queue_family_index, .dstQueueFamilyIndex = graphics.queue_family_index, .buffer = compute.storage_buffer->get_handle(), .size = compute.storage_buffer->get_size()}; - command_buffer.pipelineBarrier( - vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, release_buffer_barrier, nullptr); + command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, release_buffer_barrier, + nullptr); // Copied from Device::flush_command_buffer, which we can't use because it would be // working with the wrong command pool @@ -248,7 +247,8 @@ void HPPComputeNBody::build_copy_command_buffer(vk::CommandBuffer command_buffer .buffer = compute.storage_buffer->get_handle(), .size = compute.storage_buffer->get_size()}; - command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eVertexInput, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, buffer_barrier, nullptr); + command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eVertexInput, vk::PipelineStageFlagBits::eComputeShader, {}, nullptr, buffer_barrier, + nullptr); } command_buffer.end(); } @@ -275,9 +275,8 @@ vk::Pipeline HPPComputeNBody::create_compute_pipeline(vk::PipelineShaderStageCre vk::DescriptorPool HPPComputeNBody::create_descriptor_pool() { - std::array pool_sizes = {{{vk::DescriptorType::eUniformBuffer, 2}, - {vk::DescriptorType::eStorageBuffer, 1}, - {vk::DescriptorType::eCombinedImageSampler, 2}}}; + std::array pool_sizes = { + {{vk::DescriptorType::eUniformBuffer, 2}, {vk::DescriptorType::eStorageBuffer, 1}, {vk::DescriptorType::eCombinedImageSampler, 2}}}; return get_device().get_handle().createDescriptorPool( {.maxSets = 2, .poolSizeCount = static_cast(pool_sizes.size()), .pPoolSizes = pool_sizes.data()}); @@ -325,19 +324,9 @@ vk::Pipeline HPPComputeNBody::create_graphics_pipeline() depth_stencil_state.depthCompareOp = vk::CompareOp::eAlways; depth_stencil_state.back.compareOp = vk::CompareOp::eAlways; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::ePointList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - graphics.pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline( + get_device().get_handle(), pipeline_cache, shader_stages, vertex_input_state, vk::PrimitiveTopology::ePointList, 0, vk::PolygonMode::eFill, + vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, graphics.pipeline_layout, render_pass); } void HPPComputeNBody::draw() @@ -441,8 +430,7 @@ void HPPComputeNBody::prepare_compute() MovementSpecializationData movement_specialization_data{compute.work_group_size, compute.shared_data_size, 0.002f, 0.75f, 0.05f}; vk::SpecializationInfo specialization_info{static_cast(movement_specialization_map_entries.size()), - movement_specialization_map_entries.data(), - sizeof(movement_specialization_data), + movement_specialization_map_entries.data(), sizeof(movement_specialization_data), &movement_specialization_data}; stage.pSpecializationInfo = &specialization_info; @@ -507,12 +495,8 @@ void HPPComputeNBody::prepare_compute_storage_buffers() }; #else std::vector attractors = { - glm::vec3(5.0f, 0.0f, 0.0f), - glm::vec3(-5.0f, 0.0f, 0.0f), - glm::vec3(0.0f, 0.0f, 5.0f), - glm::vec3(0.0f, 0.0f, -5.0f), - glm::vec3(0.0f, 4.0f, 0.0f), - glm::vec3(0.0f, -8.0f, 0.0f), + glm::vec3(5.0f, 0.0f, 0.0f), glm::vec3(-5.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 5.0f), + glm::vec3(0.0f, 0.0f, -5.0f), glm::vec3(0.0f, 4.0f, 0.0f), glm::vec3(0.0f, -8.0f, 0.0f), }; #endif @@ -539,8 +523,7 @@ void HPPComputeNBody::prepare_compute_storage_buffers() else { // Position - glm::vec3 position(attractors[i] + - glm::vec3(rnd_distribution(rnd_engine), rnd_distribution(rnd_engine), rnd_distribution(rnd_engine)) * 0.75f); + glm::vec3 position(attractors[i] + glm::vec3(rnd_distribution(rnd_engine), rnd_distribution(rnd_engine), rnd_distribution(rnd_engine)) * 0.75f); float len = glm::length(glm::normalize(position - attractors[i])); position.y *= 2.0f - (len * len); @@ -565,11 +548,9 @@ void HPPComputeNBody::prepare_compute_storage_buffers() // SSBO won't be changed on the host after upload so copy to device local memory vkb::core::BufferCpp staging_buffer = vkb::core::BufferCpp::create_staging_buffer(get_device(), particle_buffer); - compute.storage_buffer = std::make_unique(get_device(), - storage_buffer_size, - vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eStorageBuffer | - vk::BufferUsageFlagBits::eTransferDst, - VMA_MEMORY_USAGE_GPU_ONLY); + compute.storage_buffer = std::make_unique( + get_device(), storage_buffer_size, + vk::BufferUsageFlagBits::eVertexBuffer | vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferDst, VMA_MEMORY_USAGE_GPU_ONLY); // Copy from staging buffer to storage buffer vk::Device device = get_device().get_handle(); @@ -635,14 +616,12 @@ void HPPComputeNBody::update_graphics_descriptor_set() { vk::DescriptorBufferInfo buffer_descriptor{graphics.uniform_buffer->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo particle_image_descriptor{textures.particle.sampler, - textures.particle.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - textures.particle.image->get_vk_image_view().get_format())}; - vk::DescriptorImageInfo gradient_image_descriptor{textures.gradient.sampler, - textures.gradient.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - textures.gradient.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo particle_image_descriptor{ + textures.particle.sampler, textures.particle.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, textures.particle.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo gradient_image_descriptor{ + textures.gradient.sampler, textures.gradient.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, textures.gradient.image->get_vk_image_view().get_format())}; std::array write_descriptor_sets = {{{.dstSet = graphics.descriptor_set, .dstBinding = 0, diff --git a/samples/api/hpp_compute_nbody/hpp_compute_nbody.h b/samples/api/hpp_compute_nbody/hpp_compute_nbody.h index 93fd610dc7..0cc25dde96 100644 --- a/samples/api/hpp_compute_nbody/hpp_compute_nbody.h +++ b/samples/api/hpp_compute_nbody/hpp_compute_nbody.h @@ -46,14 +46,14 @@ class HPPComputeNBody : public HPPApiVulkanSample struct Compute { - vk::CommandBuffer command_buffer; // Command buffer storing the dispatch commands and barriers - vk::CommandPool command_pool; // Use a separate command pool (queue family may differ from the one used for graphics) - vk::DescriptorSet descriptor_set; // Compute shader bindings + vk::CommandBuffer command_buffer; // Command buffer storing the dispatch commands and barriers + vk::CommandPool command_pool; // Use a separate command pool (queue family may differ from the one used for graphics) + vk::DescriptorSet descriptor_set; // Compute shader bindings vk::DescriptorSetLayout descriptor_set_layout; // Compute shader binding layout vk::Pipeline pipeline_calculate; // Compute pipeline for N-Body velocity calculation (1st pass) vk::Pipeline pipeline_integrate; // Compute pipeline for euler integration (2nd pass) vk::PipelineLayout pipeline_layout; // Layout of the compute pipeline - vk::Queue queue; // Separate queue for compute commands (queue family may differ from the one used for graphics) + vk::Queue queue; // Separate queue for compute commands (queue family may differ from the one used for graphics) uint32_t queue_family_index = ~0; vk::Fence fence; // Fence to wait for compute dispatch completion before UBO update vk::Semaphore semaphore; // Execution dependency between compute & graphic submission diff --git a/samples/api/hpp_dynamic_uniform_buffers/hpp_dynamic_uniform_buffers.cpp b/samples/api/hpp_dynamic_uniform_buffers/hpp_dynamic_uniform_buffers.cpp index 6f4b7e32f5..d782250812 100644 --- a/samples/api/hpp_dynamic_uniform_buffers/hpp_dynamic_uniform_buffers.cpp +++ b/samples/api/hpp_dynamic_uniform_buffers/hpp_dynamic_uniform_buffers.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -171,9 +171,8 @@ void HPPDynamicUniformBuffers::render(float delta_time) vk::DescriptorPool HPPDynamicUniformBuffers::create_descriptor_pool() { // Example uses one ubo, on dynamic ubo, and one combined image sampler - std::array pool_sizes = {{{vk::DescriptorType::eUniformBuffer, 1}, - {vk::DescriptorType::eUniformBufferDynamic, 1}, - {vk::DescriptorType::eCombinedImageSampler, 1}}}; + std::array pool_sizes = { + {{vk::DescriptorType::eUniformBuffer, 1}, {vk::DescriptorType::eUniformBufferDynamic, 1}, {vk::DescriptorType::eCombinedImageSampler, 1}}}; return get_device().get_handle().createDescriptorPool( {.maxSets = 2, .poolSizeCount = static_cast(pool_sizes.size()), .pPoolSizes = pool_sizes.data()}); } @@ -189,8 +188,9 @@ vk::DescriptorSetLayout HPPDynamicUniformBuffers::create_descriptor_set_layout() vk::Pipeline HPPDynamicUniformBuffers::create_pipeline() { // Load shaders - std::vector shader_stages = {load_shader("dynamic_uniform_buffers", "base.vert.spv", vk::ShaderStageFlagBits::eVertex), - load_shader("dynamic_uniform_buffers", "base.frag.spv", vk::ShaderStageFlagBits::eFragment)}; + std::vector shader_stages = { + load_shader("dynamic_uniform_buffers", "base.vert.spv", vk::ShaderStageFlagBits::eVertex), + load_shader("dynamic_uniform_buffers", "base.frag.spv", vk::ShaderStageFlagBits::eFragment)}; // Vertex bindings and attributes vk::VertexInputBindingDescription vertex_input_binding{0, sizeof(Vertex), vk::VertexInputRate::eVertex}; @@ -212,19 +212,9 @@ vk::Pipeline HPPDynamicUniformBuffers::create_pipeline() depth_stencil_state.depthCompareOp = vk::CompareOp::eGreater; depth_stencil_state.back.compareOp = vk::CompareOp::eGreater; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, vertex_input_state, + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, + vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, pipeline_layout, render_pass); } void HPPDynamicUniformBuffers::draw() @@ -242,14 +232,9 @@ void HPPDynamicUniformBuffers::generate_cube() { // Setup vertices indices for a colored cube std::vector vertices = { - {{-1.0f, -1.0f, 1.0f}, {1.0f, 0.0f, 0.0f}}, - {{1.0f, -1.0f, 1.0f}, {0.0f, 1.0f, 0.0f}}, - {{1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 0.0f}}, - {{-1.0f, -1.0f, -1.0f}, {1.0f, 0.0f, 0.0f}}, - {{1.0f, -1.0f, -1.0f}, {0.0f, 1.0f, 0.0f}}, - {{1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 0.0f}}, + {{-1.0f, -1.0f, 1.0f}, {1.0f, 0.0f, 0.0f}}, {{1.0f, -1.0f, 1.0f}, {0.0f, 1.0f, 0.0f}}, {{1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 0.0f}}, {{-1.0f, -1.0f, -1.0f}, {1.0f, 0.0f, 0.0f}}, {{1.0f, -1.0f, -1.0f}, {0.0f, 1.0f, 0.0f}}, + {{1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 1.0f}}, {{-1.0f, 1.0f, -1.0f}, {0.0f, 0.0f, 0.0f}}, }; // clang-format off @@ -380,8 +365,7 @@ void HPPDynamicUniformBuffers::update_dynamic_uniform_buffer(float delta_time, b rotations[index] += animation_timer * rotation_speeds[index]; // Update matrices - glm::vec3 pos(-((fdim * offset.x) / 2.0f) + offset.x / 2.0f + fx * offset.x, - -((fdim * offset.y) / 2.0f) + offset.y / 2.0f + fy * offset.y, + glm::vec3 pos(-((fdim * offset.x) / 2.0f) + offset.x / 2.0f + fx * offset.x, -((fdim * offset.y) / 2.0f) + offset.y / 2.0f + fy * offset.y, -((fdim * offset.z) / 2.0f) + offset.z / 2.0f + fz * offset.z); *model_mat = glm::translate(glm::mat4(1.0f), pos); *model_mat = glm::rotate(*model_mat, rotations[index].x, glm::vec3(1.0f, 1.0f, 0.0f)); diff --git a/samples/api/hpp_hdr/hpp_hdr.cpp b/samples/api/hpp_hdr/hpp_hdr.cpp index db32c836c7..6a71ac5782 100644 --- a/samples/api/hpp_hdr/hpp_hdr.cpp +++ b/samples/api/hpp_hdr/hpp_hdr.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -159,13 +159,13 @@ void HPPHDR::build_command_buffers() */ { // Final composition - std::array clear_values = {{vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 0.0f}})), - vk::ClearDepthStencilValue{0.0f, 0}}}; - vk::RenderPassBeginInfo render_pass_begin_info{.renderPass = render_pass, - .framebuffer = framebuffers[i], - .renderArea = {{0, 0}, extent}, - .clearValueCount = static_cast(clear_values.size()), - .pClearValues = clear_values.data()}; + std::array clear_values = { + {vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 0.0f}})), vk::ClearDepthStencilValue{0.0f, 0}}}; + vk::RenderPassBeginInfo render_pass_begin_info{.renderPass = render_pass, + .framebuffer = framebuffers[i], + .renderArea = {{0, 0}, extent}, + .clearValueCount = static_cast(clear_values.size()), + .pClearValues = clear_values.data()}; command_buffer.beginRenderPass(render_pass_begin_info, vk::SubpassContents::eInline); vk::Viewport viewport{0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}; @@ -236,9 +236,9 @@ vk::DeviceMemory HPPHDR::allocate_memory(vk::Image image) { vk::MemoryRequirements memory_requirements = get_device().get_handle().getImageMemoryRequirements(image); - vk::MemoryAllocateInfo memory_allocate_info{.allocationSize = memory_requirements.size, - .memoryTypeIndex = get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, - vk::MemoryPropertyFlagBits::eDeviceLocal)}; + vk::MemoryAllocateInfo memory_allocate_info{ + .allocationSize = memory_requirements.size, + .memoryTypeIndex = get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal)}; return get_device().get_handle().allocateMemory(memory_allocate_info); } @@ -289,18 +289,9 @@ vk::Pipeline HPPHDR::create_bloom_pipeline(uint32_t direction) depth_stencil_state.front = depth_stencil_state.back; // Empty vertex input state, full screen triangles are generated by the vertex shader - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - {}, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eFront, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - bloom.pipeline_layout, + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, {}, vk::PrimitiveTopology::eTriangleList, 0, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eFront, vk::FrontFace::eCounterClockwise, + {blend_attachment_state}, depth_stencil_state, bloom.pipeline_layout, direction == 1 ? render_pass : filter_pass.render_pass); } @@ -319,19 +310,9 @@ vk::Pipeline HPPHDR::create_composition_pipeline() depth_stencil_state.front = depth_stencil_state.back; // Empty vertex input state, full screen triangles are generated by the vertex shader - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - {}, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eFront, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - composition.pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, {}, vk::PrimitiveTopology::eTriangleList, 0, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eFront, vk::FrontFace::eCounterClockwise, + {blend_attachment_state}, depth_stencil_state, composition.pipeline_layout, render_pass); } vk::RenderPass HPPHDR::create_filter_render_pass() @@ -405,19 +386,9 @@ vk::Pipeline HPPHDR::create_models_pipeline(uint32_t shaderType, vk::CullModeFla depth_stencil_state.back.compareOp = vk::CompareOp::eAlways; depth_stencil_state.front = depth_stencil_state.back; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - cullMode, - vk::FrontFace::eCounterClockwise, - blend_attachment_states, - depth_stencil_state, - models.pipeline_layout, - offscreen.render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, vertex_input_state, + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, cullMode, vk::FrontFace::eCounterClockwise, + blend_attachment_states, depth_stencil_state, models.pipeline_layout, offscreen.render_pass); } vk::RenderPass HPPHDR::create_offscreen_render_pass() @@ -443,8 +414,7 @@ vk::RenderPass HPPHDR::create_offscreen_render_pass() attachment_descriptions[1].format = offscreen.color[1].format; attachment_descriptions[2].format = offscreen.depth.format; - std::array color_references{{{0, vk::ImageLayout::eColorAttachmentOptimal}, - {1, vk::ImageLayout::eColorAttachmentOptimal}}}; + std::array color_references{{{0, vk::ImageLayout::eColorAttachmentOptimal}, {1, vk::ImageLayout::eColorAttachmentOptimal}}}; vk::AttachmentReference depth_reference{2, vk::ImageLayout::eDepthStencilAttachmentOptimal}; @@ -456,7 +426,8 @@ vk::RenderPass HPPHDR::create_offscreen_render_pass() return create_render_pass(attachment_descriptions, subpass); } -vk::RenderPass HPPHDR::create_render_pass(std::vector const &attachment_descriptions, vk::SubpassDescription const &subpass_description) +vk::RenderPass HPPHDR::create_render_pass(std::vector const &attachment_descriptions, + vk::SubpassDescription const &subpass_description) { // Use subpass dependencies for attachment layout transitions std::array subpass_dependencies; @@ -569,9 +540,10 @@ void HPPHDR::prepare_composition() void HPPHDR::prepare_models() { - std::array bindings = {{{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, - {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}, - {2, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment}}}; + std::array bindings = { + {{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, + {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}, + {2, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment}}}; vk::Device device = get_device().get_handle(); models.descriptor_set_layout = device.createDescriptorSetLayout({.bindingCount = static_cast(bindings.size()), .pBindings = bindings.data()}); @@ -611,12 +583,12 @@ void HPPHDR::prepare_offscreen_buffer() offscreen.render_pass = create_offscreen_render_pass(); - offscreen.framebuffer = vkb::common::create_framebuffer( - get_device().get_handle(), offscreen.render_pass, {offscreen.color[0].view, offscreen.color[1].view, offscreen.depth.view}, offscreen.extent); + offscreen.framebuffer = vkb::common::create_framebuffer(get_device().get_handle(), offscreen.render_pass, + {offscreen.color[0].view, offscreen.color[1].view, offscreen.depth.view}, offscreen.extent); // Create sampler to sample from the color attachments - offscreen.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), color_format, - vk::Filter::eNearest, vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); + offscreen.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), color_format, vk::Filter::eNearest, + vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); } // Bloom separable filter pass @@ -628,9 +600,10 @@ void HPPHDR::prepare_offscreen_buffer() // Floating point color attachment filter_pass.color = create_attachment(color_format, vk::ImageUsageFlagBits::eColorAttachment); filter_pass.render_pass = create_filter_render_pass(); - filter_pass.framebuffer = vkb::common::create_framebuffer(get_device().get_handle(), filter_pass.render_pass, {filter_pass.color.view}, filter_pass.extent); - filter_pass.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), - color_format, vk::Filter::eNearest, vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); + filter_pass.framebuffer = + vkb::common::create_framebuffer(get_device().get_handle(), filter_pass.render_pass, {filter_pass.color.view}, filter_pass.extent); + filter_pass.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), color_format, vk::Filter::eNearest, + vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); } } @@ -638,16 +611,12 @@ void HPPHDR::prepare_offscreen_buffer() void HPPHDR::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffers.matrices = std::make_unique(get_device(), - sizeof(ubo_matrices), - vk::BufferUsageFlagBits::eUniformBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.matrices = + std::make_unique(get_device(), sizeof(ubo_matrices), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); // Params - uniform_buffers.params = std::make_unique(get_device(), - sizeof(ubo_params), - vk::BufferUsageFlagBits::eUniformBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.params = + std::make_unique(get_device(), sizeof(ubo_params), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); update_params(); @@ -695,10 +664,9 @@ void HPPHDR::update_model_descriptor_set(vk::DescriptorSet descriptor_set) { vk::DescriptorBufferInfo matrix_buffer_descriptor{uniform_buffers.matrices->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo environment_image_descriptor{textures.envmap.sampler, - textures.envmap.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - textures.envmap.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo environment_image_descriptor{ + textures.envmap.sampler, textures.envmap.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, textures.envmap.image->get_vk_image_view().get_format())}; vk::DescriptorBufferInfo params_buffer_descriptor{uniform_buffers.params->get_handle(), 0, vk::WholeSize}; diff --git a/samples/api/hpp_hdr/hpp_hdr.h b/samples/api/hpp_hdr/hpp_hdr.h index 4d6bd977a8..77637b0df7 100644 --- a/samples/api/hpp_hdr/hpp_hdr.h +++ b/samples/api/hpp_hdr/hpp_hdr.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -200,20 +200,20 @@ class HPPHDR : public HPPApiVulkanSample vk::Image create_image(vk::Format format, vk::ImageUsageFlagBits usage); vk::Pipeline create_models_pipeline(uint32_t shaderType, vk::CullModeFlagBits cullMode, bool depthTestAndWrite); vk::RenderPass create_offscreen_render_pass(); - vk::RenderPass create_render_pass(std::vector const &attachment_descriptions, vk::SubpassDescription const &subpass_description); - void draw(); - void load_assets(); - void prepare_bloom(); - void prepare_camera(); - void prepare_composition(); - void prepare_models(); - void prepare_offscreen_buffer(); - void prepare_uniform_buffers(); - void update_composition_descriptor_set(); - void update_bloom_descriptor_set(); - void update_model_descriptor_set(vk::DescriptorSet descriptor_set); - void update_params(); - void update_uniform_buffers(); + vk::RenderPass create_render_pass(std::vector const &attachment_descriptions, vk::SubpassDescription const &subpass_description); + void draw(); + void load_assets(); + void prepare_bloom(); + void prepare_camera(); + void prepare_composition(); + void prepare_models(); + void prepare_offscreen_buffer(); + void prepare_uniform_buffers(); + void update_composition_descriptor_set(); + void update_bloom_descriptor_set(); + void update_model_descriptor_set(vk::DescriptorSet descriptor_set); + void update_params(); + void update_uniform_buffers(); private: Bloom bloom; diff --git a/samples/api/hpp_hello_triangle/hpp_hello_triangle.cpp b/samples/api/hpp_hello_triangle/hpp_hello_triangle.cpp index c1eba8a5ff..21af421abc 100644 --- a/samples/api/hpp_hello_triangle/hpp_hello_triangle.cpp +++ b/samples/api/hpp_hello_triangle/hpp_hello_triangle.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. - * Copyright (c) 2024-2025, Arm Limited and Contributors +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. + * Copyright (c) 2024-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -55,23 +55,17 @@ VKAPI_ATTR vk::Bool32 VKAPI_CALL debug_utils_messenger_callback(vk::DebugUtilsMe * @return true if all required extensions are available * @return false otherwise */ -bool validate_extensions(const std::vector &required, - const std::vector &available) +bool validate_extensions(const std::vector &required, const std::vector &available) { // inner find_if gives true if the extension was not found // outer find_if gives true if none of the extensions were not found, that is if all extensions were found - return std::ranges::find_if(required, - [&available](auto extension) { - return std::ranges::find_if(available, - [&extension](auto const &ep) { - return strcmp(ep.extensionName, extension) == 0; - }) == available.end(); - }) == required.end(); + return std::ranges::find_if(required, [&available](auto extension) { + return std::ranges::find_if(available, [&extension](auto const &ep) { return strcmp(ep.extensionName, extension) == 0; }) == available.end(); + }) == required.end(); } HPPHelloTriangle::HPPHelloTriangle() -{ -} +{} HPPHelloTriangle::~HPPHelloTriangle() { @@ -332,8 +326,9 @@ vk::Device HPPHelloTriangle::create_device(const std::vector &requ #if (defined(VKB_ENABLE_PORTABILITY)) // VK_KHR_portability_subset must be enabled if present in the implementation (e.g on macOS/iOS using MoltenVK with beta extensions enabled) - if (std::ranges::any_of(device_extensions, - [](vk::ExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(device_extensions, [](vk::ExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME) == 0; + })) { active_device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME); } @@ -375,7 +370,9 @@ vk::Pipeline HPPHelloTriangle::create_graphics_pipeline() std::vector shader_stages{ {.stage = vk::ShaderStageFlagBits::eVertex, .module = create_shader_module("hello_triangle/" + shader_folder + "/triangle.vert.spv"), .pName = "main"}, - {.stage = vk::ShaderStageFlagBits::eFragment, .module = create_shader_module("hello_triangle/" + shader_folder + "/triangle.frag.spv"), .pName = "main"}}; + {.stage = vk::ShaderStageFlagBits::eFragment, + .module = create_shader_module("hello_triangle/" + shader_folder + "/triangle.frag.spv"), + .pName = "main"}}; // Define the vertex input binding. vk::VertexInputBindingDescription binding_description{.binding = 0, .stride = sizeof(Vertex), .inputRate = vk::VertexInputRate::eVertex}; @@ -386,11 +383,10 @@ vk::Pipeline HPPHelloTriangle::create_graphics_pipeline() {.location = 1, .binding = 0, .format = vk::Format::eR32G32B32Sfloat, .offset = offsetof(Vertex, color)}}}; // Define the pipeline vertex input. - vk::PipelineVertexInputStateCreateInfo vertex_input{ - .vertexBindingDescriptionCount = 1, - .pVertexBindingDescriptions = &binding_description, - .vertexAttributeDescriptionCount = static_cast(attribute_descriptions.size()), - .pVertexAttributeDescriptions = attribute_descriptions.data()}; + vk::PipelineVertexInputStateCreateInfo vertex_input{.vertexBindingDescriptionCount = 1, + .pVertexBindingDescriptions = &binding_description, + .vertexAttributeDescriptionCount = static_cast(attribute_descriptions.size()), + .pVertexAttributeDescriptions = attribute_descriptions.data()}; // Our attachment will write to all color channels, but no blending is enabled. vk::PipelineColorBlendAttachmentState blend_attachment{.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | @@ -399,17 +395,10 @@ vk::Pipeline HPPHelloTriangle::create_graphics_pipeline() // Disable all depth testing. vk::PipelineDepthStencilStateCreateInfo depth_stencil; - vk::Pipeline pipeline = vkb::common::create_graphics_pipeline(device, - nullptr, - shader_stages, - vertex_input, + vk::Pipeline pipeline = vkb::common::create_graphics_pipeline(device, nullptr, shader_stages, vertex_input, vk::PrimitiveTopology::eTriangleList, // We will use triangle lists to draw geometry. - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eBack, - vk::FrontFace::eClockwise, - {blend_attachment}, - depth_stencil, + 0, vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, vk::FrontFace::eClockwise, + {blend_attachment}, depth_stencil, pipeline_layout, // We need to specify the pipeline layout render_pass); // and the render pass up front as well @@ -431,7 +420,8 @@ vk::ImageView HPPHelloTriangle::create_image_view(vk::Image image) return device.createImageView(image_view_create_info); } -vk::Instance HPPHelloTriangle::create_instance(std::vector const &required_instance_extensions, std::vector const &required_validation_layers) +vk::Instance HPPHelloTriangle::create_instance(std::vector const &required_instance_extensions, + std::vector const &required_validation_layers) { #if defined(_HPP_VULKAN_LIBRARY) static vk::detail::DynamicLoader dl(_HPP_VULKAN_LIBRARY); @@ -452,8 +442,9 @@ vk::Instance HPPHelloTriangle::create_instance(std::vector const & #if (defined(VKB_ENABLE_PORTABILITY)) active_instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); bool portability_enumeration_available = false; - if (std::ranges::any_of(available_instance_extensions, - [](vk::ExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(available_instance_extensions, [](vk::ExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; + })) { active_instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); portability_enumeration_available = true; @@ -510,11 +501,10 @@ vk::Instance HPPHelloTriangle::create_instance(std::vector const & .ppEnabledExtensionNames = active_instance_extensions.data()}; #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) - debug_utils_create_info = - vk::DebugUtilsMessengerCreateInfoEXT{.messageSeverity = - vk::DebugUtilsMessageSeverityFlagBitsEXT::eError | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning, - .messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance, - .pfnUserCallback = debug_utils_messenger_callback}; + debug_utils_create_info = vk::DebugUtilsMessengerCreateInfoEXT{ + .messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eError | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning, + .messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance, + .pfnUserCallback = debug_utils_messenger_callback}; instance_info.pNext = &debug_utils_create_info; #endif @@ -600,8 +590,7 @@ vk::ShaderModule HPPHelloTriangle::create_shader_module(std::string const &path) return device.createShaderModule(shader_module_create_info); } -vk::SwapchainKHR - HPPHelloTriangle::create_swapchain(vk::Extent2D const &swapchain_extent, vk::SurfaceFormatKHR surface_format, vk::SwapchainKHR old_swapchain) +vk::SwapchainKHR HPPHelloTriangle::create_swapchain(vk::Extent2D const &swapchain_extent, vk::SurfaceFormatKHR surface_format, vk::SwapchainKHR old_swapchain) { vk::SurfaceCapabilitiesKHR surface_properties = gpu.getSurfaceCapabilitiesKHR(surface); @@ -616,8 +605,9 @@ vk::SwapchainKHR } // Figure out a suitable surface transform. - vk::SurfaceTransformFlagBitsKHR pre_transform = - (surface_properties.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) ? vk::SurfaceTransformFlagBitsKHR::eIdentity : surface_properties.currentTransform; + vk::SurfaceTransformFlagBitsKHR pre_transform = (surface_properties.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) ? + vk::SurfaceTransformFlagBitsKHR::eIdentity : + surface_properties.currentTransform; // Find a supported composite type. vk::CompositeAlphaFlagBitsKHR composite = vk::CompositeAlphaFlagBitsKHR::eOpaque; @@ -641,20 +631,19 @@ vk::SwapchainKHR // FIFO must be supported by all implementations. vk::PresentModeKHR swapchain_present_mode = vk::PresentModeKHR::eFifo; - vk::SwapchainCreateInfoKHR swapchain_create_info{ - .surface = surface, - .minImageCount = desired_swapchain_images, - .imageFormat = surface_format.format, - .imageColorSpace = surface_format.colorSpace, - .imageExtent = swapchain_extent, - .imageArrayLayers = 1, - .imageUsage = vk::ImageUsageFlagBits::eColorAttachment, - .imageSharingMode = vk::SharingMode::eExclusive, - .preTransform = pre_transform, - .compositeAlpha = composite, - .presentMode = swapchain_present_mode, - .clipped = true, - .oldSwapchain = old_swapchain}; + vk::SwapchainCreateInfoKHR swapchain_create_info{.surface = surface, + .minImageCount = desired_swapchain_images, + .imageFormat = surface_format.format, + .imageColorSpace = surface_format.colorSpace, + .imageExtent = swapchain_extent, + .imageArrayLayers = 1, + .imageUsage = vk::ImageUsageFlagBits::eColorAttachment, + .imageSharingMode = vk::SharingMode::eExclusive, + .preTransform = pre_transform, + .compositeAlpha = composite, + .presentMode = swapchain_present_mode, + .clipped = true, + .oldSwapchain = old_swapchain}; return device.createSwapchainKHR(swapchain_create_info); } @@ -663,9 +652,7 @@ std::pair HPPHelloTriangle::create_vertex_buffer() { // Vertex data for a single colored triangle const std::vector vertices = { - {{0.5f, -0.5f, 0.5f}, {1.0f, 0.0f, 0.0f}}, - {{0.5f, 0.5f, 0.5f}, {0.0f, 1.0f, 0.0f}}, - {{-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}}}; + {{0.5f, -0.5f, 0.5f}, {1.0f, 0.0f, 0.0f}}, {{0.5f, 0.5f, 0.5f}, {0.0f, 1.0f, 0.0f}}, {{-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}}}; const vk::DeviceSize buffer_size = sizeof(vertices[0]) * vertices.size(); @@ -675,15 +662,15 @@ std::pair HPPHelloTriangle::create_vertex_buffer() // We use the Vulkan Memory Allocator to find a memory type that can be written and mapped from the host // On most setups this will return a memory type that resides in VRAM and is accessible from the host - VmaAllocationCreateInfo allocation_create_info{ - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - .requiredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}; + VmaAllocationCreateInfo allocation_create_info{.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}; vk::Buffer vertex_buffer; VmaAllocation vertex_buffer_allocation; VmaAllocationInfo allocation_info{}; - vmaCreateBuffer(vma_allocator, reinterpret_cast(&buffer_create_info), &allocation_create_info, reinterpret_cast(&vertex_buffer), &vertex_buffer_allocation, &allocation_info); + vmaCreateBuffer(vma_allocator, reinterpret_cast(&buffer_create_info), &allocation_create_info, + reinterpret_cast(&vertex_buffer), &vertex_buffer_allocation, &allocation_info); if (allocation_info.pMappedData) { memcpy(allocation_info.pMappedData, vertices.data(), buffer_size); @@ -699,9 +686,8 @@ std::pair HPPHelloTriangle::create_vertex_buffer() VmaAllocator HPPHelloTriangle::create_vma_allocator() { // This sample uses the Vulkan Memory Alloctor (VMA), which needs to be set up - VmaVulkanFunctions vma_vulkan_functions{ - .vkGetInstanceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetInstanceProcAddr, - .vkGetDeviceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetDeviceProcAddr}; + VmaVulkanFunctions vma_vulkan_functions{.vkGetInstanceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetInstanceProcAddr, + .vkGetDeviceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetDeviceProcAddr}; VmaAllocatorCreateInfo allocator_info{.physicalDevice = gpu, .device = device, .pVulkanFunctions = &vma_vulkan_functions, .instance = instance}; diff --git a/samples/api/hpp_hello_triangle/hpp_hello_triangle.h b/samples/api/hpp_hello_triangle/hpp_hello_triangle.h index e798d94743..95aac6b6d3 100644 --- a/samples/api/hpp_hello_triangle/hpp_hello_triangle.h +++ b/samples/api/hpp_hello_triangle/hpp_hello_triangle.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -68,14 +68,14 @@ class HPPHelloTriangle : public vkb::Application virtual bool resize(const uint32_t width, const uint32_t height) override; virtual void update(float delta_time) override; - std::pair acquire_next_image(); - vk::Device create_device(const std::vector &required_device_extensions); - vk::Pipeline create_graphics_pipeline(); - vk::ImageView create_image_view(vk::Image image); - vk::Instance create_instance(std::vector const &required_instance_extensions, std::vector const &required_validation_layers); - vk::RenderPass create_render_pass(); - vk::ShaderModule create_shader_module(std::string const &path); - vk::SwapchainKHR create_swapchain(vk::Extent2D const &swapchain_extent, vk::SurfaceFormatKHR surface_format, vk::SwapchainKHR old_swapchain); + std::pair acquire_next_image(); + vk::Device create_device(const std::vector &required_device_extensions); + vk::Pipeline create_graphics_pipeline(); + vk::ImageView create_image_view(vk::Image image); + vk::Instance create_instance(std::vector const &required_instance_extensions, std::vector const &required_validation_layers); + vk::RenderPass create_render_pass(); + vk::ShaderModule create_shader_module(std::string const &path); + vk::SwapchainKHR create_swapchain(vk::Extent2D const &swapchain_extent, vk::SurfaceFormatKHR surface_format, vk::SwapchainKHR old_swapchain); std::pair create_vertex_buffer(); VmaAllocator create_vma_allocator(); void init_framebuffers(); diff --git a/samples/api/hpp_hello_triangle_1_3/hpp_hello_triangle_1_3.cpp b/samples/api/hpp_hello_triangle_1_3/hpp_hello_triangle_1_3.cpp index 94b7bd55e7..04e95ab840 100644 --- a/samples/api/hpp_hello_triangle_1_3/hpp_hello_triangle_1_3.cpp +++ b/samples/api/hpp_hello_triangle_1_3/hpp_hello_triangle_1_3.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2025-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -191,7 +191,8 @@ void HPPHelloTriangleV13::select_physical_device_and_surface(vkb::Window *window context.instance.destroySurfaceKHR(context.surface); } - context.surface = static_cast(window->create_surface(static_cast(context.instance), static_cast(physical_device))); + context.surface = + static_cast(window->create_surface(static_cast(context.instance), static_cast(physical_device))); if (!context.surface) { throw std::runtime_error("Failed to create window surface."); @@ -200,11 +201,10 @@ void HPPHelloTriangleV13::select_physical_device_and_surface(vkb::Window *window // Find a queue family that supports graphics and presentation std::vector queue_family_properties = physical_device.getQueueFamilyProperties(); - auto qfpIt = std::ranges::find_if(queue_family_properties, - [&physical_device, surface = context.surface](vk::QueueFamilyProperties const &qfp) { - static uint32_t index = 0; - return (qfp.queueFlags & vk::QueueFlagBits::eGraphics) && physical_device.getSurfaceSupportKHR(index++, surface); - }); + auto qfpIt = std::ranges::find_if(queue_family_properties, [&physical_device, surface = context.surface](vk::QueueFamilyProperties const &qfp) { + static uint32_t index = 0; + return (qfp.queueFlags & vk::QueueFlagBits::eGraphics) && physical_device.getSurfaceSupportKHR(index++, surface); + }); if (qfpIt != queue_family_properties.end()) { context.graphics_queue_index = std::distance(queue_family_properties.begin(), qfpIt); @@ -387,8 +387,9 @@ void HPPHelloTriangleV13::init_device() #if (defined(VKB_ENABLE_PORTABILITY)) // VK_KHR_portability_subset must be enabled if present in the implementation (e.g on macOS/iOS using MoltenVK with beta extensions enabled) - if (std::ranges::any_of(device_extensions, - [](vk::ExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(device_extensions, [](vk::ExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME) == 0; + })) { required_device_extensions.push_back(VK_KHR_PORTABILITY_SUBSET_EXTENSION_NAME); } @@ -422,9 +423,8 @@ void HPPHelloTriangleV13::init_device() float queue_priority = 0.5f; // Create one queue - vk::DeviceQueueCreateInfo queue_info{.queueFamilyIndex = static_cast(context.graphics_queue_index), - .queueCount = 1, - .pQueuePriorities = &queue_priority}; + vk::DeviceQueueCreateInfo queue_info{ + .queueFamilyIndex = static_cast(context.graphics_queue_index), .queueCount = 1, .pQueuePriorities = &queue_priority}; vk::DeviceCreateInfo device_info{.pNext = &enabled_features_chain.get(), .queueCreateInfoCount = 1, @@ -460,9 +460,9 @@ void HPPHelloTriangleV13::init_instance() std::vector required_instance_extensions{VK_KHR_SURFACE_EXTENSION_NAME}; #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) - bool has_debug_utils = std::ranges::any_of( - available_instance_extensions, - [](auto const &ep) { return strncmp(ep.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME, strlen(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) == 0; }); + bool has_debug_utils = std::ranges::any_of(available_instance_extensions, [](auto const &ep) { + return strncmp(ep.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME, strlen(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) == 0; + }); if (has_debug_utils) { required_instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); @@ -475,9 +475,9 @@ void HPPHelloTriangleV13::init_instance() #if (defined(VKB_ENABLE_PORTABILITY)) required_instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); - bool portability_enumeration_available = std::ranges::any_of( - available_instance_extensions, - [](VkExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; }); + bool portability_enumeration_available = std::ranges::any_of(available_instance_extensions, [](VkExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; + }); if (portability_enumeration_available) { required_instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); @@ -587,9 +587,8 @@ void HPPHelloTriangleV13::init_per_frame(PerFrame &per_frame) .queueFamilyIndex = static_cast(context.graphics_queue_index)}; per_frame.primary_command_pool = context.device.createCommandPool(cmd_pool_info); - vk::CommandBufferAllocateInfo cmd_buf_info{.commandPool = per_frame.primary_command_pool, - .level = vk::CommandBufferLevel::ePrimary, - .commandBufferCount = 1}; + vk::CommandBufferAllocateInfo cmd_buf_info{ + .commandPool = per_frame.primary_command_pool, .level = vk::CommandBufferLevel::ePrimary, .commandBufferCount = 1}; per_frame.primary_command_buffer = context.device.allocateCommandBuffers(cmd_buf_info)[0]; } @@ -624,8 +623,8 @@ void HPPHelloTriangleV13::init_pipeline() vk::PipelineRasterizationStateCreateInfo raster{.polygonMode = vk::PolygonMode::eFill, .lineWidth = 1.0f}; // Specify that these states will be dynamic, i.e. not part of pipeline state object. - std::vector dynamic_states = { - vk::DynamicState::eViewport, vk::DynamicState::eScissor, vk::DynamicState::eCullMode, vk::DynamicState::eFrontFace, vk::DynamicState::ePrimitiveTopology}; + std::vector dynamic_states = {vk::DynamicState::eViewport, vk::DynamicState::eScissor, vk::DynamicState::eCullMode, + vk::DynamicState::eFrontFace, vk::DynamicState::ePrimitiveTopology}; // Our attachment will write to all color channels, but no blending is enabled. vk::PipelineColorBlendAttachmentState blend_attachment{.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | @@ -849,10 +848,10 @@ void HPPHelloTriangleV13::init_vertex_buffer() vk::MemoryRequirements memory_requirements = context.device.getBufferMemoryRequirements(context.vertex_buffer); // Allocate memory for the buffer - vk::MemoryAllocateInfo alloc_info{ - .allocationSize = memory_requirements.size, - .memoryTypeIndex = - find_memory_type(context.gpu, memory_requirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent)}; + vk::MemoryAllocateInfo alloc_info{.allocationSize = memory_requirements.size, + .memoryTypeIndex = + find_memory_type(context.gpu, memory_requirements.memoryTypeBits, + vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent)}; context.vertex_buffer_memory = context.device.allocateMemory(alloc_info); @@ -924,10 +923,7 @@ void HPPHelloTriangleV13::render_triangle(uint32_t swapchain_index) cmd.begin(begin_info); // Before starting rendering, transition the swapchain image to COLOR_ATTACHMENT_OPTIMAL - transition_image_layout(cmd, - context.swapchain_images[swapchain_index], - vk::ImageLayout::eUndefined, - vk::ImageLayout::eColorAttachmentOptimal, + transition_image_layout(cmd, context.swapchain_images[swapchain_index], vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal, {}, // srcAccessMask (no need to wait for previous operations) vk::AccessFlagBits2::eColorAttachmentWrite, // dstAccessMask vk::PipelineStageFlagBits2::eTopOfPipe, // srcStage @@ -946,15 +942,16 @@ void HPPHelloTriangleV13::render_triangle(uint32_t swapchain_index) .clearValue = clear_value}; // Begin rendering - vk::RenderingInfo rendering_info{ - .renderArea = { // Initialize the nested `VkRect2D` structure - .offset = {0, 0}, // Initialize the `VkOffset2D` inside `renderArea` - .extent = { // Initialize the `VkExtent2D` inside `renderArea` - .width = context.swapchain_dimensions.width, - .height = context.swapchain_dimensions.height}}, - .layerCount = 1, - .colorAttachmentCount = 1, - .pColorAttachments = &color_attachment}; + vk::RenderingInfo rendering_info{.renderArea = + { // Initialize the nested `VkRect2D` structure + .offset = {0, 0}, // Initialize the `VkOffset2D` inside `renderArea` + .extent = + {// Initialize the `VkExtent2D` inside `renderArea` + .width = context.swapchain_dimensions.width, + .height = context.swapchain_dimensions.height}}, + .layerCount = 1, + .colorAttachmentCount = 1, + .pColorAttachments = &color_attachment}; cmd.beginRendering(rendering_info); @@ -1002,10 +999,7 @@ void HPPHelloTriangleV13::render_triangle(uint32_t swapchain_index) cmd.endRendering(); // After rendering , transition the swapchain image to PRESENT_SRC - transition_image_layout(cmd, - context.swapchain_images[swapchain_index], - vk::ImageLayout::eColorAttachmentOptimal, - vk::ImageLayout::ePresentSrcKHR, + transition_image_layout(cmd, context.swapchain_images[swapchain_index], vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::ePresentSrcKHR, vk::AccessFlagBits2::eColorAttachmentWrite, // srcAccessMask {}, // dstAccessMask vk::PipelineStageFlagBits2::eColorAttachmentOutput, // srcStage @@ -1092,32 +1086,31 @@ void HPPHelloTriangleV13::transition_image_layout(vk::CommandBuffer cmd, vk::PipelineStageFlags2 dstStage) { // Initialize the VkImageMemoryBarrier2 structure - vk::ImageMemoryBarrier2 image_barrier{ - // Specify the pipeline stages and access masks for the barrier - .srcStageMask = srcStage, // Source pipeline stage mask - .srcAccessMask = srcAccessMask, // Source access mask - .dstStageMask = dstStage, // Destination pipeline stage mask - .dstAccessMask = dstAccessMask, // Destination access mask - - // Specify the old and new layouts of the image - .oldLayout = oldLayout, // Current layout of the image - .newLayout = newLayout, // Target layout of the image - - // We are not changing the ownership between queues - .srcQueueFamilyIndex = vk::QueueFamilyIgnored, - .dstQueueFamilyIndex = vk::QueueFamilyIgnored, - - // Specify the image to be affected by this barrier - .image = image, - - // Define the subresource range (which parts of the image are affected) - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, // Affects the color aspect of the image - .baseMipLevel = 0, // Start at mip level 0 - .levelCount = 1, // Number of mip levels affected - .baseArrayLayer = 0, // Start at array layer 0 - .layerCount = 1 // Number of array layers affected - }}; + vk::ImageMemoryBarrier2 image_barrier{ // Specify the pipeline stages and access masks for the barrier + .srcStageMask = srcStage, // Source pipeline stage mask + .srcAccessMask = srcAccessMask, // Source access mask + .dstStageMask = dstStage, // Destination pipeline stage mask + .dstAccessMask = dstAccessMask, // Destination access mask + + // Specify the old and new layouts of the image + .oldLayout = oldLayout, // Current layout of the image + .newLayout = newLayout, // Target layout of the image + + // We are not changing the ownership between queues + .srcQueueFamilyIndex = vk::QueueFamilyIgnored, + .dstQueueFamilyIndex = vk::QueueFamilyIgnored, + + // Specify the image to be affected by this barrier + .image = image, + + // Define the subresource range (which parts of the image are affected) + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, // Affects the color aspect of the image + .baseMipLevel = 0, // Start at mip level 0 + .levelCount = 1, // Number of mip levels affected + .baseArrayLayer = 0, // Start at array layer 0 + .layerCount = 1 // Number of array layers affected + }}; // Initialize the VkDependencyInfo structure vk::DependencyInfo dependency_info{ @@ -1138,20 +1131,17 @@ void HPPHelloTriangleV13::transition_image_layout(vk::CommandBuffer cmd, * @return true if all required extensions are available * @return false otherwise */ -bool HPPHelloTriangleV13::validate_extensions(const std::vector &required, - const std::vector &available) +bool HPPHelloTriangleV13::validate_extensions(const std::vector &required, const std::vector &available) { - return std::ranges::all_of(required, - [&available](auto const &extension_name) { - bool found = std::ranges::any_of( - available, [&extension_name](auto const &ep) { return strcmp(ep.extensionName, extension_name) == 0; }); - if (!found) - { - // Output an error message for the missing extension - LOGE("Error: Required extension not found: {}", extension_name); - } - return found; - }); + return std::ranges::all_of(required, [&available](auto const &extension_name) { + bool found = std::ranges::any_of(available, [&extension_name](auto const &ep) { return strcmp(ep.extensionName, extension_name) == 0; }); + if (!found) + { + // Output an error message for the missing extension + LOGE("Error: Required extension not found: {}", extension_name); + } + return found; + }); } std::unique_ptr create_hpp_hello_triangle_1_3() diff --git a/samples/api/hpp_instancing/hpp_instancing.cpp b/samples/api/hpp_instancing/hpp_instancing.cpp index 264fd4f06a..fd3e0d52f0 100644 --- a/samples/api/hpp_instancing/hpp_instancing.cpp +++ b/samples/api/hpp_instancing/hpp_instancing.cpp @@ -115,9 +115,8 @@ void HPPInstancing::build_command_buffers() { vk::CommandBufferBeginInfo command_buffer_begin_info; - std::array clear_values = - {{vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.033f, 0.0f}})), - vk::ClearDepthStencilValue{0.0f, 0}}}; + std::array clear_values = { + {vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.033f, 0.0f}})), vk::ClearDepthStencilValue{0.0f, 0}}}; vk::RenderPassBeginInfo render_pass_begin_info{.renderPass = render_pass, .renderArea = {{0, 0}, extent}, @@ -198,9 +197,8 @@ vk::DescriptorPool HPPInstancing::create_descriptor_pool() { // Example uses one ubo std::array pool_sizes = {{{vk::DescriptorType::eUniformBuffer, 2}, {vk::DescriptorType::eCombinedImageSampler, 2}}}; - vk::DescriptorPoolCreateInfo descriptor_pool_create_info{.maxSets = 2, - .poolSizeCount = static_cast(pool_sizes.size()), - .pPoolSizes = pool_sizes.data()}; + vk::DescriptorPoolCreateInfo descriptor_pool_create_info{ + .maxSets = 2, .poolSizeCount = static_cast(pool_sizes.size()), .pPoolSizes = pool_sizes.data()}; return get_device().get_handle().createDescriptorPool(descriptor_pool_create_info); } @@ -249,19 +247,9 @@ vk::Pipeline HPPInstancing::create_planet_pipeline() depth_stencil_state.back.compareOp = vk::CompareOp::eAlways; depth_stencil_state.front = depth_stencil_state.back; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eBack, - vk::FrontFace::eClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, input_state, vk::PrimitiveTopology::eTriangleList, 0, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, vk::FrontFace::eClockwise, {blend_attachment_state}, + depth_stencil_state, pipeline_layout, render_pass); } vk::Pipeline HPPInstancing::create_rocks_pipeline() @@ -311,19 +299,9 @@ vk::Pipeline HPPInstancing::create_rocks_pipeline() depth_stencil_state.back.compareOp = vk::CompareOp::eAlways; depth_stencil_state.front = depth_stencil_state.back; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eBack, - vk::FrontFace::eClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, input_state, vk::PrimitiveTopology::eTriangleList, 0, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, vk::FrontFace::eClockwise, {blend_attachment_state}, + depth_stencil_state, pipeline_layout, render_pass); } vk::Pipeline HPPInstancing::create_starfield_pipeline() @@ -360,19 +338,10 @@ vk::Pipeline HPPInstancing::create_starfield_pipeline() depth_stencil_state.back.compareOp = vk::CompareOp::eAlways; depth_stencil_state.front = depth_stencil_state.back; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, {}, // Vertices are generated in the vertex shader - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, + vk::FrontFace::eClockwise, {blend_attachment_state}, depth_stencil_state, pipeline_layout, render_pass); } void HPPInstancing::draw() @@ -427,7 +396,8 @@ void HPPInstancing::prepare_instance_data() rho = sqrt((pow(ring0[1], 2.0f) - pow(ring0[0], 2.0f)) * uniform_dist(rnd_generator) + pow(ring0[0], 2.0f)); theta = 2.0f * glm::pi() * uniform_dist(rnd_generator); instance_data[i].pos = glm::vec3(rho * cos(theta), uniform_dist(rnd_generator) * 0.5f - 0.25f, rho * sin(theta)); - instance_data[i].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator)); + instance_data[i].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), + glm::pi() * uniform_dist(rnd_generator)); instance_data[i].scale = 1.5f + uniform_dist(rnd_generator) - uniform_dist(rnd_generator); instance_data[i].texIndex = rnd_texture_index(rnd_generator); instance_data[i].scale *= 0.75f; @@ -436,7 +406,8 @@ void HPPInstancing::prepare_instance_data() rho = sqrt((pow(ring1[1], 2.0f) - pow(ring1[0], 2.0f)) * uniform_dist(rnd_generator) + pow(ring1[0], 2.0f)); theta = 2.0f * glm::pi() * uniform_dist(rnd_generator); instance_data[j].pos = glm::vec3(rho * cos(theta), uniform_dist(rnd_generator) * 0.5f - 0.25f, rho * sin(theta)); - instance_data[j].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator)); + instance_data[j].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), + glm::pi() * uniform_dist(rnd_generator)); instance_data[j].scale = 1.5f + uniform_dist(rnd_generator) - uniform_dist(rnd_generator); instance_data[j].texIndex = rnd_texture_index(rnd_generator); instance_data[j].scale *= 0.75f; @@ -494,11 +465,10 @@ void HPPInstancing::update_uniform_buffer(float delta_time) void HPPInstancing::update_planet_descriptor_set() { - vk::DescriptorBufferInfo buffer_descriptor{uniform_buffers.scene->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo image_descriptor{planet.texture.sampler, - planet.texture.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - planet.texture.image->get_vk_image_view().get_format())}; + vk::DescriptorBufferInfo buffer_descriptor{uniform_buffers.scene->get_handle(), 0, vk::WholeSize}; + vk::DescriptorImageInfo image_descriptor{ + planet.texture.sampler, planet.texture.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, planet.texture.image->get_vk_image_view().get_format())}; std::array write_descriptor_sets = {{{.dstSet = planet.descriptor_set, .dstBinding = 0, .descriptorCount = 1, @@ -514,11 +484,10 @@ void HPPInstancing::update_planet_descriptor_set() void HPPInstancing::update_rocks_descriptor_set() { - vk::DescriptorBufferInfo buffer_descriptor{uniform_buffers.scene->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo image_descriptor{rocks.texture.sampler, - rocks.texture.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - rocks.texture.image->get_vk_image_view().get_format())}; + vk::DescriptorBufferInfo buffer_descriptor{uniform_buffers.scene->get_handle(), 0, vk::WholeSize}; + vk::DescriptorImageInfo image_descriptor{ + rocks.texture.sampler, rocks.texture.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, rocks.texture.image->get_vk_image_view().get_format())}; std::array write_descriptor_sets = {{{.dstSet = rocks.descriptor_set, .dstBinding = 0, .descriptorCount = 1, diff --git a/samples/api/hpp_oit_depth_peeling/hpp_oit_depth_peeling.cpp b/samples/api/hpp_oit_depth_peeling/hpp_oit_depth_peeling.cpp index 435c877294..c05e9524a0 100644 --- a/samples/api/hpp_oit_depth_peeling/hpp_oit_depth_peeling.cpp +++ b/samples/api/hpp_oit_depth_peeling/hpp_oit_depth_peeling.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2024-2025, Google - * Copyright (c) 2024-2025, NVIDIA +/* Copyright (c) 2024-2026, Google + * Copyright (c) 2024-2026, NVIDIA * * SPDX-License-Identifier: Apache-2.0 * @@ -92,14 +92,12 @@ void HPPOITDepthPeeling::build_command_buffers() { vk::CommandBufferBeginInfo command_buffer_begin_info; - std::array clear_values = {{vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 0.0f}})), - vk::ClearDepthStencilValue{0.0f, 0}}}; + std::array clear_values = {{vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 0.0f}})), vk::ClearDepthStencilValue{0.0f, 0}}}; - vk::RenderPassBeginInfo render_pass_begin_info{.renderArea = {{0, 0}, extent}, - .clearValueCount = static_cast(clear_values.size()), - .pClearValues = clear_values.data()}; - vk::Viewport viewport{0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}; - vk::Rect2D scissor{{0, 0}, extent}; + vk::RenderPassBeginInfo render_pass_begin_info{ + .renderArea = {{0, 0}, extent}, .clearValueCount = static_cast(clear_values.size()), .pClearValues = clear_values.data()}; + vk::Viewport viewport{0.0f, 0.0f, static_cast(extent.width), static_cast(extent.height), 0.0f, 1.0f}; + vk::Rect2D scissor{{0, 0}, extent}; for (int32_t i = 0; i < draw_cmd_buffers.size(); ++i) { @@ -117,39 +115,28 @@ void HPPOITDepthPeeling::build_command_buffers() // It is bound as texture and read in the shader to discard fragments from the // previous layers. vk::ImageSubresourceRange depth_subresource_range = {vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1}; - vkb::common::image_layout_transition(command_buffer, - depths[l % kDepthCount].image->get_handle(), - vk::PipelineStageFlagBits::eFragmentShader, + vkb::common::image_layout_transition(command_buffer, depths[l % kDepthCount].image->get_handle(), vk::PipelineStageFlagBits::eFragmentShader, vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests, vk::AccessFlagBits::eShaderRead, vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite, l <= 1 ? vk::ImageLayout::eUndefined : vk::ImageLayout::eDepthStencilReadOnlyOptimal, - vk::ImageLayout::eDepthStencilAttachmentOptimal, - depth_subresource_range); + vk::ImageLayout::eDepthStencilAttachmentOptimal, depth_subresource_range); if (l > 0) { - vkb::common::image_layout_transition(command_buffer, - depths[(l + 1) % kDepthCount].image->get_handle(), + vkb::common::image_layout_transition(command_buffer, depths[(l + 1) % kDepthCount].image->get_handle(), vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests, vk::PipelineStageFlagBits::eFragmentShader, vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite, - vk::AccessFlagBits::eShaderRead, - vk::ImageLayout::eDepthStencilAttachmentOptimal, - vk::ImageLayout::eDepthStencilReadOnlyOptimal, - depth_subresource_range); + vk::AccessFlagBits::eShaderRead, vk::ImageLayout::eDepthStencilAttachmentOptimal, + vk::ImageLayout::eDepthStencilReadOnlyOptimal, depth_subresource_range); } // Set one of the layer textures as color attachment, as the gatherPass pass will render to it. vk::ImageSubresourceRange layer_subresource_range = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}; - vkb::common::image_layout_transition(command_buffer, - layers[l].image->get_handle(), - vk::PipelineStageFlagBits::eFragmentShader, - vk::PipelineStageFlagBits::eColorAttachmentOutput, - vk::AccessFlagBits::eShaderRead, - vk::AccessFlagBits::eColorAttachmentWrite, - vk::ImageLayout::eUndefined, - vk::ImageLayout::eColorAttachmentOptimal, - layer_subresource_range); + vkb::common::image_layout_transition(command_buffer, layers[l].image->get_handle(), vk::PipelineStageFlagBits::eFragmentShader, + vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::AccessFlagBits::eShaderRead, + vk::AccessFlagBits::eColorAttachmentWrite, vk::ImageLayout::eUndefined, + vk::ImageLayout::eColorAttachmentOptimal, layer_subresource_range); render_pass_begin_info.framebuffer = layers[l].gather_framebuffer; render_pass_begin_info.renderPass = gatherPass.render_pass; @@ -159,7 +146,8 @@ void HPPOITDepthPeeling::build_command_buffers() command_buffer.setViewport(0, viewport); command_buffer.setScissor(0, scissor); - command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gatherPass.pipeline_layout, 0, depths[l % kDepthCount].gather_descriptor_set, {}); + command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gatherPass.pipeline_layout, 0, + depths[l % kDepthCount].gather_descriptor_set, {}); command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, l == 0 ? gatherPass.first_pipeline : gatherPass.pipeline); draw_model(model, command_buffer); @@ -167,15 +155,10 @@ void HPPOITDepthPeeling::build_command_buffers() command_buffer.endRenderPass(); // Get the layer texture ready to be read by the combinePass pass. - vkb::common::image_layout_transition(command_buffer, - layers[l].image->get_handle(), - vk::PipelineStageFlagBits::eColorAttachmentOutput, - vk::PipelineStageFlagBits::eFragmentShader, - vk::AccessFlagBits::eColorAttachmentWrite, - vk::AccessFlagBits::eShaderRead, - vk::ImageLayout::eColorAttachmentOptimal, - vk::ImageLayout::eShaderReadOnlyOptimal, - layer_subresource_range); + vkb::common::image_layout_transition(command_buffer, layers[l].image->get_handle(), vk::PipelineStageFlagBits::eColorAttachmentOutput, + vk::PipelineStageFlagBits::eFragmentShader, vk::AccessFlagBits::eColorAttachmentWrite, + vk::AccessFlagBits::eShaderRead, vk::ImageLayout::eColorAttachmentOptimal, + vk::ImageLayout::eShaderReadOnlyOptimal, layer_subresource_range); } // Combine pass @@ -239,26 +222,16 @@ void HPPOITDepthPeeling::create_background_pipeline() load_shader("oit_depth_peeling/background.frag.spv", vk::ShaderStageFlagBits::eFragment)}; vk::VertexInputBindingDescription vertex_input_binding{0, sizeof(HPPVertex), vk::VertexInputRate::eVertex}; - std::array vertex_input_attributes = {{{0, 0, vk::Format::eR32G32B32Sfloat, offsetof(HPPVertex, pos)}, - {1, 0, vk::Format::eR32G32Sfloat, offsetof(HPPVertex, uv)}}}; + std::array vertex_input_attributes = { + {{0, 0, vk::Format::eR32G32B32Sfloat, offsetof(HPPVertex, pos)}, {1, 0, vk::Format::eR32G32Sfloat, offsetof(HPPVertex, uv)}}}; vk::PipelineColorBlendAttachmentState blend_attachment_state{.colorWriteMask = vk::FlagTraits::allFlags}; vk::PipelineDepthStencilStateCreateInfo depth_stencil_state{.depthCompareOp = vk::CompareOp::eGreater, .back = {.compareOp = vk::CompareOp::eAlways}}; - background.pipeline = vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - {}, - vk::PrimitiveTopology::eTriangleList, - {}, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - combinePass.pipeline_layout, - render_pass); + background.pipeline = vkb::common::create_graphics_pipeline( + get_device().get_handle(), pipeline_cache, shader_stages, {}, vk::PrimitiveTopology::eTriangleList, {}, vk::PolygonMode::eFill, + vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, combinePass.pipeline_layout, render_pass); } void HPPOITDepthPeeling::create_combine_pass() @@ -269,7 +242,8 @@ void HPPOITDepthPeeling::create_combine_pass() {{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}, {2, vk::DescriptorType::eCombinedImageSampler, kLayerMaxCount, vk::ShaderStageFlagBits::eFragment}}}; - combinePass.descriptor_set_layout = device.createDescriptorSetLayout({.bindingCount = static_cast(set_layout_bindings.size()), .pBindings = set_layout_bindings.data()}); + combinePass.descriptor_set_layout = + device.createDescriptorSetLayout({.bindingCount = static_cast(set_layout_bindings.size()), .pBindings = set_layout_bindings.data()}); combinePass.descriptor_set = vkb::common::allocate_descriptor_set(device, descriptor_pool, combinePass.descriptor_set_layout); @@ -284,8 +258,8 @@ void HPPOITDepthPeeling::create_combine_pass_pipeline() load_shader("oit_depth_peeling/combine.frag.spv", vk::ShaderStageFlagBits::eFragment)}; vk::VertexInputBindingDescription vertex_input_binding{0, sizeof(HPPVertex), vk::VertexInputRate::eVertex}; - std::array vertex_input_attributes = {{{0, 0, vk::Format::eR32G32B32Sfloat, offsetof(HPPVertex, pos)}, - {1, 0, vk::Format::eR32G32Sfloat, offsetof(HPPVertex, uv)}}}; + std::array vertex_input_attributes = { + {{0, 0, vk::Format::eR32G32B32Sfloat, offsetof(HPPVertex, pos)}, {1, 0, vk::Format::eR32G32Sfloat, offsetof(HPPVertex, uv)}}}; vk::PipelineColorBlendAttachmentState blend_attachment_state{true, vk::BlendFactor::eSrcAlpha, @@ -298,19 +272,9 @@ void HPPOITDepthPeeling::create_combine_pass_pipeline() vk::PipelineDepthStencilStateCreateInfo depth_stencil_state{.depthCompareOp = vk::CompareOp::eGreater, .back = {.compareOp = vk::CompareOp::eAlways}}; - combinePass.pipeline = vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - {}, - vk::PrimitiveTopology::eTriangleList, - {}, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - combinePass.pipeline_layout, - render_pass); + combinePass.pipeline = vkb::common::create_graphics_pipeline( + get_device().get_handle(), pipeline_cache, shader_stages, {}, vk::PrimitiveTopology::eTriangleList, {}, vk::PolygonMode::eFill, + vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, combinePass.pipeline_layout, render_pass); } void HPPOITDepthPeeling::create_descriptor_pool() @@ -321,16 +285,15 @@ void HPPOITDepthPeeling::create_descriptor_pool() const uint32_t num_combine_pass_combined_image_sampler = kLayerMaxCount + 1; const uint32_t num_combine_pass_uniform_buffer = 1; - const uint32_t num_uniform_buffer_descriptors = num_gather_pass_uniform_buffer + num_combine_pass_uniform_buffer; - const uint32_t num_combined_image_sampler_descriptors = num_gather_pass_combined_image_sampler + num_combine_pass_combined_image_sampler; - std::array pool_sizes = {{{vk::DescriptorType::eUniformBuffer, num_uniform_buffer_descriptors}, - {vk::DescriptorType::eCombinedImageSampler, num_combined_image_sampler_descriptors}}}; - const uint32_t num_gather_descriptor_sets = 2; - const uint32_t num_combine_descriptor_sets = 1; - const uint32_t num_descriptor_sets = num_gather_descriptor_sets + num_combine_descriptor_sets; - vk::DescriptorPoolCreateInfo descriptor_pool_create_info{.maxSets = num_descriptor_sets, - .poolSizeCount = static_cast(pool_sizes.size()), - .pPoolSizes = pool_sizes.data()}; + const uint32_t num_uniform_buffer_descriptors = num_gather_pass_uniform_buffer + num_combine_pass_uniform_buffer; + const uint32_t num_combined_image_sampler_descriptors = num_gather_pass_combined_image_sampler + num_combine_pass_combined_image_sampler; + std::array pool_sizes = {{{vk::DescriptorType::eUniformBuffer, num_uniform_buffer_descriptors}, + {vk::DescriptorType::eCombinedImageSampler, num_combined_image_sampler_descriptors}}}; + const uint32_t num_gather_descriptor_sets = 2; + const uint32_t num_combine_descriptor_sets = 1; + const uint32_t num_descriptor_sets = num_gather_descriptor_sets + num_combine_descriptor_sets; + vk::DescriptorPoolCreateInfo descriptor_pool_create_info{ + .maxSets = num_descriptor_sets, .poolSizeCount = static_cast(pool_sizes.size()), .pPoolSizes = pool_sizes.data()}; descriptor_pool = get_device().get_handle().createDescriptorPool(descriptor_pool_create_info); } @@ -388,47 +351,29 @@ void HPPOITDepthPeeling::create_gather_pass_pipelines() load_shader("oit_depth_peeling/gather_first.frag.spv", vk::ShaderStageFlagBits::eFragment)}; vk::VertexInputBindingDescription vertex_input_binding{0, sizeof(HPPVertex), vk::VertexInputRate::eVertex}; - std::array vertex_input_attributes = {{{0, 0, vk::Format::eR32G32B32Sfloat, offsetof(HPPVertex, pos)}, - {1, 0, vk::Format::eR32G32Sfloat, offsetof(HPPVertex, uv)}}}; - vk::PipelineVertexInputStateCreateInfo vertex_input_state{.vertexBindingDescriptionCount = 1, - .pVertexBindingDescriptions = &vertex_input_binding, - .vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()), - .pVertexAttributeDescriptions = vertex_input_attributes.data()}; + std::array vertex_input_attributes = { + {{0, 0, vk::Format::eR32G32B32Sfloat, offsetof(HPPVertex, pos)}, {1, 0, vk::Format::eR32G32Sfloat, offsetof(HPPVertex, uv)}}}; + vk::PipelineVertexInputStateCreateInfo vertex_input_state{.vertexBindingDescriptionCount = 1, + .pVertexBindingDescriptions = &vertex_input_binding, + .vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()), + .pVertexAttributeDescriptions = vertex_input_attributes.data()}; vk::PipelineColorBlendAttachmentState blend_attachment_state{.colorWriteMask = vk::FlagTraits::allFlags}; vk::PipelineDepthStencilStateCreateInfo depth_stencil_state{ .depthTestEnable = true, .depthWriteEnable = true, .depthCompareOp = vk::CompareOp::eGreater, .back = {.compareOp = vk::CompareOp::eAlways}}; - gatherPass.first_pipeline = vkb::common::create_graphics_pipeline(device, - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - {}, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - gatherPass.pipeline_layout, - gatherPass.render_pass); + gatherPass.first_pipeline = + vkb::common::create_graphics_pipeline(device, pipeline_cache, shader_stages, vertex_input_state, vk::PrimitiveTopology::eTriangleList, {}, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, {blend_attachment_state}, + depth_stencil_state, gatherPass.pipeline_layout, gatherPass.render_pass); shader_stages[1] = load_shader("oit_depth_peeling/gather.frag.spv", vk::ShaderStageFlagBits::eFragment); - gatherPass.pipeline = vkb::common::create_graphics_pipeline(device, - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - {}, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - gatherPass.pipeline_layout, - gatherPass.render_pass); + gatherPass.pipeline = + vkb::common::create_graphics_pipeline(device, pipeline_cache, shader_stages, vertex_input_state, vk::PrimitiveTopology::eTriangleList, {}, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, {blend_attachment_state}, + depth_stencil_state, gatherPass.pipeline_layout, gatherPass.render_pass); } void HPPOITDepthPeeling::create_gather_pass_render_pass() @@ -473,31 +418,25 @@ void HPPOITDepthPeeling::create_images(const uint32_t width, const uint32_t heig const vk::Extent3D image_extent = {width, height, 1}; for (uint32_t i = 0; i < kLayerMaxCount; ++i) { - layers[i].image = std::make_unique(get_device(), - image_extent, - vk::Format::eR8G8B8A8Unorm, + layers[i].image = std::make_unique(get_device(), image_extent, vk::Format::eR8G8B8A8Unorm, vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment, - VMA_MEMORY_USAGE_GPU_ONLY, - vk::SampleCountFlagBits::e1); + VMA_MEMORY_USAGE_GPU_ONLY, vk::SampleCountFlagBits::e1); layers[i].image_view = std::make_unique(*layers[i].image, vk::ImageViewType::e2D, vk::Format::eR8G8B8A8Unorm); } for (uint32_t i = 0; i < kDepthCount; ++i) { - depths[i].image = std::make_unique(get_device(), - image_extent, - vk::Format::eD32Sfloat, + depths[i].image = std::make_unique(get_device(), image_extent, vk::Format::eD32Sfloat, vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eDepthStencilAttachment, - VMA_MEMORY_USAGE_GPU_ONLY, - vk::SampleCountFlagBits::e1); + VMA_MEMORY_USAGE_GPU_ONLY, vk::SampleCountFlagBits::e1); depths[i].image_view = std::make_unique(*depths[i].image, vk::ImageViewType::e2D, vk::Format::eD32Sfloat); } } void HPPOITDepthPeeling::create_point_sampler() { - point_sampler = vkb::common::create_sampler( - get_device().get_handle(), vk::Filter::eNearest, vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest, vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); + point_sampler = vkb::common::create_sampler(get_device().get_handle(), vk::Filter::eNearest, vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest, + vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); } void HPPOITDepthPeeling::create_scene_constants_buffer() @@ -528,8 +467,7 @@ void HPPOITDepthPeeling::update_descriptors() for (uint32_t i = 0; i < kDepthCount; ++i) { - vk::DescriptorImageInfo depth_texture_descriptor{point_sampler, - depths[(i + 1) % kDepthCount].image_view->get_handle(), + vk::DescriptorImageInfo depth_texture_descriptor{point_sampler, depths[(i + 1) % kDepthCount].image_view->get_handle(), vk::ImageLayout::eDepthStencilReadOnlyOptimal}; std::array write_descriptor_sets = {{{.dstSet = depths[i].gather_descriptor_set, @@ -545,8 +483,7 @@ void HPPOITDepthPeeling::update_descriptors() device.updateDescriptorSets(write_descriptor_sets, {}); } - vk::DescriptorImageInfo background_texture_descriptor{background.texture.sampler, - background.texture.image->get_vk_image_view().get_handle(), + vk::DescriptorImageInfo background_texture_descriptor{background.texture.sampler, background.texture.image->get_vk_image_view().get_handle(), vk::ImageLayout::eShaderReadOnlyOptimal}; std::array layer_texture_descriptor; diff --git a/samples/api/hpp_oit_linked_lists/hpp_oit_linked_lists.cpp b/samples/api/hpp_oit_linked_lists/hpp_oit_linked_lists.cpp index f03f286b0c..7d27816685 100644 --- a/samples/api/hpp_oit_linked_lists/hpp_oit_linked_lists.cpp +++ b/samples/api/hpp_oit_linked_lists/hpp_oit_linked_lists.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA +/* Copyright (c) 2023-2026, NVIDIA * * SPDX-License-Identifier: Apache-2.0 * @@ -100,13 +100,10 @@ void HPPOITLinkedLists::build_command_buffers() { vk::CommandBufferBeginInfo command_buffer_begin_info; - vk::RenderPassBeginInfo gather_render_pass_begin_info{.renderPass = gather_render_pass, - .framebuffer = gather_framebuffer, - .renderArea = {{0, 0}, extent}}; + vk::RenderPassBeginInfo gather_render_pass_begin_info{.renderPass = gather_render_pass, .framebuffer = gather_framebuffer, .renderArea = {{0, 0}, extent}}; - std::array combine_clear_values = - {{vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 0.0f}})), - vk::ClearDepthStencilValue{0.0f, 0}}}; + std::array combine_clear_values = { + {vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 0.0f}})), vk::ClearDepthStencilValue{0.0f, 0}}}; vk::RenderPassBeginInfo combine_render_pass_begin_info{.renderPass = render_pass, .renderArea = {{0, 0}, extent}, .clearValueCount = static_cast(combine_clear_values.size()), @@ -132,15 +129,9 @@ void HPPOITLinkedLists::build_command_buffers() } command_buffer.endRenderPass(); - vkb::common::image_layout_transition(command_buffer, - linked_list_head_image->get_handle(), - vk::PipelineStageFlagBits::eFragmentShader, - vk::PipelineStageFlagBits::eFragmentShader, - vk::AccessFlagBits::eShaderWrite, - vk::AccessFlagBits::eShaderRead, - vk::ImageLayout::eGeneral, - vk::ImageLayout::eGeneral, - {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}); + vkb::common::image_layout_transition(command_buffer, linked_list_head_image->get_handle(), vk::PipelineStageFlagBits::eFragmentShader, + vk::PipelineStageFlagBits::eFragmentShader, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead, + vk::ImageLayout::eGeneral, vk::ImageLayout::eGeneral, {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}); // Combine pass combine_render_pass_begin_info.framebuffer = framebuffers[i]; @@ -201,15 +192,9 @@ void HPPOITLinkedLists::clear_sized_resources() command_buffer.fillBuffer(fragment_counter->get_handle(), 0, sizeof(glm::uint), 0); vk::ImageSubresourceRange subresource_range{vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}; - vkb::common::image_layout_transition(command_buffer, - linked_list_head_image->get_handle(), - vk::PipelineStageFlagBits::eBottomOfPipe, - vk::PipelineStageFlagBits::eTransfer, - vk::AccessFlagBits::eMemoryWrite, - vk::AccessFlagBits::eTransferWrite, - vk::ImageLayout::eUndefined, - vk::ImageLayout::eGeneral, - subresource_range); + vkb::common::image_layout_transition(command_buffer, linked_list_head_image->get_handle(), vk::PipelineStageFlagBits::eBottomOfPipe, + vk::PipelineStageFlagBits::eTransfer, vk::AccessFlagBits::eMemoryWrite, vk::AccessFlagBits::eTransferWrite, + vk::ImageLayout::eUndefined, vk::ImageLayout::eGeneral, subresource_range); vk::ClearColorValue linked_lists_clear_value(kLinkedListEndSentinel, kLinkedListEndSentinel, kLinkedListEndSentinel, kLinkedListEndSentinel); command_buffer.clearColorImage(linked_list_head_image->get_handle(), vk::ImageLayout::eGeneral, linked_lists_clear_value, subresource_range); @@ -229,8 +214,8 @@ void HPPOITLinkedLists::create_constant_buffers() { scene_constants = std::make_unique(get_device(), sizeof(SceneConstants), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); - instance_data = std::make_unique( - get_device(), sizeof(Instance) * kInstanceCount, vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); + instance_data = std::make_unique(get_device(), sizeof(Instance) * kInstanceCount, vk::BufferUsageFlagBits::eUniformBuffer, + VMA_MEMORY_USAGE_CPU_TO_GPU); } vk::DescriptorPool HPPOITLinkedLists::create_descriptor_pool() @@ -240,9 +225,8 @@ vk::DescriptorPool HPPOITLinkedLists::create_descriptor_pool() {vk::DescriptorType::eStorageBuffer, 2}, {vk::DescriptorType::eCombinedImageSampler, 1}}}; - vk::DescriptorPoolCreateInfo descriptor_pool_create_info{.maxSets = 1, - .poolSizeCount = static_cast(pool_sizes.size()), - .pPoolSizes = pool_sizes.data()}; + vk::DescriptorPoolCreateInfo descriptor_pool_create_info{ + .maxSets = 1, .poolSizeCount = static_cast(pool_sizes.size()), .pPoolSizes = pool_sizes.data()}; return get_device().get_handle().createDescriptorPool(descriptor_pool_create_info); } @@ -270,12 +254,9 @@ void HPPOITLinkedLists::create_fragment_resources(vk::Extent2D const &extent) { const vk::Extent3D image_extent{extent.width, extent.height, 1}; const vk::Format image_format{vk::Format::eR32Uint}; - linked_list_head_image = std::make_unique(get_device(), - image_extent, - image_format, - vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eTransferDst, - VMA_MEMORY_USAGE_GPU_ONLY, - vk::SampleCountFlagBits::e1); + linked_list_head_image = + std::make_unique(get_device(), image_extent, image_format, vk::ImageUsageFlagBits::eStorage | vk::ImageUsageFlagBits::eTransferDst, + VMA_MEMORY_USAGE_GPU_ONLY, vk::SampleCountFlagBits::e1); linked_list_head_image_view = std::make_unique(*linked_list_head_image, vk::ImageViewType::e2D, image_format); fragment_max_count = extent.width * extent.height * kFragmentsPerPixelAverage; @@ -319,40 +300,24 @@ void HPPOITLinkedLists::create_pipelines() .vertexAttributeDescriptionCount = 1, .pVertexAttributeDescriptions = &gather_vertex_input_attribute}; - gather_pipeline = vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - gather_shader_stages, - gather_vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, + gather_pipeline = vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, gather_shader_stages, gather_vertex_input_state, + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, + vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, pipeline_layout, gather_render_pass); - std::vector background_shader_stages = {load_shader("oit_linked_lists/fullscreen.vert.spv", vk::ShaderStageFlagBits::eVertex), - load_shader("oit_linked_lists/background.frag.spv", vk::ShaderStageFlagBits::eFragment)}; - vk::PipelineVertexInputStateCreateInfo vertex_input_state; - - background_pipeline = vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - background_shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); - - std::vector combine_shader_stages = {load_shader("oit_linked_lists/combine.vert.spv", vk::ShaderStageFlagBits::eVertex), - load_shader("oit_linked_lists/combine.frag.spv", vk::ShaderStageFlagBits::eFragment)}; + std::vector background_shader_stages = { + load_shader("oit_linked_lists/fullscreen.vert.spv", vk::ShaderStageFlagBits::eVertex), + load_shader("oit_linked_lists/background.frag.spv", vk::ShaderStageFlagBits::eFragment)}; + vk::PipelineVertexInputStateCreateInfo vertex_input_state; + + background_pipeline = + vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, background_shader_stages, vertex_input_state, + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, + vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, pipeline_layout, render_pass); + + std::vector combine_shader_stages = { + load_shader("oit_linked_lists/combine.vert.spv", vk::ShaderStageFlagBits::eVertex), + load_shader("oit_linked_lists/combine.frag.spv", vk::ShaderStageFlagBits::eFragment)}; vk::PipelineColorBlendAttachmentState combine_blend_attachment_state{true, vk::BlendFactor::eSrcAlpha, @@ -364,19 +329,9 @@ void HPPOITLinkedLists::create_pipelines() vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA}; - combine_pipeline = vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - combine_shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {combine_blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + combine_pipeline = vkb::common::create_graphics_pipeline( + get_device().get_handle(), pipeline_cache, combine_shader_stages, vertex_input_state, vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, + vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, {combine_blend_attachment_state}, depth_stencil_state, pipeline_layout, render_pass); } void HPPOITLinkedLists::create_sized_objects(vk::Extent2D const &extent) @@ -447,10 +402,9 @@ void HPPOITLinkedLists::update_descriptors() vk::DescriptorImageInfo linked_list_head_image_view_descriptor{nullptr, linked_list_head_image_view->get_handle(), vk::ImageLayout::eGeneral}; vk::DescriptorBufferInfo fragment_buffer_descriptor{fragment_buffer->get_handle(), 0, vk::WholeSize}; vk::DescriptorBufferInfo fragment_counter_descriptor{fragment_counter->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo background_texture_descriptor{background_texture.sampler, - background_texture.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - background_texture.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo background_texture_descriptor{ + background_texture.sampler, background_texture.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, background_texture.image->get_vk_image_view().get_format())}; std::array write_descriptor_sets = {{{.dstSet = descriptor_set, .dstBinding = 0, diff --git a/samples/api/hpp_separate_image_sampler/hpp_separate_image_sampler.cpp b/samples/api/hpp_separate_image_sampler/hpp_separate_image_sampler.cpp index af69bf3797..8c1b7ca057 100644 --- a/samples/api/hpp_separate_image_sampler/hpp_separate_image_sampler.cpp +++ b/samples/api/hpp_separate_image_sampler/hpp_separate_image_sampler.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -193,9 +193,8 @@ vk::DescriptorPool HPPSeparateImageSampler::create_descriptor_pool() std::array pool_sizes = { {{vk::DescriptorType::eUniformBuffer, 1}, {vk::DescriptorType::eSampledImage, 1}, {vk::DescriptorType::eSampler, 2}}}; - vk::DescriptorPoolCreateInfo descriptor_pool_create_info{.maxSets = 3, - .poolSizeCount = static_cast(pool_sizes.size()), - .pPoolSizes = pool_sizes.data()}; + vk::DescriptorPoolCreateInfo descriptor_pool_create_info{ + .maxSets = 3, .poolSizeCount = static_cast(pool_sizes.size()), .pPoolSizes = pool_sizes.data()}; return get_device().get_handle().createDescriptorPool(descriptor_pool_create_info); } @@ -228,19 +227,9 @@ vk::Pipeline HPPSeparateImageSampler::create_graphics_pipeline() depth_stencil_state.depthCompareOp = vk::CompareOp::eGreater; depth_stencil_state.back.compareOp = vk::CompareOp::eGreater; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, input_state, vk::PrimitiveTopology::eTriangleList, 0, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, + {blend_attachment_state}, depth_stencil_state, pipeline_layout, render_pass); } vk::PipelineLayout HPPSeparateImageSampler::create_pipeline_layout(std::vector const &descriptor_set_layouts) @@ -254,11 +243,7 @@ vk::PipelineLayout HPPSeparateImageSampler::create_pipeline_layout(std::vectorget_format(), - filter, - vk::SamplerAddressMode::eRepeat, + get_device().get_gpu().get_handle(), get_device().get_handle(), texture.image->get_format(), filter, vk::SamplerAddressMode::eRepeat, get_device().get_gpu().get_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f, static_cast(texture.image->get_mipmaps().size())); } @@ -289,12 +274,10 @@ void HPPSeparateImageSampler::draw() void HPPSeparateImageSampler::generate_quad() { // Setup vertices for a single uv-mapped quad made from two triangles - std::vector vertices = - { - {{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, - {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; + std::vector vertices = {{{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, + {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; // Setup indices std::vector indices = {0, 1, 2, 2, 3, 0}; @@ -306,16 +289,12 @@ void HPPSeparateImageSampler::generate_quad() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory // Vertex buffer - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eVertexBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + vertex_buffer = std::make_unique( + get_device(), vertex_buffer_size, vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eVertexBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eIndexBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + index_buffer = std::make_unique( + get_device(), index_buffer_size, vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eIndexBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); } @@ -342,19 +321,18 @@ void HPPSeparateImageSampler::update_base_descriptor_set() vk::DescriptorImageInfo image_info{{}, texture.image->get_vk_image_view().get_handle(), vk::ImageLayout::eShaderReadOnlyOptimal}; // Sampled image descriptor - std::array write_descriptor_sets = { - { - {.dstSet = base_descriptor_set, - .dstBinding = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &buffer_descriptor}, // Binding 0 : Vertex shader uniform buffer - {.dstSet = base_descriptor_set, - .dstBinding = 1, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eSampledImage, - .pImageInfo = &image_info} // Binding 1 : Fragment shader sampled image - }}; + std::array write_descriptor_sets = {{ + {.dstSet = base_descriptor_set, + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_descriptor}, // Binding 0 : Vertex shader uniform buffer + {.dstSet = base_descriptor_set, + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eSampledImage, + .pImageInfo = &image_info} // Binding 1 : Fragment shader sampled image + }}; get_device().get_handle().updateDescriptorSets(write_descriptor_sets, {}); } @@ -365,8 +343,11 @@ void HPPSeparateImageSampler::update_sampler_descriptor_set(size_t index) // Descriptor info only references the sampler vk::DescriptorImageInfo sampler_info{samplers[index]}; - vk::WriteDescriptorSet sampler_write_descriptor_set{ - .dstSet = sampler_descriptor_sets[index], .dstBinding = 0, .descriptorCount = 1, .descriptorType = vk::DescriptorType::eSampler, .pImageInfo = &sampler_info}; + vk::WriteDescriptorSet sampler_write_descriptor_set{.dstSet = sampler_descriptor_sets[index], + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eSampler, + .pImageInfo = &sampler_info}; get_device().get_handle().updateDescriptorSets(sampler_write_descriptor_set, {}); } diff --git a/samples/api/hpp_terrain_tessellation/hpp_terrain_tessellation.cpp b/samples/api/hpp_terrain_tessellation/hpp_terrain_tessellation.cpp index 459ac27850..aa0d6bcc51 100644 --- a/samples/api/hpp_terrain_tessellation/hpp_terrain_tessellation.cpp +++ b/samples/api/hpp_terrain_tessellation/hpp_terrain_tessellation.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -209,11 +209,10 @@ vk::DescriptorPool HPPTerrainTessellation::create_descriptor_pool() vk::DescriptorSetLayout HPPTerrainTessellation::create_sky_sphere_descriptor_set_layout() { - std::array layout_bindings = { - {{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex}, - {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}}}; - vk::DescriptorSetLayoutCreateInfo skysphere_descriptor_layout{.bindingCount = static_cast(layout_bindings.size()), - .pBindings = layout_bindings.data()}; + std::array layout_bindings = {{{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex}, + {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}}}; + vk::DescriptorSetLayoutCreateInfo skysphere_descriptor_layout{.bindingCount = static_cast(layout_bindings.size()), + .pBindings = layout_bindings.data()}; return get_device().get_handle().createDescriptorSetLayout(skysphere_descriptor_layout); } @@ -250,19 +249,9 @@ vk::Pipeline HPPTerrainTessellation::create_sky_sphere_pipeline() depth_stencil_state.front = depth_stencil_state.back; // For the sky_sphere use triangle list topology - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eBack, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - sky_sphere.pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline( + get_device().get_handle(), pipeline_cache, shader_stages, vertex_input_state, vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, + vk::CullModeFlagBits::eBack, vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, sky_sphere.pipeline_layout, render_pass); } vk::DescriptorSetLayout HPPTerrainTessellation::create_terrain_descriptor_set_layout() @@ -270,9 +259,7 @@ vk::DescriptorSetLayout HPPTerrainTessellation::create_terrain_descriptor_set_la // Terrain std::array layout_bindings = { {{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eTessellationControl | vk::ShaderStageFlagBits::eTessellationEvaluation}, - {1, - vk::DescriptorType::eCombinedImageSampler, - 1, + {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eTessellationControl | vk::ShaderStageFlagBits::eTessellationEvaluation | vk::ShaderStageFlagBits::eFragment}, {2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}}}; @@ -308,19 +295,11 @@ vk::Pipeline HPPTerrainTessellation::create_terrain_pipeline(vk::PolygonMode pol depth_stencil_state.back.compareOp = vk::CompareOp::eGreater; depth_stencil_state.front = depth_stencil_state.back; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - terrain.shader_stages, - vertex_input_state, + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, terrain.shader_stages, vertex_input_state, vk::PrimitiveTopology::ePatchList, 4, // we render the terrain as a grid of quad patches - polygon_mode, - vk::CullModeFlagBits::eBack, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - terrain.pipeline_layout, - render_pass); + polygon_mode, vk::CullModeFlagBits::eBack, vk::FrontFace::eCounterClockwise, {blend_attachment_state}, + depth_stencil_state, terrain.pipeline_layout, render_pass); } void HPPTerrainTessellation::draw() @@ -336,9 +315,8 @@ void HPPTerrainTessellation::draw() if (statistics.query_supported) { // Read query results for displaying in next frame - auto result = get_device() - .get_handle() - .getQueryPoolResult>(statistics.query_pool, 0, 1, sizeof(statistics.results), vk::QueryResultFlagBits::e64); + auto result = get_device().get_handle().getQueryPoolResult>(statistics.query_pool, 0, 1, sizeof(statistics.results), + vk::QueryResultFlagBits::e64); if (result.result == vk::Result::eSuccess) { statistics.results = result.value; @@ -448,10 +426,12 @@ void HPPTerrainTessellation::load_assets() sky_sphere.texture = load_texture("textures/skysphere_rgba.ktx", vkb::scene_graph::components::HPPImage::Color); // Terrain textures are stored in a texture array with layers corresponding to terrain height; create a repeating sampler - terrain.terrain_array = load_texture_array("textures/terrain_texturearray_rgba.ktx", vkb::scene_graph::components::HPPImage::Color, vk::SamplerAddressMode::eRepeat); + terrain.terrain_array = + load_texture_array("textures/terrain_texturearray_rgba.ktx", vkb::scene_graph::components::HPPImage::Color, vk::SamplerAddressMode::eRepeat); // Height data is stored in a one-channel texture; create a mirroring sampler - terrain.height_map = load_texture("textures/terrain_heightmap_r16.ktx", vkb::scene_graph::components::HPPImage::Other, vk::SamplerAddressMode::eMirroredRepeat); + terrain.height_map = + load_texture("textures/terrain_heightmap_r16.ktx", vkb::scene_graph::components::HPPImage::Other, vk::SamplerAddressMode::eMirroredRepeat); } void HPPTerrainTessellation::prepare_camera() @@ -478,9 +458,7 @@ void HPPTerrainTessellation::prepare_statistics() if (statistics.query_supported) { // Create query pool - statistics.query_pool = vkb::common::create_query_pool(get_device().get_handle(), - vk::QueryType::ePipelineStatistics, - 2, + statistics.query_pool = vkb::common::create_query_pool(get_device().get_handle(), vk::QueryType::ePipelineStatistics, 2, vk::QueryPipelineStatisticFlagBits::eVertexShaderInvocations | vk::QueryPipelineStatisticFlagBits::eTessellationEvaluationShaderInvocations); } @@ -504,12 +482,12 @@ void HPPTerrainTessellation::prepare_terrain() void HPPTerrainTessellation::prepare_uniform_buffers() { // Shared tessellation shader stages uniform buffer - terrain.tessellation_buffer = - std::make_unique(get_device(), sizeof(terrain.tessellation), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); + terrain.tessellation_buffer = std::make_unique(get_device(), sizeof(terrain.tessellation), vk::BufferUsageFlagBits::eUniformBuffer, + VMA_MEMORY_USAGE_CPU_TO_GPU); // Skysphere vertex shader uniform buffer - sky_sphere.transform_buffer = - std::make_unique(get_device(), sizeof(sky_sphere.transform), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); + sky_sphere.transform_buffer = std::make_unique(get_device(), sizeof(sky_sphere.transform), vk::BufferUsageFlagBits::eUniformBuffer, + VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -557,10 +535,9 @@ void HPPTerrainTessellation::update_sky_sphere_descriptor_set() { vk::DescriptorBufferInfo skysphere_buffer_descriptor{sky_sphere.transform_buffer->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo skysphere_image_descriptor{sky_sphere.texture.sampler, - sky_sphere.texture.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - sky_sphere.texture.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo skysphere_image_descriptor{ + sky_sphere.texture.sampler, sky_sphere.texture.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, sky_sphere.texture.image->get_vk_image_view().get_format())}; std::array skysphere_write_descriptor_sets = {{{.dstSet = sky_sphere.descriptor_set, .dstBinding = 0, @@ -580,15 +557,13 @@ void HPPTerrainTessellation::update_terrain_descriptor_set() { vk::DescriptorBufferInfo terrain_buffer_descriptor{terrain.tessellation_buffer->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo heightmap_image_descriptor{terrain.height_map.sampler, - terrain.height_map.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - terrain.height_map.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo heightmap_image_descriptor{ + terrain.height_map.sampler, terrain.height_map.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, terrain.height_map.image->get_vk_image_view().get_format())}; - vk::DescriptorImageInfo terrainmap_image_descriptor{terrain.terrain_array.sampler, - terrain.terrain_array.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - terrain.terrain_array.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo terrainmap_image_descriptor{ + terrain.terrain_array.sampler, terrain.terrain_array.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, terrain.terrain_array.image->get_vk_image_view().get_format())}; std::array terrain_write_descriptor_sets = {{{.dstSet = terrain.descriptor_set, .dstBinding = 0, diff --git a/samples/api/hpp_texture_loading/hpp_texture_loading.cpp b/samples/api/hpp_texture_loading/hpp_texture_loading.cpp index 98770dc07a..3a22d55744 100644 --- a/samples/api/hpp_texture_loading/hpp_texture_loading.cpp +++ b/samples/api/hpp_texture_loading/hpp_texture_loading.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -203,19 +203,9 @@ vk::Pipeline HPPTextureLoading::create_pipeline() depth_stencil_state.depthCompareOp = vk::CompareOp::eGreater; depth_stencil_state.back.compareOp = vk::CompareOp::eGreater; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, vertex_input_state, + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, + vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, pipeline_layout, render_pass); } void HPPTextureLoading::draw() @@ -265,14 +255,14 @@ void HPPTextureLoading::generate_quad() Vulkan offers two types of image tiling (memory layout): Linear tiled images: - These are stored as is and can be copied directly to. But due to the linear nature they're not a good match for GPUs and format and feature support is very limited. - It's not advised to use linear tiled images for anything else than copying from host to GPU if buffer copies are not an option. - Linear tiling is thus only implemented for learning purposes, one should always prefer optimal tiled image. + These are stored as is and can be copied directly to. But due to the linear nature they're not a good match for GPUs and format and feature support is + very limited. It's not advised to use linear tiled images for anything else than copying from host to GPU if buffer copies are not an option. Linear tiling + is thus only implemented for learning purposes, one should always prefer optimal tiled image. Optimal tiled images: - These are stored in an implementation specific layout matching the capability of the hardware. They usually support more formats and features and are much faster. - Optimal tiled images are stored on the device and not accessible by the host. So they can't be written directly to (like liner tiled images) and always require - some sort of data copy, either from a buffer or a linear tiled image. + These are stored in an implementation specific layout matching the capability of the hardware. They usually support more formats and features and are + much faster. Optimal tiled images are stored on the device and not accessible by the host. So they can't be written directly to (like liner tiled images) and + always require some sort of data copy, either from a buffer or a linear tiled image. In Short: Always use optimal tiled images for rendering. */ @@ -311,10 +301,9 @@ void HPPTextureLoading::load_texture() // Create a host-visible staging buffer that contains the raw image data // This buffer will be the data source for copying texture data to the optimal tiled image on the device // This buffer is used as a transfer source for the buffer copy - vk::BufferCreateInfo buffer_create_info{.size = ktx_texture->dataSize, - .usage = vk::BufferUsageFlagBits::eTransferSrc, - .sharingMode = vk::SharingMode::eExclusive}; - vk::Buffer staging_buffer = device.createBuffer(buffer_create_info); + vk::BufferCreateInfo buffer_create_info{ + .size = ktx_texture->dataSize, .usage = vk::BufferUsageFlagBits::eTransferSrc, .sharingMode = vk::SharingMode::eExclusive}; + vk::Buffer staging_buffer = device.createBuffer(buffer_create_info); // Get memory requirements for the staging buffer (alignment, memory type bits) vk::MemoryRequirements memory_requirements = device.getBufferMemoryRequirements(staging_buffer); @@ -411,7 +400,8 @@ void HPPTextureLoading::load_texture() // Insert a memory dependency at the proper pipeline stages that will execute the image layout transition // Source pipeline stage stage is copy command execution (VK_PIPELINE_STAGE_TRANSFER_BIT) // Destination pipeline stage fragment shader access (VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) - copy_command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, {}, nullptr, nullptr, image_memory_barrier); + copy_command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, {}, nullptr, nullptr, + image_memory_barrier); // Store current layout for later reuse texture.image_layout = vk::ImageLayout::eShaderReadOnlyOptimal; @@ -493,8 +483,8 @@ void HPPTextureLoading::load_texture() // Create a texture sampler // In Vulkan textures are accessed by samplers - // This separates all the sampling information from the texture data. This means you could have multiple sampler objects for the same texture with different settings - // Note: Similar to the samplers available with OpenGL 3.3 + // This separates all the sampling information from the texture data. This means you could have multiple sampler objects for the same texture with different + // settings Note: Similar to the samplers available with OpenGL 3.3 // Enable anisotropic filtering // This feature is optional, so we must check if it's supported on the device @@ -505,9 +495,9 @@ void HPPTextureLoading::load_texture() maxAnisotropy = get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy; } - texture.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), - format, vk::Filter::eLinear, vk::SamplerAddressMode::eClampToEdge, - maxAnisotropy, (use_staging) ? static_cast(texture.mip_levels) : 0.0f); + texture.sampler = + vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), format, vk::Filter::eLinear, + vk::SamplerAddressMode::eClampToEdge, maxAnisotropy, (use_staging) ? static_cast(texture.mip_levels) : 0.0f); // Create image view // Textures are not directly accessed by the shaders and diff --git a/samples/api/hpp_texture_loading/hpp_texture_loading.h b/samples/api/hpp_texture_loading/hpp_texture_loading.h index 9170c73bb7..346f50793c 100644 --- a/samples/api/hpp_texture_loading/hpp_texture_loading.h +++ b/samples/api/hpp_texture_loading/hpp_texture_loading.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2021-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -31,7 +31,8 @@ class HPPTextureLoading : public HPPApiVulkanSample private: // Contains all Vulkan objects that are required to store and use a texture - // Note that this repository contains a texture class (vulkan_texture.h) that encapsulates texture loading functionality in a class that is used in subsequent demos + // Note that this repository contains a texture class (vulkan_texture.h) that encapsulates texture loading functionality in a class that is used in + // subsequent demos struct Texture { vk::DeviceMemory device_memory; diff --git a/samples/api/hpp_texture_mipmap_generation/hpp_texture_mipmap_generation.cpp b/samples/api/hpp_texture_mipmap_generation/hpp_texture_mipmap_generation.cpp index 166852d05b..e84eed1519 100644 --- a/samples/api/hpp_texture_mipmap_generation/hpp_texture_mipmap_generation.cpp +++ b/samples/api/hpp_texture_mipmap_generation/hpp_texture_mipmap_generation.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2022-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -181,9 +181,8 @@ vk::DescriptorPool HPPTextureMipMapGeneration::create_descriptor_pool() std::array pool_sizes = { {{vk::DescriptorType::eUniformBuffer, 1}, {vk::DescriptorType::eSampledImage, 1}, {vk::DescriptorType::eSampler, 3}}}; - vk::DescriptorPoolCreateInfo descriptor_pool_create_info{.maxSets = 2, - .poolSizeCount = static_cast(pool_sizes.size()), - .pPoolSizes = pool_sizes.data()}; + vk::DescriptorPoolCreateInfo descriptor_pool_create_info{ + .maxSets = 2, .poolSizeCount = static_cast(pool_sizes.size()), .pPoolSizes = pool_sizes.data()}; return get_device().get_handle().createDescriptorPool(descriptor_pool_create_info); } @@ -191,9 +190,10 @@ vk::DescriptorPool HPPTextureMipMapGeneration::create_descriptor_pool() vk::DescriptorSetLayout HPPTextureMipMapGeneration::create_descriptor_set_layout() { std::array set_layout_bindings = { - {{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, // Binding 0 : Parameter uniform buffer - {1, vk::DescriptorType::eSampledImage, 1, vk::ShaderStageFlagBits::eFragment}, // Binding 1 : Fragment shader image sampler - {2, vk::DescriptorType::eSampler, 3, vk::ShaderStageFlagBits::eFragment}}}; // Binding 2 : Sampler array (3 descriptors) + {{0, vk::DescriptorType::eUniformBuffer, 1, + vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, // Binding 0 : Parameter uniform buffer + {1, vk::DescriptorType::eSampledImage, 1, vk::ShaderStageFlagBits::eFragment}, // Binding 1 : Fragment shader image sampler + {2, vk::DescriptorType::eSampler, 3, vk::ShaderStageFlagBits::eFragment}}}; // Binding 2 : Sampler array (3 descriptors) vk::DescriptorSetLayoutCreateInfo descriptor_layout{.bindingCount = static_cast(set_layout_bindings.size()), .pBindings = set_layout_bindings.data()}; @@ -214,10 +214,10 @@ vk::Pipeline HPPTextureMipMapGeneration::create_pipeline() {0, 0, vk::Format::eR32G32B32Sfloat, 0}, // Position {1, 0, vk::Format::eR32G32Sfloat, sizeof(float) * 6}, // UV }}; - vk::PipelineVertexInputStateCreateInfo vertex_input_state{.vertexBindingDescriptionCount = 1, - .pVertexBindingDescriptions = &vertex_input_binding, + vk::PipelineVertexInputStateCreateInfo vertex_input_state{.vertexBindingDescriptionCount = 1, + .pVertexBindingDescriptions = &vertex_input_binding, .vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()), - .pVertexAttributeDescriptions = vertex_input_attributes.data()}; + .pVertexAttributeDescriptions = vertex_input_attributes.data()}; vk::PipelineColorBlendAttachmentState blend_attachment_state{.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA}; @@ -229,19 +229,9 @@ vk::Pipeline HPPTextureMipMapGeneration::create_pipeline() depth_stencil_state.back.compareOp = vk::CompareOp::eAlways; depth_stencil_state.front = depth_stencil_state.back; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eNone, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, vertex_input_state, + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, + vk::FrontFace::eCounterClockwise, {blend_attachment_state}, depth_stencil_state, pipeline_layout, render_pass); } void HPPTextureMipMapGeneration::draw() @@ -297,9 +287,9 @@ void HPPTextureMipMapGeneration::load_assets() vk::MemoryRequirements memory_requirements = device.getImageMemoryRequirements(texture.image); - vk::MemoryAllocateInfo memory_allocation{.allocationSize = memory_requirements.size, - .memoryTypeIndex = get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, - vk::MemoryPropertyFlagBits::eDeviceLocal)}; + vk::MemoryAllocateInfo memory_allocation{ + .allocationSize = memory_requirements.size, + .memoryTypeIndex = get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal)}; texture.device_memory = device.allocateMemory(memory_allocation); device.bindImageMemory(texture.image, texture.device_memory, 0); @@ -331,31 +321,26 @@ void HPPTextureMipMapGeneration::load_assets() { vk::ImageBlit image_blit{ {vk::ImageAspectFlagBits::eColor, i - 1, 0, 1}, - {{{{}, - {static_cast(texture.extent.width >> (i - 1)), - static_cast(texture.extent.height >> (i - 1)), - static_cast(1)}}}}, + {{{{}, {static_cast(texture.extent.width >> (i - 1)), static_cast(texture.extent.height >> (i - 1)), static_cast(1)}}}}, {vk::ImageAspectFlagBits::eColor, i, 0, 1}, {{{{}, {static_cast(texture.extent.width >> i), static_cast(texture.extent.height >> i), static_cast(1)}}}}}; // Prepare current mip level as image blit destination vk::ImageSubresourceRange image_subresource_range{vk::ImageAspectFlagBits::eColor, i, 1, 0, 1}; - vkb::common::image_layout_transition( - blit_command, texture.image, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, image_subresource_range); + vkb::common::image_layout_transition(blit_command, texture.image, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, + image_subresource_range); // Blit from previous level - blit_command.blitImage(texture.image, vk::ImageLayout::eTransferSrcOptimal, texture.image, vk::ImageLayout::eTransferDstOptimal, image_blit, vk::Filter::eLinear); + blit_command.blitImage(texture.image, vk::ImageLayout::eTransferSrcOptimal, texture.image, vk::ImageLayout::eTransferDstOptimal, image_blit, + vk::Filter::eLinear); // Prepare current mip level as image blit source for next level - vkb::common::image_layout_transition( - blit_command, texture.image, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eTransferSrcOptimal, image_subresource_range); + vkb::common::image_layout_transition(blit_command, texture.image, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eTransferSrcOptimal, + image_subresource_range); } // After the loop, all mip layers are in TRANSFER_SRC layout, so transition all to SHADER_READ - vkb::common::image_layout_transition(blit_command, - texture.image, - vk::ImageLayout::eTransferSrcOptimal, - vk::ImageLayout::eShaderReadOnlyOptimal, + vkb::common::image_layout_transition(blit_command, texture.image, vk::ImageLayout::eTransferSrcOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, {vk::ImageAspectFlagBits::eColor, 0, texture.mip_levels, 0, 1}); get_device().flush_command_buffer(blit_command, queue, true); @@ -364,27 +349,22 @@ void HPPTextureMipMapGeneration::load_assets() // Create samplers for different mip map demonstration cases // Without mip mapping - samplers[0] = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), format, - vk::Filter::eLinear, vk::SamplerAddressMode::eRepeat, 1.0f, 0.0f); + samplers[0] = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), format, vk::Filter::eLinear, + vk::SamplerAddressMode::eRepeat, 1.0f, 0.0f); // With mip mapping - samplers[1] = - vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), format, - vk::Filter::eLinear, vk::SamplerAddressMode::eRepeat, 1.0f, static_cast(texture.mip_levels)); + samplers[1] = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), format, vk::Filter::eLinear, + vk::SamplerAddressMode::eRepeat, 1.0f, static_cast(texture.mip_levels)); // With mip mapping and anisotropic filtering (when supported) samplers[2] = vkb::common::create_sampler( - get_device().get_gpu().get_handle(), - get_device().get_handle(), - format, - vk::Filter::eLinear, - vk::SamplerAddressMode::eRepeat, + get_device().get_gpu().get_handle(), get_device().get_handle(), format, vk::Filter::eLinear, vk::SamplerAddressMode::eRepeat, get_device().get_gpu().get_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f, static_cast(texture.mip_levels)); // Create image view - texture.view = vkb::common::create_image_view( - get_device().get_handle(), texture.image, vk::ImageViewType::e2D, format, vk::ImageAspectFlagBits::eColor, 0, texture.mip_levels); + texture.view = vkb::common::create_image_view(get_device().get_handle(), texture.image, vk::ImageViewType::e2D, format, vk::ImageAspectFlagBits::eColor, 0, + texture.mip_levels); } void HPPTextureMipMapGeneration::prepare_camera() @@ -397,10 +377,7 @@ void HPPTextureMipMapGeneration::prepare_camera() void HPPTextureMipMapGeneration::prepare_uniform_buffers() { // Shared parameter uniform buffer block - uniform_buffer = std::make_unique(get_device(), - sizeof(ubo), - vk::BufferUsageFlagBits::eUniformBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer = std::make_unique(get_device(), sizeof(ubo), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -425,7 +402,7 @@ void HPPTextureMipMapGeneration::update_descriptor_set() .dstBinding = 1, .descriptorCount = 1, .descriptorType = vk::DescriptorType::eSampledImage, - .pImageInfo = &image_descriptor}, // Binding 1 : Fragment shader texture sampler + .pImageInfo = &image_descriptor}, // Binding 1 : Fragment shader texture sampler {.dstSet = descriptor_set, .dstBinding = 2, .descriptorCount = static_cast(sampler_descriptors.size()), diff --git a/samples/api/hpp_timestamp_queries/hpp_timestamp_queries.cpp b/samples/api/hpp_timestamp_queries/hpp_timestamp_queries.cpp index 3dd66f587f..4959c24b1a 100644 --- a/samples/api/hpp_timestamp_queries/hpp_timestamp_queries.cpp +++ b/samples/api/hpp_timestamp_queries/hpp_timestamp_queries.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -59,7 +59,8 @@ bool HPPTimestampQueries::prepare(const vkb::ApplicationOptions &options) if (!device_limits.timestampComputeAndGraphics) { // Check if the graphics queue used in this sample supports time stamps - vk::QueueFamilyProperties const &graphics_queue_family_properties = get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0).get_properties(); + vk::QueueFamilyProperties const &graphics_queue_family_properties = + get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0).get_properties(); if (graphics_queue_family_properties.timestampValidBits == 0) { throw std::runtime_error{"The selected graphics queue family does not support timestamp queries!"}; @@ -191,8 +192,8 @@ void HPPTimestampQueries::build_command_buffers() Third render pass: Scene rendering with applied second bloom pass (when enabled) */ { - std::array clear_values = {{vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 0.0f}})), - vk::ClearDepthStencilValue{0.0f, 0}}}; + std::array clear_values = { + {vk::ClearColorValue(std::array({{0.0f, 0.0f, 0.0f, 0.0f}})), vk::ClearDepthStencilValue{0.0f, 0}}}; // Final composition command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, time_stamps.query_pool, bloom.enabled ? 4 : 2); @@ -262,11 +263,14 @@ void HPPTimestampQueries::on_update_ui_overlay(vkb::Drawer &drawer) // The timestampPeriod property of the device tells how many nanoseconds such a timestep translates to on the selected device float timestampFrequency = get_device().get_gpu().get_properties().limits.timestampPeriod; - drawer.text("Pass 1: Offscreen scene rendering: %.3f ms", static_cast(time_stamps.values[1] - time_stamps.values[0]) * timestampFrequency / 1000000.0f); - drawer.text("Pass 2: %s %.3f ms", (bloom.enabled ? "First bloom pass" : "Scene display"), static_cast(time_stamps.values[3] - time_stamps.values[2]) * timestampFrequency / 1000000.0f); + drawer.text("Pass 1: Offscreen scene rendering: %.3f ms", + static_cast(time_stamps.values[1] - time_stamps.values[0]) * timestampFrequency / 1000000.0f); + drawer.text("Pass 2: %s %.3f ms", (bloom.enabled ? "First bloom pass" : "Scene display"), + static_cast(time_stamps.values[3] - time_stamps.values[2]) * timestampFrequency / 1000000.0f); if (bloom.enabled) { - drawer.text("Pass 3: Second bloom pass %.3f ms", static_cast(time_stamps.values[5] - time_stamps.values[4]) * timestampFrequency / 1000000.0f); + drawer.text("Pass 3: Second bloom pass %.3f ms", + static_cast(time_stamps.values[5] - time_stamps.values[4]) * timestampFrequency / 1000000.0f); drawer.set_dirty(true); } } @@ -288,9 +292,9 @@ vk::DeviceMemory HPPTimestampQueries::allocate_memory(vk::Image image) { vk::MemoryRequirements memory_requirements = get_device().get_handle().getImageMemoryRequirements(image); - vk::MemoryAllocateInfo memory_allocate_info{.allocationSize = memory_requirements.size, - .memoryTypeIndex = get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, - vk::MemoryPropertyFlagBits::eDeviceLocal)}; + vk::MemoryAllocateInfo memory_allocate_info{ + .allocationSize = memory_requirements.size, + .memoryTypeIndex = get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal)}; return get_device().get_handle().allocateMemory(memory_allocate_info); } @@ -341,18 +345,9 @@ vk::Pipeline HPPTimestampQueries::create_bloom_pipeline(uint32_t direction) depth_stencil_state.front = depth_stencil_state.back; // Empty vertex input state, full screen triangles are generated by the vertex shader - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - {}, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eFront, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - bloom.pipeline_layout, + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, {}, vk::PrimitiveTopology::eTriangleList, 0, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eFront, vk::FrontFace::eCounterClockwise, + {blend_attachment_state}, depth_stencil_state, bloom.pipeline_layout, direction == 1 ? render_pass : filter_pass.render_pass); } @@ -371,19 +366,9 @@ vk::Pipeline HPPTimestampQueries::create_composition_pipeline() depth_stencil_state.front = depth_stencil_state.back; // Empty vertex input state, full screen triangles are generated by the vertex shader - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - {}, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eFront, - vk::FrontFace::eCounterClockwise, - {blend_attachment_state}, - depth_stencil_state, - composition.pipeline_layout, - render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, {}, vk::PrimitiveTopology::eTriangleList, 0, + vk::PolygonMode::eFill, vk::CullModeFlagBits::eFront, vk::FrontFace::eCounterClockwise, + {blend_attachment_state}, depth_stencil_state, composition.pipeline_layout, render_pass); } vk::RenderPass HPPTimestampQueries::create_filter_render_pass() @@ -457,19 +442,9 @@ vk::Pipeline HPPTimestampQueries::create_models_pipeline(uint32_t shaderType, vk depth_stencil_state.back.compareOp = vk::CompareOp::eAlways; depth_stencil_state.front = depth_stencil_state.back; - return vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - cullMode, - vk::FrontFace::eCounterClockwise, - blend_attachment_states, - depth_stencil_state, - models.pipeline_layout, - offscreen.render_pass); + return vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, vertex_input_state, + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, cullMode, vk::FrontFace::eCounterClockwise, + blend_attachment_states, depth_stencil_state, models.pipeline_layout, offscreen.render_pass); } vk::RenderPass HPPTimestampQueries::create_offscreen_render_pass() @@ -495,8 +470,7 @@ vk::RenderPass HPPTimestampQueries::create_offscreen_render_pass() attachment_descriptions[1].format = offscreen.color[1].format; attachment_descriptions[2].format = offscreen.depth.format; - std::array color_references{{{0, vk::ImageLayout::eColorAttachmentOptimal}, - {1, vk::ImageLayout::eColorAttachmentOptimal}}}; + std::array color_references{{{0, vk::ImageLayout::eColorAttachmentOptimal}, {1, vk::ImageLayout::eColorAttachmentOptimal}}}; vk::AttachmentReference depth_reference{2, vk::ImageLayout::eDepthStencilAttachmentOptimal}; @@ -508,7 +482,8 @@ vk::RenderPass HPPTimestampQueries::create_offscreen_render_pass() return create_render_pass(attachment_descriptions, subpass); } -vk::RenderPass HPPTimestampQueries::create_render_pass(std::vector const &attachment_descriptions, vk::SubpassDescription const &subpass_description) +vk::RenderPass HPPTimestampQueries::create_render_pass(std::vector const &attachment_descriptions, + vk::SubpassDescription const &subpass_description) { // Use subpass dependencies for attachment layout transitions std::array subpass_dependencies; @@ -566,13 +541,9 @@ void HPPTimestampQueries::get_time_stamp_results() // A note on the flags used: // vk::QueryResultFlagBits::e64: Results will have 64 bits. As time stamp values are on nano-seconds, this flag should always be used to avoid 32 bit overflows // vk::QueryResultFlagBits::eWait: Since we want to immediately display the results, we use this flag to have the CPU wait until the results are available - vk::Result result = get_device().get_handle().getQueryPoolResults(time_stamps.query_pool, - 0, - count, - time_stamps.values.size() * sizeof(uint64_t), - time_stamps.values.data(), - sizeof(uint64_t), - vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); + vk::Result result = + get_device().get_handle().getQueryPoolResults(time_stamps.query_pool, 0, count, time_stamps.values.size() * sizeof(uint64_t), time_stamps.values.data(), + sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); assert(result == vk::Result::eSuccess); } @@ -643,9 +614,10 @@ void HPPTimestampQueries::prepare_composition() void HPPTimestampQueries::prepare_models() { - std::array bindings = {{{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, - {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}, - {2, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment}}}; + std::array bindings = { + {{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, + {1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}, + {2, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eFragment}}}; vk::Device device = get_device().get_handle(); models.descriptor_set_layout = device.createDescriptorSetLayout({.bindingCount = static_cast(bindings.size()), .pBindings = bindings.data()}); @@ -677,12 +649,12 @@ void HPPTimestampQueries::prepare_offscreen_buffer() offscreen.render_pass = create_offscreen_render_pass(); - offscreen.framebuffer = vkb::common::create_framebuffer( - get_device().get_handle(), offscreen.render_pass, {offscreen.color[0].view, offscreen.color[1].view, offscreen.depth.view}, offscreen.extent); + offscreen.framebuffer = vkb::common::create_framebuffer(get_device().get_handle(), offscreen.render_pass, + {offscreen.color[0].view, offscreen.color[1].view, offscreen.depth.view}, offscreen.extent); // Create sampler to sample from the color attachments - offscreen.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), - offscreen.color[0].format, vk::Filter::eNearest, vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); + offscreen.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), offscreen.color[0].format, + vk::Filter::eNearest, vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); } // Bloom separable filter pass @@ -701,9 +673,10 @@ void HPPTimestampQueries::prepare_offscreen_buffer() filter_pass.color = create_attachment(color_format, vk::ImageUsageFlagBits::eColorAttachment); filter_pass.render_pass = create_filter_render_pass(); - filter_pass.framebuffer = vkb::common::create_framebuffer(get_device().get_handle(), filter_pass.render_pass, {filter_pass.color.view}, filter_pass.extent); - filter_pass.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), - filter_pass.color.format, vk::Filter::eNearest, vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); + filter_pass.framebuffer = + vkb::common::create_framebuffer(get_device().get_handle(), filter_pass.render_pass, {filter_pass.color.view}, filter_pass.extent); + filter_pass.sampler = vkb::common::create_sampler(get_device().get_gpu().get_handle(), get_device().get_handle(), filter_pass.color.format, + vk::Filter::eNearest, vk::SamplerAddressMode::eClampToEdge, 1.0f, 1.0f); } } @@ -718,16 +691,12 @@ void HPPTimestampQueries::prepare_time_stamps() void HPPTimestampQueries::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffers.matrices = std::make_unique(get_device(), - sizeof(ubo_matrices), - vk::BufferUsageFlagBits::eUniformBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.matrices = + std::make_unique(get_device(), sizeof(ubo_matrices), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); // Params - uniform_buffers.params = std::make_unique(get_device(), - sizeof(ubo_params), - vk::BufferUsageFlagBits::eUniformBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.params = + std::make_unique(get_device(), sizeof(ubo_params), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); update_params(); @@ -775,10 +744,9 @@ void HPPTimestampQueries::update_model_descriptor_set(vk::DescriptorSet descript { vk::DescriptorBufferInfo matrix_buffer_descriptor{uniform_buffers.matrices->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo environment_image_descriptor{textures.envmap.sampler, - textures.envmap.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - textures.envmap.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo environment_image_descriptor{ + textures.envmap.sampler, textures.envmap.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, textures.envmap.image->get_vk_image_view().get_format())}; vk::DescriptorBufferInfo params_buffer_descriptor{uniform_buffers.params->get_handle(), 0, vk::WholeSize}; diff --git a/samples/api/hpp_timestamp_queries/hpp_timestamp_queries.h b/samples/api/hpp_timestamp_queries/hpp_timestamp_queries.h index 086d75f30b..e900da1d61 100644 --- a/samples/api/hpp_timestamp_queries/hpp_timestamp_queries.h +++ b/samples/api/hpp_timestamp_queries/hpp_timestamp_queries.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, NVIDIA CORPORATION. All rights reserved. +/* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -211,22 +211,22 @@ class HPPTimestampQueries : public HPPApiVulkanSample vk::Image create_image(vk::Format format, vk::ImageUsageFlagBits usage); vk::Pipeline create_models_pipeline(uint32_t shaderType, vk::CullModeFlagBits cullMode, bool depthTestAndWrite); vk::RenderPass create_offscreen_render_pass(); - vk::RenderPass create_render_pass(std::vector const &attachment_descriptions, vk::SubpassDescription const &subpass_description); - void draw(); - void get_time_stamp_results(); - void load_assets(); - void prepare_bloom(); - void prepare_camera(); - void prepare_composition(); - void prepare_models(); - void prepare_offscreen_buffer(); - void prepare_time_stamps(); - void prepare_uniform_buffers(); - void update_composition_descriptor_set(); - void update_bloom_descriptor_set(); - void update_model_descriptor_set(vk::DescriptorSet descriptor_set); - void update_params(); - void update_uniform_buffers(); + vk::RenderPass create_render_pass(std::vector const &attachment_descriptions, vk::SubpassDescription const &subpass_description); + void draw(); + void get_time_stamp_results(); + void load_assets(); + void prepare_bloom(); + void prepare_camera(); + void prepare_composition(); + void prepare_models(); + void prepare_offscreen_buffer(); + void prepare_time_stamps(); + void prepare_uniform_buffers(); + void update_composition_descriptor_set(); + void update_bloom_descriptor_set(); + void update_model_descriptor_set(vk::DescriptorSet descriptor_set); + void update_params(); + void update_uniform_buffers(); private: Bloom bloom; diff --git a/samples/api/instancing/instancing.cpp b/samples/api/instancing/instancing.cpp index 33e7c299d9..31d0d56d59 100644 --- a/samples/api/instancing/instancing.cpp +++ b/samples/api/instancing/instancing.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -151,48 +151,32 @@ void Instancing::load_assets() void Instancing::setup_descriptor_pool() { // Example uses one ubo - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2), - }; + std::vector pool_sizes = { + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2), + }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - vkb::to_u32(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(vkb::to_u32(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void Instancing::setup_descriptor_set_layout() { - std::vector set_layout_bindings = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - // Binding 1 : Fragment shader combined sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), - }; + std::vector set_layout_bindings = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Fragment shader combined sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), + }; VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - vkb::to_u32(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), vkb::to_u32(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } @@ -209,8 +193,10 @@ void Instancing::setup_descriptor_set() VkDescriptorImageInfo image_descriptor = create_descriptor(textures.rocks); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_set_alloc_info, &descriptor_sets.instanced_rocks)); write_descriptor_sets = { - vkb::initializers::write_descriptor_set(descriptor_sets.instanced_rocks, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set(descriptor_sets.instanced_rocks, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &image_descriptor) // Binding 1 : Color map + vkb::initializers::write_descriptor_set(descriptor_sets.instanced_rocks, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, + &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_sets.instanced_rocks, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, + &image_descriptor) // Binding 1 : Color map }; vkUpdateDescriptorSets(get_device().get_handle(), vkb::to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); @@ -219,8 +205,10 @@ void Instancing::setup_descriptor_set() image_descriptor = create_descriptor(textures.planet); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_set_alloc_info, &descriptor_sets.planet)); write_descriptor_sets = { - vkb::initializers::write_descriptor_set(descriptor_sets.planet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set(descriptor_sets.planet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &image_descriptor) // Binding 1 : Color map + vkb::initializers::write_descriptor_set(descriptor_sets.planet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, + &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_sets.planet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, + &image_descriptor) // Binding 1 : Color map }; vkUpdateDescriptorSets(get_device().get_handle(), vkb::to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); } @@ -228,61 +216,32 @@ void Instancing::setup_descriptor_set() void Instancing::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - vkb::to_u32(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), vkb::to_u32(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages; - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pInputAssemblyState = &input_assembly_state; pipeline_create_info.pRasterizationState = &rasterization_state; @@ -301,11 +260,10 @@ void Instancing::prepare_pipelines() // Vertex input bindings // The instancing pipeline uses a vertex input state with two bindings - binding_descriptions = { - // Binding point 0: Mesh vertex layout description at per-vertex rate - vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), - // Binding point 1: Instanced data at per-instance rate - vkb::initializers::vertex_input_binding_description(1, sizeof(InstanceData), VK_VERTEX_INPUT_RATE_INSTANCE)}; + binding_descriptions = {// Binding point 0: Mesh vertex layout description at per-vertex rate + vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), + // Binding point 1: Instanced data at per-instance rate + vkb::initializers::vertex_input_binding_description(1, sizeof(InstanceData), VK_VERTEX_INPUT_RATE_INSTANCE)}; // Vertex attribute bindings // Note that the shader declaration for per-vertex and per-instance attributes is the same, the different input rates are only stored in the bindings: @@ -324,7 +282,7 @@ void Instancing::prepare_pipelines() vkb::initializers::vertex_input_attribute_description(1, 3, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 3: Position vkb::initializers::vertex_input_attribute_description(1, 4, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3), // Location 4: Rotation vkb::initializers::vertex_input_attribute_description(1, 5, VK_FORMAT_R32_SFLOAT, sizeof(float) * 6), // Location 5: Scale - vkb::initializers::vertex_input_attribute_description(1, 6, VK_FORMAT_R32_SINT, sizeof(float) * 7), // Location 6: Texture array layer index + vkb::initializers::vertex_input_attribute_description(1, 6, VK_FORMAT_R32_SINT, sizeof(float) * 7), // Location 6: Texture array layer index }; input_state.pVertexBindingDescriptions = binding_descriptions.data(); input_state.pVertexAttributeDescriptions = attribute_descriptions.data(); @@ -380,16 +338,19 @@ void Instancing::prepare_instance_data() rho = sqrt((pow(ring0[1], 2.0f) - pow(ring0[0], 2.0f)) * uniform_dist(rnd_generator) + pow(ring0[0], 2.0f)); theta = 2.0f * glm::pi() * uniform_dist(rnd_generator); instance_data[i].pos = glm::vec3(rho * cos(theta), uniform_dist(rnd_generator) * 0.5f - 0.25f, rho * sin(theta)); - instance_data[i].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator)); + instance_data[i].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), + glm::pi() * uniform_dist(rnd_generator)); instance_data[i].scale = 1.5f + uniform_dist(rnd_generator) - uniform_dist(rnd_generator); instance_data[i].texIndex = rnd_texture_index(rnd_generator); instance_data[i].scale *= 0.75f; // Outer ring - rho = sqrt((pow(ring1[1], 2.0f) - pow(ring1[0], 2.0f)) * uniform_dist(rnd_generator) + pow(ring1[0], 2.0f)); - theta = 2.0f * glm::pi() * uniform_dist(rnd_generator); - instance_data[static_cast(i + INSTANCE_COUNT / 2)].pos = glm::vec3(rho * cos(theta), uniform_dist(rnd_generator) * 0.5f - 0.25f, rho * sin(theta)); - instance_data[static_cast(i + INSTANCE_COUNT / 2)].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator)); + rho = sqrt((pow(ring1[1], 2.0f) - pow(ring1[0], 2.0f)) * uniform_dist(rnd_generator) + pow(ring1[0], 2.0f)); + theta = 2.0f * glm::pi() * uniform_dist(rnd_generator); + instance_data[static_cast(i + INSTANCE_COUNT / 2)].pos = + glm::vec3(rho * cos(theta), uniform_dist(rnd_generator) * 0.5f - 0.25f, rho * sin(theta)); + instance_data[static_cast(i + INSTANCE_COUNT / 2)].rot = glm::vec3( + glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator)); instance_data[static_cast(i + INSTANCE_COUNT / 2)].scale = 1.5f + uniform_dist(rnd_generator) - uniform_dist(rnd_generator); instance_data[static_cast(i + INSTANCE_COUNT / 2)].texIndex = rnd_texture_index(rnd_generator); instance_data[static_cast(i + INSTANCE_COUNT / 2)].scale *= 0.75f; @@ -404,19 +365,15 @@ void Instancing::prepare_instance_data() vkb::core::BufferC staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), instance_data); - instance_buffer.buffer = std::make_unique(get_device(), instance_buffer.size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + instance_buffer.buffer = std::make_unique( + get_device(), instance_buffer.size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Copy to staging buffer VkCommandBuffer copy_command = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); VkBufferCopy copy_region = {}; copy_region.size = instance_buffer.size; - vkCmdCopyBuffer( - copy_command, - staging_buffer.get_handle(), - instance_buffer.buffer->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, staging_buffer.get_handle(), instance_buffer.buffer->get_handle(), 1, ©_region); get_device().flush_command_buffer(copy_command, queue, true); @@ -427,10 +384,7 @@ void Instancing::prepare_instance_data() void Instancing::prepare_uniform_buffers() { - uniform_buffers.scene = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.scene = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffer(0.0f); } diff --git a/samples/api/oit_depth_peeling/oit_depth_peeling.cpp b/samples/api/oit_depth_peeling/oit_depth_peeling.cpp index b8da7ab844..9ea943a926 100644 --- a/samples/api/oit_depth_peeling/oit_depth_peeling.cpp +++ b/samples/api/oit_depth_peeling/oit_depth_peeling.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2024-2025, Google +/* Copyright (c) 2024-2026, Google * * SPDX-License-Identifier: Apache-2.0 * @@ -19,8 +19,7 @@ #include OITDepthPeeling::OITDepthPeeling() -{ -} +{} OITDepthPeeling::~OITDepthPeeling() { @@ -159,30 +158,25 @@ void OITDepthPeeling::build_command_buffers() // It is bound as texture and read in the shader to discard fragments from the // previous layers. VkImageSubresourceRange depth_subresource_range = {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1}; - vkb::image_layout_transition( - draw_cmd_buffers[i], depth_image[l % kDepthCount]->get_handle(), - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - l <= 1 ? VK_IMAGE_LAYOUT_UNDEFINED : VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - depth_subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], depth_image[l % kDepthCount]->get_handle(), VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_ACCESS_SHADER_READ_BIT, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, + l <= 1 ? VK_IMAGE_LAYOUT_UNDEFINED : VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, depth_subresource_range); if (l > 0) { vkb::image_layout_transition( draw_cmd_buffers[i], depth_image[(l + 1) % kDepthCount]->get_handle(), VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, - depth_subresource_range); + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, depth_subresource_range); } // Set one of the layer textures as color attachment, as the gather pass will render to it. VkImageSubresourceRange layer_subresource_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - vkb::image_layout_transition( - draw_cmd_buffers[i], layer_image[l]->get_handle(), - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - layer_subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], layer_image[l]->get_handle(), VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, layer_subresource_range); render_pass_begin_info.framebuffer = gather_framebuffer[l]; render_pass_begin_info.renderPass = gather_render_pass; @@ -195,7 +189,8 @@ void OITDepthPeeling::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, gather_pipeline_layout, 0, 1, &gather_descriptor_set[l % kDepthCount], 0, NULL); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, gather_pipeline_layout, 0, 1, + &gather_descriptor_set[l % kDepthCount], 0, NULL); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, l == 0 ? gather_first_pipeline : gather_pipeline); draw_model(object, draw_cmd_buffers[i]); @@ -203,12 +198,9 @@ void OITDepthPeeling::build_command_buffers() vkCmdEndRenderPass(draw_cmd_buffers[i]); // Get the layer texture ready to be read by the combine pass. - vkb::image_layout_transition( - draw_cmd_buffers[i], layer_image[l]->get_handle(), - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - layer_subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], layer_image[l]->get_handle(), VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, layer_subresource_range); } // Combine pass @@ -323,13 +315,17 @@ void OITDepthPeeling::create_images(const uint32_t width, const uint32_t height) const VkExtent3D image_extent = {width, height, 1}; for (uint32_t i = 0; i < kLayerMaxCount; ++i) { - layer_image[i] = std::make_unique(get_device(), image_extent, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY, VK_SAMPLE_COUNT_1_BIT); + layer_image[i] = std::make_unique(get_device(), image_extent, VK_FORMAT_R8G8B8A8_UNORM, + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY, + VK_SAMPLE_COUNT_1_BIT); layer_image_view[i] = std::make_unique(*layer_image[i], VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM); } for (uint32_t i = 0; i < kDepthCount; ++i) { - depth_image[i] = std::make_unique(get_device(), image_extent, VK_FORMAT_D32_SFLOAT, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY, VK_SAMPLE_COUNT_1_BIT); + depth_image[i] = std::make_unique(get_device(), image_extent, VK_FORMAT_D32_SFLOAT, + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY, + VK_SAMPLE_COUNT_1_BIT); depth_image_view[i] = std::make_unique(*depth_image[i], VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_D32_SFLOAT); } } @@ -361,7 +357,8 @@ void OITDepthPeeling::create_samplers() void OITDepthPeeling::create_constant_buffers() { - scene_constants = std::make_unique(get_device(), sizeof(SceneConstants), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + scene_constants = + std::make_unique(get_device(), sizeof(SceneConstants), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } void OITDepthPeeling::create_descriptors() @@ -371,7 +368,8 @@ void OITDepthPeeling::create_descriptors() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &gather_descriptor_set_layout)); } @@ -381,7 +379,8 @@ void OITDepthPeeling::create_descriptors() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2, kLayerMaxCount), }; - VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &combine_descriptor_set_layout)); } @@ -392,16 +391,17 @@ void OITDepthPeeling::create_descriptors() const uint32_t num_combine_pass_combined_image_sampler = kLayerMaxCount + 1; const uint32_t num_combine_pass_uniform_buffer = 1; - const uint32_t num_uniform_buffer_descriptors = num_gather_pass_uniform_buffer + num_combine_pass_uniform_buffer; - const uint32_t num_combined_image_sampler_descriptors = num_gather_pass_combined_image_sampler + num_combine_pass_combined_image_sampler; - std::vector pool_sizes = { + const uint32_t num_uniform_buffer_descriptors = num_gather_pass_uniform_buffer + num_combine_pass_uniform_buffer; + const uint32_t num_combined_image_sampler_descriptors = num_gather_pass_combined_image_sampler + num_combine_pass_combined_image_sampler; + std::vector pool_sizes = { vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, num_uniform_buffer_descriptors), vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, num_combined_image_sampler_descriptors), }; const uint32_t num_gather_descriptor_sets = 2; const uint32_t num_combine_descriptor_sets = 1; const uint32_t num_descriptor_sets = num_gather_descriptor_sets + num_combine_descriptor_sets; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); + VkDescriptorPoolCreateInfo descriptor_pool_create_info = + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -438,10 +438,12 @@ void OITDepthPeeling::update_descriptors() { std::vector write_descriptor_sets(3); - write_descriptor_sets[0] = vkb::initializers::write_descriptor_set(combine_descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &scene_constants_descriptor); + write_descriptor_sets[0] = + vkb::initializers::write_descriptor_set(combine_descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &scene_constants_descriptor); VkDescriptorImageInfo background_texture_descriptor = create_descriptor(background_texture); - write_descriptor_sets[1] = vkb::initializers::write_descriptor_set(combine_descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &background_texture_descriptor); + write_descriptor_sets[1] = + vkb::initializers::write_descriptor_set(combine_descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &background_texture_descriptor); VkDescriptorImageInfo layer_texture_descriptor[kLayerMaxCount]; for (uint32_t i = 0; i < kLayerMaxCount; ++i) @@ -450,7 +452,8 @@ void OITDepthPeeling::update_descriptors() layer_texture_descriptor[i].imageView = layer_image_view[i]->get_handle(); layer_texture_descriptor[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } - write_descriptor_sets[2] = vkb::initializers::write_descriptor_set(combine_descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, layer_texture_descriptor, kLayerMaxCount); + write_descriptor_sets[2] = vkb::initializers::write_descriptor_set(combine_descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, + layer_texture_descriptor, kLayerMaxCount); vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); } @@ -470,9 +473,11 @@ void OITDepthPeeling::create_pipelines() { VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineRasterizationStateCreateInfo rasterization_state = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xF, VK_FALSE); VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); @@ -481,10 +486,12 @@ void OITDepthPeeling::create_pipelines() VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamicState = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); + VkPipelineDynamicStateCreateInfo dynamicState = + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); std::array shader_stages{}; diff --git a/samples/api/oit_linked_lists/oit_linked_lists.cpp b/samples/api/oit_linked_lists/oit_linked_lists.cpp index a854e5225a..b4c93725e1 100644 --- a/samples/api/oit_linked_lists/oit_linked_lists.cpp +++ b/samples/api/oit_linked_lists/oit_linked_lists.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Google +/* Copyright (c) 2023-2026, Google * * SPDX-License-Identifier: Apache-2.0 * @@ -19,8 +19,7 @@ #include OITLinkedLists::OITLinkedLists() -{ -} +{} OITLinkedLists::~OITLinkedLists() { @@ -162,12 +161,9 @@ void OITLinkedLists::build_command_buffers() } VkImageSubresourceRange subresource_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - vkb::image_layout_transition( - draw_cmd_buffers[i], linked_list_head_image->get_handle(), - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], linked_list_head_image->get_handle(), VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, VK_IMAGE_LAYOUT_GENERAL, + VK_IMAGE_LAYOUT_GENERAL, subresource_range); // Combine pass { @@ -251,18 +247,22 @@ void OITLinkedLists::create_fragment_resources(const uint32_t width, const uint3 { { const VkExtent3D image_extent = {width, height, 1}; - linked_list_head_image = std::make_unique(get_device(), image_extent, VK_FORMAT_R32_UINT, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY, VK_SAMPLE_COUNT_1_BIT); - linked_list_head_image_view = std::make_unique(*linked_list_head_image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R32_UINT); + linked_list_head_image = + std::make_unique(get_device(), image_extent, VK_FORMAT_R32_UINT, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + VMA_MEMORY_USAGE_GPU_ONLY, VK_SAMPLE_COUNT_1_BIT); + linked_list_head_image_view = std::make_unique(*linked_list_head_image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R32_UINT); } { fragment_max_count = width * height * kFragmentsPerPixelAverage; const uint32_t fragment_buffer_size = sizeof(glm::uvec3) * fragment_max_count; - fragment_buffer = std::make_unique(get_device(), fragment_buffer_size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + fragment_buffer = + std::make_unique(get_device(), fragment_buffer_size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY); } { - fragment_counter = std::make_unique(get_device(), sizeof(glm::uint), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + fragment_counter = std::make_unique( + get_device(), sizeof(glm::uint), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); } } @@ -278,12 +278,9 @@ void OITLinkedLists::clear_sized_resources() vkCmdFillBuffer(command_buffer, fragment_counter->get_handle(), 0, sizeof(glm::uint), 0); VkImageSubresourceRange subresource_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - vkb::image_layout_transition( - command_buffer, linked_list_head_image->get_handle(), - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, - subresource_range); + vkb::image_layout_transition(command_buffer, linked_list_head_image->get_handle(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, + subresource_range); VkClearColorValue linked_lists_clear_value; linked_lists_clear_value.uint32[0] = kLinkedListEndSentinel; @@ -315,8 +312,10 @@ void OITLinkedLists::load_assets() void OITLinkedLists::create_constant_buffers() { - scene_constants = std::make_unique(get_device(), sizeof(SceneConstants), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); - instance_data = std::make_unique(get_device(), sizeof(Instance) * kInstanceCount, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + scene_constants = + std::make_unique(get_device(), sizeof(SceneConstants), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + instance_data = + std::make_unique(get_device(), sizeof(Instance) * kInstanceCount, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } void OITLinkedLists::create_descriptors() @@ -330,7 +329,8 @@ void OITLinkedLists::create_descriptors() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 4), vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 5), }; - VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); } @@ -341,8 +341,9 @@ void OITLinkedLists::create_descriptors() vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2), vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1), }; - const uint32_t num_descriptor_sets = 1; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); + const uint32_t num_descriptor_sets = 1; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -352,12 +353,13 @@ void OITLinkedLists::create_descriptors() void OITLinkedLists::update_descriptors() { - VkDescriptorBufferInfo scene_constants_descriptor = create_descriptor(*scene_constants); - VkDescriptorBufferInfo instance_data_descriptor = create_descriptor(*instance_data); - VkDescriptorImageInfo linked_list_head_image_view_descriptor = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, linked_list_head_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL); - VkDescriptorBufferInfo fragment_buffer_descriptor = create_descriptor(*fragment_buffer); - VkDescriptorBufferInfo fragment_counter_descriptor = create_descriptor(*fragment_counter); - VkDescriptorImageInfo background_texture_descriptor = create_descriptor(background_texture); + VkDescriptorBufferInfo scene_constants_descriptor = create_descriptor(*scene_constants); + VkDescriptorBufferInfo instance_data_descriptor = create_descriptor(*instance_data); + VkDescriptorImageInfo linked_list_head_image_view_descriptor = + vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, linked_list_head_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL); + VkDescriptorBufferInfo fragment_buffer_descriptor = create_descriptor(*fragment_buffer); + VkDescriptorBufferInfo fragment_counter_descriptor = create_descriptor(*fragment_counter); + VkDescriptorImageInfo background_texture_descriptor = create_descriptor(background_texture); std::vector write_descriptor_sets = { vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &scene_constants_descriptor), @@ -380,9 +382,11 @@ void OITLinkedLists::create_pipelines() { VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineRasterizationStateCreateInfo rasterization_state = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xF, VK_FALSE); VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); @@ -391,10 +395,12 @@ void OITLinkedLists::create_pipelines() VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamicState = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); + VkPipelineDynamicStateCreateInfo dynamicState = + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); std::array shader_stages{}; @@ -486,9 +492,7 @@ void OITLinkedLists::fill_instance_data() { Instance instances[kInstanceCount] = {}; - auto get_random_float = []() { - return static_cast(rand()) / (RAND_MAX); - }; + auto get_random_float = []() { return static_cast(rand()) / (RAND_MAX); }; for (uint32_t l = 0, instance_index = 0; l < kInstanceLayerCount; ++l) { @@ -496,14 +500,11 @@ void OITLinkedLists::fill_instance_data() { for (uint32_t r = 0; r < kInstanceRowCount; ++r, ++instance_index) { - const float x = static_cast(r) - ((kInstanceRowCount - 1) * 0.5f); - const float y = static_cast(c) - ((kInstanceColumnCount - 1) * 0.5f); - const float z = static_cast(l) - ((kInstanceLayerCount - 1) * 0.5f); - const float scale = 0.02f; - instances[instance_index].model = - glm::scale( - glm::translate(glm::mat4(1.0f), glm::vec3(x, y, z)), - glm::vec3(scale)); + const float x = static_cast(r) - ((kInstanceRowCount - 1) * 0.5f); + const float y = static_cast(c) - ((kInstanceColumnCount - 1) * 0.5f); + const float z = static_cast(l) - ((kInstanceLayerCount - 1) * 0.5f); + const float scale = 0.02f; + instances[instance_index].model = glm::scale(glm::translate(glm::mat4(1.0f), glm::vec3(x, y, z)), glm::vec3(scale)); instances[instance_index].color.r = get_random_float(); instances[instance_index].color.g = get_random_float(); diff --git a/samples/api/separate_image_sampler/separate_image_sampler.cpp b/samples/api/separate_image_sampler/separate_image_sampler.cpp index 3559e75cf5..f2f998859a 100644 --- a/samples/api/separate_image_sampler/separate_image_sampler.cpp +++ b/samples/api/separate_image_sampler/separate_image_sampler.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, Sascha Willems +/* Copyright (c) 2021-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -94,7 +94,8 @@ void SeparateImageSampler::build_command_buffers() // Bind the uniform buffer and sampled image to set 0 vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &base_descriptor_set, 0, nullptr); // Bind the selected sampler to set 1 - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 1, 1, &sampler_descriptor_sets[selected_sampler], 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 1, 1, &sampler_descriptor_sets[selected_sampler], 0, + nullptr); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); VkDeviceSize offsets[1] = {0}; @@ -170,12 +171,10 @@ void SeparateImageSampler::draw() void SeparateImageSampler::generate_quad() { // Setup vertices for a single uv-mapped quad made from two triangles - std::vector vertices = - { - {{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, - {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; + std::vector vertices = {{{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, + {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; // Setup indices std::vector indices = {0, 1, 2, 2, 3, 0}; @@ -187,15 +186,11 @@ void SeparateImageSampler::generate_quad() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory // Vertex buffer - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); @@ -203,16 +198,12 @@ void SeparateImageSampler::generate_quad() void SeparateImageSampler::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLER, 2)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLER, 2)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 3); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 3); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -223,43 +214,26 @@ void SeparateImageSampler::setup_descriptor_set_layout() std::vector set_layout_bindings{}; // Set layout for the uniform buffer and the image - set_layout_bindings = { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - // Binding 1 : Fragment shader sampled image - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1)}; + set_layout_bindings = {// Binding 0 : Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Fragment shader sampled image + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT, 1)}; descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &base_descriptor_set_layout)); // Set layout for the samplers - set_layout_bindings = { - // Binding 0: Fragment shader sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 0)}; + set_layout_bindings = {// Binding 0: Fragment shader sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0)}; descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &sampler_descriptor_set_layout)); // Pipeline layout // Set layout for the base descriptors in set 0 and set layout for the sampler descriptors in set 1 std::vector set_layouts = {base_descriptor_set_layout, sampler_descriptor_set_layout}; VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - set_layouts.data(), - static_cast(set_layouts.size())); + vkb::initializers::pipeline_layout_create_info(set_layouts.data(), static_cast(set_layouts.size())); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } @@ -269,11 +243,7 @@ void SeparateImageSampler::setup_descriptor_set() VkDescriptorSetAllocateInfo descriptor_set_alloc_info{}; // Descriptors set for the uniform buffer and the image - descriptor_set_alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &base_descriptor_set_layout, - 1); + descriptor_set_alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &base_descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_set_alloc_info, &base_descriptor_set)); VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*uniform_buffer_vs); @@ -294,11 +264,7 @@ void SeparateImageSampler::setup_descriptor_set() std::vector write_descriptor_sets = { // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set( - base_descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &buffer_descriptor), + vkb::initializers::write_descriptor_set(base_descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), // Binding 1 : Fragment shader sampled image image_write_descriptor_set}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); @@ -328,52 +294,27 @@ void SeparateImageSampler::setup_descriptor_set() void SeparateImageSampler::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages{}; @@ -395,11 +336,7 @@ void SeparateImageSampler::prepare_pipelines() vertex_input_state.vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -419,10 +356,7 @@ void SeparateImageSampler::prepare_pipelines() void SeparateImageSampler::prepare_uniform_buffers() { // Vertex shader uniform buffer block - uniform_buffer_vs = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer_vs = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -480,8 +414,7 @@ void SeparateImageSampler::on_update_ui_overlay(vkb::Drawer &drawer) { if (drawer.header("Settings")) { - const std::vector sampler_names = {"Linear filtering", - "Nearest filtering"}; + const std::vector sampler_names = {"Linear filtering", "Nearest filtering"}; if (drawer.combo_box("Sampler", &selected_sampler, sampler_names)) { update_uniform_buffers(); diff --git a/samples/api/swapchain_recreation/swapchain_recreation.cpp b/samples/api/swapchain_recreation/swapchain_recreation.cpp index 1323bbdff6..1e12cb43aa 100644 --- a/samples/api/swapchain_recreation/swapchain_recreation.cpp +++ b/samples/api/swapchain_recreation/swapchain_recreation.cpp @@ -346,8 +346,7 @@ bool SwapchainRecreation::recreate_swapchain() VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(get_gpu_handle(), get_surface(), &surface_properties)); // Only rebuild the swapchain if the dimensions have changed - if (surface_properties.currentExtent.width == swapchain_extents.width && - surface_properties.currentExtent.height == swapchain_extents.height && + if (surface_properties.currentExtent.width == swapchain_extents.width && surface_properties.currentExtent.height == swapchain_extents.height && are_present_modes_compatible()) { return false; @@ -476,8 +475,7 @@ void SwapchainRecreation::render(uint32_t index) // Draw two rectangles via vkCmdClearAttachments. The gray rectangle scales with the // window, but the colorful one has fixed size, and it's skipped if the window is too small. vkCmdClearAttachments(frame.command_buffer, 1, &gray_clear, 1, &gray_rect); - if (colorful_rect_x + colorful_rect_width <= swapchain_extents.width && - colorful_rect_y + colorful_rect_height <= swapchain_extents.height) + if (colorful_rect_x + colorful_rect_width <= swapchain_extents.width && colorful_rect_y + colorful_rect_height <= swapchain_extents.height) { vkCmdClearAttachments(frame.command_buffer, 1, &colorful_clear, 1, &colorful_rect); } @@ -683,9 +681,7 @@ void SwapchainRecreation::cleanup_present_history() // Move clean up data to the next (now first) present operation, if any. Note that // there cannot be any clean up data on the rest of the present operations, because // the first present already gathers every old swapchain to clean up. - assert(std::ranges::all_of(present_history, [](const PresentOperationInfo &op) { - return op.old_swapchains.empty(); - })); + assert(std::ranges::all_of(present_history, [](const PresentOperationInfo &op) { return op.old_swapchains.empty(); })); present_history.front().old_swapchains = std::move(present_info.old_swapchains); // Put the present operation at the end of the queue, so it's revisited after the @@ -743,8 +739,7 @@ void SwapchainRecreation::associate_fence_with_present_history(uint32_t index, V // present with that image. Associate the fence with that present operation. for (size_t history_index = 0; history_index < present_history.size(); ++history_index) { - PresentOperationInfo &present_info = - present_history[present_history.size() - history_index - 1]; + PresentOperationInfo &present_info = present_history[present_history.size() - history_index - 1]; if (present_info.image_index == INVALID_IMAGE_INDEX) { // No previous presentation with this index. diff --git a/samples/api/terrain_tessellation/terrain_tessellation.cpp b/samples/api/terrain_tessellation/terrain_tessellation.cpp index 4a2d8382b4..2d11b106c8 100644 --- a/samples/api/terrain_tessellation/terrain_tessellation.cpp +++ b/samples/api/terrain_tessellation/terrain_tessellation.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -107,8 +107,7 @@ void TerrainTessellation::setup_query_result_buffer() query_pool_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; query_pool_info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; query_pool_info.pipelineStatistics = - VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT | - VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT; + VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT | VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT; query_pool_info.queryCount = 2; VK_CHECK(vkCreateQueryPool(get_device().get_handle(), &query_pool_info, NULL, &query_pool)); } @@ -118,15 +117,7 @@ void TerrainTessellation::setup_query_result_buffer() void TerrainTessellation::get_query_results() { // We use vkGetQueryResults to copy the results into a host visible buffer - vkGetQueryPoolResults( - get_device().get_handle(), - query_pool, - 0, - 1, - sizeof(pipeline_stats), - pipeline_stats, - sizeof(uint64_t), - VK_QUERY_RESULT_64_BIT); + vkGetQueryPoolResults(get_device().get_handle(), query_pool, 0, 1, sizeof(pipeline_stats), pipeline_stats, sizeof(uint64_t), VK_QUERY_RESULT_64_BIT); } void TerrainTessellation::load_assets() @@ -335,14 +326,10 @@ void TerrainTessellation::generate_terrain() vkb::core::BufferC vertex_staging = vkb::core::BufferC::create_staging_buffer(get_device(), vertices); vkb::core::BufferC index_staging = vkb::core::BufferC::create_staging_buffer(get_device(), indices); - terrain.vertices = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + terrain.vertices = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); - terrain.indices = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + terrain.indices = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Copy from staging buffers @@ -351,36 +338,21 @@ void TerrainTessellation::generate_terrain() VkBufferCopy copy_region = {}; copy_region.size = vertex_buffer_size; - vkCmdCopyBuffer( - copy_command, - vertex_staging.get_handle(), - terrain.vertices->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, vertex_staging.get_handle(), terrain.vertices->get_handle(), 1, ©_region); copy_region.size = index_buffer_size; - vkCmdCopyBuffer( - copy_command, - index_staging.get_handle(), - terrain.indices->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, index_staging.get_handle(), terrain.indices->get_handle(), 1, ©_region); get_device().flush_command_buffer(copy_command, queue, true); } void TerrainTessellation::setup_descriptor_pool() { - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -392,24 +364,17 @@ void TerrainTessellation::setup_descriptor_set_layouts() std::vector set_layout_bindings; // Terrain - set_layout_bindings = - { - // Binding 0 : Shared Tessellation shader ubo - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, - 0), - // Binding 1 : Height map - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 1), - // Binding 3 : Terrain texture array layers - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 2), - }; + set_layout_bindings = { + // Binding 0 : Shared Tessellation shader ubo + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, 0), + // Binding 1 : Height map + vkb::initializers::descriptor_set_layout_binding( + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 1), + // Binding 3 : Terrain texture array layers + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), + }; descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layouts.terrain)); @@ -417,19 +382,12 @@ void TerrainTessellation::setup_descriptor_set_layouts() VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.terrain)); // Skysphere - set_layout_bindings = - { - // Binding 0 : Vertex shader ubo - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - // Binding 1 : Color map - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), - }; + set_layout_bindings = { + // Binding 0 : Vertex shader ubo + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Color map + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), + }; descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layouts.skysphere)); @@ -449,27 +407,14 @@ void TerrainTessellation::setup_descriptor_sets() VkDescriptorBufferInfo terrain_buffer_descriptor = create_descriptor(*uniform_buffers.terrain_tessellation); VkDescriptorImageInfo heightmap_image_descriptor = create_descriptor(textures.heightmap); VkDescriptorImageInfo terrainmap_image_descriptor = create_descriptor(textures.terrain_array); - write_descriptor_sets = - { - // Binding 0 : Shared tessellation shader ubo - vkb::initializers::write_descriptor_set( - descriptor_sets.terrain, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &terrain_buffer_descriptor), - // Binding 1 : Displacement map - vkb::initializers::write_descriptor_set( - descriptor_sets.terrain, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - 1, - &heightmap_image_descriptor), - // Binding 2 : Color map (alpha channel) - vkb::initializers::write_descriptor_set( - descriptor_sets.terrain, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - 2, - &terrainmap_image_descriptor), - }; + write_descriptor_sets = { + // Binding 0 : Shared tessellation shader ubo + vkb::initializers::write_descriptor_set(descriptor_sets.terrain, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &terrain_buffer_descriptor), + // Binding 1 : Displacement map + vkb::initializers::write_descriptor_set(descriptor_sets.terrain, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &heightmap_image_descriptor), + // Binding 2 : Color map (alpha channel) + vkb::initializers::write_descriptor_set(descriptor_sets.terrain, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &terrainmap_image_descriptor), + }; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); // Skysphere @@ -478,78 +423,42 @@ void TerrainTessellation::setup_descriptor_sets() VkDescriptorBufferInfo skysphere_buffer_descriptor = create_descriptor(*uniform_buffers.skysphere_vertex); VkDescriptorImageInfo skysphere_image_descriptor = create_descriptor(textures.skysphere); - write_descriptor_sets = - { - // Binding 0 : Vertex shader ubo - vkb::initializers::write_descriptor_set( - descriptor_sets.skysphere, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &skysphere_buffer_descriptor), - // Binding 1 : Fragment shader color map - vkb::initializers::write_descriptor_set( - descriptor_sets.skysphere, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - 1, - &skysphere_image_descriptor), - }; + write_descriptor_sets = { + // Binding 0 : Vertex shader ubo + vkb::initializers::write_descriptor_set(descriptor_sets.skysphere, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &skysphere_buffer_descriptor), + // Binding 1 : Fragment shader color map + vkb::initializers::write_descriptor_set(descriptor_sets.skysphere, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &skysphere_image_descriptor), + }; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); } void TerrainTessellation::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state_create_info = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_LINE_WIDTH}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // We render the terrain as a grid of quad patches - VkPipelineTessellationStateCreateInfo tessellation_state = - vkb::initializers::pipeline_tessellation_state_create_info(4); + VkPipelineTessellationStateCreateInfo tessellation_state = vkb::initializers::pipeline_tessellation_state_create_info(4); // Vertex bindings an attributes // Binding description @@ -578,8 +487,7 @@ void TerrainTessellation::prepare_pipelines() shader_stages[2] = load_shader("terrain_tessellation", "terrain.tesc.spv", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT); shader_stages[3] = load_shader("terrain_tessellation", "terrain.tese.spv", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info(pipeline_layouts.terrain, render_pass, 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layouts.terrain, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state_create_info; @@ -626,16 +534,12 @@ void TerrainTessellation::prepare_pipelines() void TerrainTessellation::prepare_uniform_buffers() { // Shared tessellation shader stages uniform buffer - uniform_buffers.terrain_tessellation = std::make_unique(get_device(), - sizeof(ubo_tess), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.terrain_tessellation = + std::make_unique(get_device(), sizeof(ubo_tess), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); // Skysphere vertex shader uniform buffer - uniform_buffers.skysphere_vertex = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.skysphere_vertex = + std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } diff --git a/samples/api/texture_loading/texture_loading.cpp b/samples/api/texture_loading/texture_loading.cpp index 61b939ff08..3d2ed0dd04 100644 --- a/samples/api/texture_loading/texture_loading.cpp +++ b/samples/api/texture_loading/texture_loading.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -64,14 +64,14 @@ void TextureLoading::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) Vulkan offers two types of image tiling (memory layout): Linear tiled images: - These are stored as is and can be copied directly to. But due to the linear nature they're not a good match for GPUs and format and feature support is very limited. - It's not advised to use linear tiled images for anything else than copying from host to GPU if buffer copies are not an option. - Linear tiling is thus only implemented for learning purposes, one should always prefer optimal tiled image. + These are stored as is and can be copied directly to. But due to the linear nature they're not a good match for GPUs and format and feature support is + very limited. It's not advised to use linear tiled images for anything else than copying from host to GPU if buffer copies are not an option. Linear tiling + is thus only implemented for learning purposes, one should always prefer optimal tiled image. Optimal tiled images: - These are stored in an implementation specific layout matching the capability of the hardware. They usually support more formats and features and are much faster. - Optimal tiled images are stored on the device and not accessible by the host. So they can't be written directly to (like liner tiled images) and always require - some sort of data copy, either from a buffer or a linear tiled image. + These are stored in an implementation specific layout matching the capability of the hardware. They usually support more formats and features and are + much faster. Optimal tiled images are stored on the device and not accessible by the host. So they can't be written directly to (like liner tiled images) and + always require some sort of data copy, either from a buffer or a linear tiled image. In Short: Always use optimal tiled images for rendering. */ @@ -139,8 +139,8 @@ void TextureLoading::load_texture() vkGetBufferMemoryRequirements(get_device().get_handle(), staging_buffer, &memory_requirements); memory_allocate_info.allocationSize = memory_requirements.size; // Get memory type index for a host visible buffer - memory_allocate_info.memoryTypeIndex = - get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + memory_allocate_info.memoryTypeIndex = get_device().get_gpu().get_memory_type( + memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VK_CHECK(vkAllocateMemory(get_device().get_handle(), &memory_allocate_info, nullptr, &staging_memory)); VK_CHECK(vkBindBufferMemory(get_device().get_handle(), staging_buffer, staging_memory, 0)); @@ -218,23 +218,11 @@ void TextureLoading::load_texture() // Insert a memory dependency at the proper pipeline stages that will execute the image layout transition // Source pipeline stage is host write/read execution (VK_PIPELINE_STAGE_HOST_BIT) // Destination pipeline stage is copy command execution (VK_PIPELINE_STAGE_TRANSFER_BIT) - vkCmdPipelineBarrier( - copy_command, - VK_PIPELINE_STAGE_HOST_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, - 0, nullptr, - 0, nullptr, - 1, &image_memory_barrier); + vkCmdPipelineBarrier(copy_command, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier); // Copy mip levels from staging buffer - vkCmdCopyBufferToImage( - copy_command, - staging_buffer, - texture.image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - static_cast(buffer_copy_regions.size()), - buffer_copy_regions.data()); + vkCmdCopyBufferToImage(copy_command, staging_buffer, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(buffer_copy_regions.size()), buffer_copy_regions.data()); // Once the data has been uploaded we transfer to the texture image to the shader read layout, so it can be sampled from image_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; @@ -245,14 +233,8 @@ void TextureLoading::load_texture() // Insert a memory dependency at the proper pipeline stages that will execute the image layout transition // Source pipeline stage stage is copy command execution (VK_PIPELINE_STAGE_TRANSFER_BIT) // Destination pipeline stage fragment shader access (VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) - vkCmdPipelineBarrier( - copy_command, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - 0, - 0, nullptr, - 0, nullptr, - 1, &image_memory_barrier); + vkCmdPipelineBarrier(copy_command, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, + &image_memory_barrier); // Store current layout for later reuse texture.image_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; @@ -289,8 +271,8 @@ void TextureLoading::load_texture() // Set memory allocation size to required memory size memory_allocate_info.allocationSize = memory_requirements.size; // Get memory type that can be mapped to host memory - memory_allocate_info.memoryTypeIndex = - get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + memory_allocate_info.memoryTypeIndex = get_device().get_gpu().get_memory_type( + memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VK_CHECK(vkAllocateMemory(get_device().get_handle(), &memory_allocate_info, nullptr, &mappable_memory)); VK_CHECK(vkBindImageMemory(get_device().get_handle(), mappable_image, mappable_memory, 0)); @@ -330,14 +312,8 @@ void TextureLoading::load_texture() // Insert a memory dependency at the proper pipeline stages that will execute the image layout transition // Source pipeline stage is host write/read execution (VK_PIPELINE_STAGE_HOST_BIT) // Destination pipeline stage fragment shader access (VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) - vkCmdPipelineBarrier( - copy_command, - VK_PIPELINE_STAGE_HOST_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - 0, - 0, nullptr, - 0, nullptr, - 1, &image_memory_barrier); + vkCmdPipelineBarrier(copy_command, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, + &image_memory_barrier); get_device().flush_command_buffer(copy_command, queue, true); } @@ -352,8 +328,8 @@ void TextureLoading::load_texture() // Create a texture sampler // In Vulkan textures are accessed by samplers - // This separates all the sampling information from the texture data. This means you could have multiple sampler objects for the same texture with different settings - // Note: Similar to the samplers available with OpenGL 3.3 + // This separates all the sampling information from the texture data. This means you could have multiple sampler objects for the same texture with different + // settings Note: Similar to the samplers available with OpenGL 3.3 VkSamplerCreateInfo sampler = vkb::initializers::sampler_create_info(); sampler.magFilter = filter; sampler.minFilter = filter; @@ -480,12 +456,10 @@ void TextureLoading::draw() void TextureLoading::generate_quad() { // Setup vertices for a single uv-mapped quad made from two triangles - std::vector vertices = - { - {{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, - {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; + std::vector vertices = {{{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, + {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; // Setup indices std::vector indices = {0, 1, 2, 2, 3, 0}; @@ -497,15 +471,11 @@ void TextureLoading::generate_quad() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory // Vertex buffer - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); @@ -514,57 +484,36 @@ void TextureLoading::generate_quad() void TextureLoading::setup_descriptor_pool() { // Example uses one ubo and one image sampler - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void TextureLoading::setup_descriptor_set_layout() { - std::vector set_layout_bindings = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - // Binding 1 : Fragment shader image sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1)}; + std::vector set_layout_bindings = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Fragment shader image sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1)}; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void TextureLoading::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -572,26 +521,22 @@ void TextureLoading::setup_descriptor_set() // Setup a descriptor image info for the current texture to be used as a combined image sampler VkDescriptorImageInfo image_descriptor; - image_descriptor.imageView = texture.view; // The image's view (images are never directly accessed by the shader, but rather through views defining subresources) + image_descriptor.imageView = + texture.view; // The image's view (images are never directly accessed by the shader, but rather through views defining subresources) image_descriptor.sampler = texture.sampler; // The sampler (Telling the pipeline how to sample the texture, including repeat, border, etc.) image_descriptor.imageLayout = texture.image_layout; // The current layout of the image (Note: Should always fit the actual use, e.g. shader read) - std::vector write_descriptor_sets = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &buffer_descriptor), - // Binding 1 : Fragment shader texture sampler - // Fragment shader: layout (binding = 1) uniform sampler2D samplerColor; - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // The descriptor set will use a combined image sampler (sampler and image could be split) - 1, // Shader binding point 1 - &image_descriptor) // Pointer to the descriptor image for our texture - }; + std::vector write_descriptor_sets = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), + // Binding 1 : Fragment shader texture sampler + // Fragment shader: layout (binding = 1) uniform sampler2D samplerColor; + vkb::initializers::write_descriptor_set( + descriptor_set, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // The descriptor set will use a combined image sampler (sampler and image could be split) + 1, // Shader binding point 1 + &image_descriptor) // Pointer to the descriptor image for our texture + }; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); } @@ -599,52 +544,27 @@ void TextureLoading::setup_descriptor_set() void TextureLoading::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages; @@ -667,11 +587,7 @@ void TextureLoading::prepare_pipelines() vertex_input_state.vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -691,10 +607,7 @@ void TextureLoading::prepare_pipelines() void TextureLoading::prepare_uniform_buffers() { // Vertex shader uniform buffer block - uniform_buffer_vs = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer_vs = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } diff --git a/samples/api/texture_loading/texture_loading.h b/samples/api/texture_loading/texture_loading.h index ac05ee715d..a763ceee10 100644 --- a/samples/api/texture_loading/texture_loading.h +++ b/samples/api/texture_loading/texture_loading.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -37,7 +37,8 @@ class TextureLoading : public ApiVulkanSample { public: // Contains all Vulkan objects that are required to store and use a texture - // Note that this repository contains a texture class (vulkan_texture.h) that encapsulates texture loading functionality in a class that is used in subsequent demos + // Note that this repository contains a texture class (vulkan_texture.h) that encapsulates texture loading functionality in a class that is used in + // subsequent demos struct Texture { VkSampler sampler; diff --git a/samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp b/samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp index 139aeb5684..8e60d5f330 100644 --- a/samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp +++ b/samples/api/texture_mipmap_generation/texture_mipmap_generation.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2025, Sascha Willems +/* Copyright (c) 2019-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -83,7 +83,8 @@ void TextureMipMapGeneration::load_texture_generate_mipmaps(std::string file_nam // If this is not supported you could implement a fallback via compute shader image writes and stores VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(get_device().get_gpu().get_handle(), format, &formatProperties); - if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT) || !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT)) + if (!(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT) || + !(formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT)) { throw std::runtime_error("Selected image format does not support blit source and destination"); } @@ -196,36 +197,20 @@ void TextureMipMapGeneration::load_texture_generate_mipmaps(std::string file_nam image_blit.dstOffsets[1].z = 1; // Prepare current mip level as image blit destination - vkb::image_layout_transition(blit_command, - texture.image, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + vkb::image_layout_transition(blit_command, texture.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, {VK_IMAGE_ASPECT_COLOR_BIT, i, 1, 0, 1}); // Blit from previous level - vkCmdBlitImage( - blit_command, - texture.image, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - texture.image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1, - &image_blit, - VK_FILTER_LINEAR); + vkCmdBlitImage(blit_command, texture.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_blit, + VK_FILTER_LINEAR); // Prepare current mip level as image blit source for next level - vkb::image_layout_transition(blit_command, - texture.image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + vkb::image_layout_transition(blit_command, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, {VK_IMAGE_ASPECT_COLOR_BIT, i, 1, 0, 1}); } // After the loop, all mip layers are in TRANSFER_SRC layout, so transition all to SHADER_READ - vkb::image_layout_transition(blit_command, - texture.image, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + vkb::image_layout_transition(blit_command, texture.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, {VK_IMAGE_ASPECT_COLOR_BIT, 0, texture.mip_levels, 0, 1}); get_device().flush_command_buffer(blit_command, queue, true); @@ -357,66 +342,42 @@ void TextureMipMapGeneration::draw() void TextureMipMapGeneration::setup_descriptor_pool() { // Example uses one ubo and one image sampler - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLER, 3), - }; + std::vector pool_sizes = { + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLER, 3), + }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void TextureMipMapGeneration::setup_descriptor_set_layout() { - std::vector set_layout_bindings = - { - // Binding 0 : Parameter uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0), - // Binding 1 : Fragment shader image sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), - // Binding 2 : Sampler array (3 descriptors) - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 2, - 3), - }; + std::vector set_layout_bindings = { + // Binding 0 : Parameter uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), + // Binding 1 : Fragment shader image sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT, 1), + // Binding 2 : Sampler array (3 descriptors) + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2, 3), + }; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void TextureMipMapGeneration::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -427,20 +388,11 @@ void TextureMipMapGeneration::setup_descriptor_set() image_descriptor.sampler = VK_NULL_HANDLE; image_descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - std::vector write_descriptor_sets = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &buffer_descriptor), - // Binding 1 : Fragment shader texture sampler - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, - 1, - &image_descriptor)}; + std::vector write_descriptor_sets = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), + // Binding 1 : Fragment shader texture sampler + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, &image_descriptor)}; // Binding 2: Sampler array std::vector sampler_descriptors; @@ -463,51 +415,26 @@ void TextureMipMapGeneration::setup_descriptor_set() void TextureMipMapGeneration::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_LESS_OR_EQUAL); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages; @@ -547,10 +474,7 @@ void TextureMipMapGeneration::prepare_pipelines() void TextureMipMapGeneration::prepare_uniform_buffers() { // Shared parameter uniform buffer block - uniform_buffer = std::make_unique(get_device(), - sizeof(ubo), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer = std::make_unique(get_device(), sizeof(ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } diff --git a/samples/api/timestamp_queries/timestamp_queries.cpp b/samples/api/timestamp_queries/timestamp_queries.cpp index 2843c22bc1..8bf17afaff 100644 --- a/samples/api/timestamp_queries/timestamp_queries.cpp +++ b/samples/api/timestamp_queries/timestamp_queries.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, Sascha Willems +/* Copyright (c) 2022-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -176,7 +176,8 @@ void TimestampQueries::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(filter_pass.width, filter_pass.height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, NULL); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, + NULL); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.bloom[1]); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); @@ -217,7 +218,8 @@ void TimestampQueries::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, NULL); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, + NULL); // Scene vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.composition); @@ -571,11 +573,10 @@ void TimestampQueries::load_assets() void TimestampQueries::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; - uint32_t num_descriptor_sets = 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; + uint32_t num_descriptor_sets = 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -593,10 +594,7 @@ void TimestampQueries::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.models)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.models, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.models, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.models)); @@ -606,7 +604,8 @@ void TimestampQueries::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.bloom_filter)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.bloom_filter, 1); @@ -618,7 +617,8 @@ void TimestampQueries::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.composition)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.composition, 1); @@ -627,11 +627,7 @@ void TimestampQueries::setup_descriptor_set_layout() void TimestampQueries::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.models, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.models, 1); // 3D object descriptor set VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.object)); @@ -693,57 +689,28 @@ void TimestampQueries::setup_descriptor_sets() void TimestampQueries::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layouts.models, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layouts.models, render_pass, 0); std::vector blend_attachment_states = { vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), @@ -864,16 +831,12 @@ void TimestampQueries::prepare_pipelines() void TimestampQueries::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffers.matrices = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.matrices = + std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); // Params - uniform_buffers.params = std::make_unique(get_device(), - sizeof(ubo_params), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.params = + std::make_unique(get_device(), sizeof(ubo_params), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); update_params(); @@ -903,15 +866,8 @@ void TimestampQueries::get_time_stamp_results() // A note on the flags used: // VK_QUERY_RESULT_64_BIT: Results will have 64 bits. As time stamp values are on nano-seconds, this flag should always be used to avoid 32 bit overflows // VK_QUERY_RESULT_WAIT_BIT: Since we want to immediately display the results, we use this flag to have the CPU wait until the results are available - vkGetQueryPoolResults( - get_device().get_handle(), - query_pool_timestamps, - 0, - count, - time_stamps.size() * sizeof(uint64_t), - time_stamps.data(), - sizeof(uint64_t), - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); + vkGetQueryPoolResults(get_device().get_handle(), query_pool_timestamps, 0, count, time_stamps.size() * sizeof(uint64_t), time_stamps.data(), + sizeof(uint64_t), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); } void TimestampQueries::update_uniform_buffers() @@ -1027,7 +983,8 @@ void TimestampQueries::on_update_ui_overlay(vkb::Drawer &drawer) float timestampFrequency = get_device().get_gpu().get_properties().limits.timestampPeriod; drawer.text("Pass 1: Offscreen scene rendering: %.3f ms", static_cast(time_stamps[1] - time_stamps[0]) * timestampFrequency / 1000000.0f); - drawer.text("Pass 2: %s %.3f ms", (bloom ? "First bloom pass" : "Scene display"), static_cast(time_stamps[3] - time_stamps[2]) * timestampFrequency / 1000000.0f); + drawer.text("Pass 2: %s %.3f ms", (bloom ? "First bloom pass" : "Scene display"), + static_cast(time_stamps[3] - time_stamps[2]) * timestampFrequency / 1000000.0f); if (bloom) { drawer.text("Pass 3: Second bloom pass %.3f ms", static_cast(time_stamps[5] - time_stamps[4]) * timestampFrequency / 1000000.0f); diff --git a/samples/extensions/buffer_device_address/buffer_device_address.cpp b/samples/extensions/buffer_device_address/buffer_device_address.cpp index 66d085683c..03eb94e47f 100644 --- a/samples/extensions/buffer_device_address/buffer_device_address.cpp +++ b/samples/extensions/buffer_device_address/buffer_device_address.cpp @@ -49,12 +49,10 @@ BufferDeviceAddress::~BufferDeviceAddress() } void BufferDeviceAddress::build_command_buffers() -{ -} +{} void BufferDeviceAddress::on_update_ui_overlay(vkb::Drawer &) -{ -} +{} bool BufferDeviceAddress::prepare(const vkb::ApplicationOptions &options) { @@ -125,19 +123,14 @@ void BufferDeviceAddress::create_graphics_pipeline() VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); info.pVertexInputState = &vertex_input_state; info.pInputAssemblyState = &input_assembly_state; @@ -177,9 +170,7 @@ std::unique_ptr BufferDeviceAddress::create_index_buffer() // Build a simple subdivided quad mesh. We can tweak the vertices later in compute to create a simple cloth-y/wave-like effect. - auto index_buffer = std::make_unique(get_device(), - size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + auto index_buffer = std::make_unique(get_device(), size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); auto staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), size, nullptr); @@ -236,8 +227,8 @@ BufferDeviceAddress::TestBuffer BufferDeviceAddress::create_vbo_buffer() // To be able to query the buffer device address, we must use the SHADER_DEVICE_ADDRESS_BIT usage flag. // STORAGE_BUFFER is also required. - VkBufferCreateInfo create_info = vkb::initializers::buffer_create_info( - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR, mesh_size); + VkBufferCreateInfo create_info = + vkb::initializers::buffer_create_info(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_KHR, mesh_size); VK_CHECK(vkCreateBuffer(device, &create_info, nullptr, &buffer.buffer)); @@ -302,9 +293,7 @@ BufferDeviceAddress::TestBuffer BufferDeviceAddress::create_pointer_buffer() void BufferDeviceAddress::update_pointer_buffer(VkCommandBuffer cmd) { // Wait with updating the pointer buffer until previous frame's vertex shading is complete. - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, - 0, nullptr, 0, nullptr, 0, nullptr); + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 0, nullptr); std::vector pointers; pointers.reserve(test_buffers.size()); @@ -318,9 +307,8 @@ void BufferDeviceAddress::update_pointer_buffer(VkCommandBuffer cmd) VkMemoryBarrier global_memory_barrier = vkb::initializers::memory_barrier(); global_memory_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; global_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, 0, - 1, &global_memory_barrier, 0, nullptr, 0, nullptr); + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, 0, 1, + &global_memory_barrier, 0, nullptr, 0, nullptr); } void BufferDeviceAddress::update_meshlets(VkCommandBuffer cmd) @@ -335,8 +323,7 @@ void BufferDeviceAddress::update_meshlets(VkCommandBuffer cmd) // So we can create a wave-like animation. push_compute.fract_time = accumulated_time; - vkCmdPushConstants(cmd, pipelines.compute_pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, - 0, sizeof(push_compute), &push_compute); + vkCmdPushConstants(cmd, pipelines.compute_pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push_compute), &push_compute); // Write-after-read hazard is implicitly handled by the earlier pointer buffer update where // we did VERTEX -> TRANSFER -> COMPUTE chain of barriers. @@ -347,8 +334,7 @@ void BufferDeviceAddress::update_meshlets(VkCommandBuffer cmd) VkMemoryBarrier global_memory_barrier = vkb::initializers::memory_barrier(); global_memory_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; global_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, - 0, 1, &global_memory_barrier, 0, nullptr, 0, nullptr); + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, 0, 1, &global_memory_barrier, 0, nullptr, 0, nullptr); } void BufferDeviceAddress::render(float delta_time) @@ -400,9 +386,8 @@ void BufferDeviceAddress::render(float delta_time) PushVertex push_vertex{}; // Create an ad-hoc perspective matrix. - push_vertex.view_projection = - glm::perspective(0.5f * glm::pi(), static_cast(width) / static_cast(height), 1.0f, 100.0f) * - glm::lookAt(glm::vec3(0.0f, 0.0f, 5.0f), glm::vec3(0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); + push_vertex.view_projection = glm::perspective(0.5f * glm::pi(), static_cast(width) / static_cast(height), 1.0f, 100.0f) * + glm::lookAt(glm::vec3(0.0f, 0.0f, 5.0f), glm::vec3(0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // Push pointer to array of meshlets. // Every instance renders its own meshlet. diff --git a/samples/extensions/calibrated_timestamps/calibrated_timestamps.cpp b/samples/extensions/calibrated_timestamps/calibrated_timestamps.cpp index 0281e3a797..2c08c33f0a 100644 --- a/samples/extensions/calibrated_timestamps/calibrated_timestamps.cpp +++ b/samples/extensions/calibrated_timestamps/calibrated_timestamps.cpp @@ -38,8 +38,7 @@ std::string time_domain_to_string(VkTimeDomainEXT input_time_domain) } } -CalibratedTimestamps::CalibratedTimestamps() : - is_time_domain_init(false) +CalibratedTimestamps::CalibratedTimestamps() : is_time_domain_init(false) { title = "Calibrated Timestamps"; @@ -142,7 +141,8 @@ void CalibratedTimestamps::build_command_buffers() if (display_skybox) { vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skybox); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.models, 0, 1, &descriptor_sets.skybox, 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.models, 0, 1, &descriptor_sets.skybox, 0, + nullptr); draw_model(models.skybox, draw_cmd_buffers[i]); } vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.reflect); @@ -156,7 +156,8 @@ void CalibratedTimestamps::build_command_buffers() vkCmdBeginRenderPass(draw_cmd_buffers[i], &filter_render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); vkCmdSetViewport(draw_cmd_buffers[i], 0, 1, &filter_viewport); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &filter_scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, + nullptr); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.bloom[1]); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); vkCmdEndRenderPass(draw_cmd_buffers[i]); @@ -168,7 +169,8 @@ void CalibratedTimestamps::build_command_buffers() vkCmdBeginRenderPass(draw_cmd_buffers[i], &bloom_render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); vkCmdSetViewport(draw_cmd_buffers[i], 0, 1, &bloom_viewport); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &bloom_scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, + nullptr); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.composition); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); @@ -470,11 +472,10 @@ void CalibratedTimestamps::load_assets() void CalibratedTimestamps::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; - uint32_t num_descriptor_sets = 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; + uint32_t num_descriptor_sets = 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -492,10 +493,7 @@ void CalibratedTimestamps::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.models)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.models, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.models, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.models)); @@ -504,7 +502,8 @@ void CalibratedTimestamps::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.bloom_filter)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.bloom_filter, 1); @@ -515,7 +514,8 @@ void CalibratedTimestamps::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.composition)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.composition, 1); @@ -581,22 +581,26 @@ void CalibratedTimestamps::setup_descriptor_sets() void CalibratedTimestamps::prepare_pipelines() { - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineRasterizationStateCreateInfo rasterization_state = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); + VkPipelineDynamicStateCreateInfo dynamic_state = + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layouts.models, render_pass, 0); @@ -700,8 +704,10 @@ void CalibratedTimestamps::prepare_pipelines() void CalibratedTimestamps::prepare_uniform_buffers() { - uniform_buffers.matrices = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); - uniform_buffers.params = std::make_unique(get_device(), sizeof(ubo_params), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.matrices = + std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.params = + std::make_unique(get_device(), sizeof(ubo_params), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); uniform_buffers.params->convert_and_update(ubo_params); @@ -789,10 +795,8 @@ void CalibratedTimestamps::get_time_domains() for (VkTimeDomainEXT time_domain : all_time_domains) { - if (time_domain != VK_TIME_DOMAIN_DEVICE_EXT && - time_domain != VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT && - time_domain != VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT && - time_domain != VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_EXT) + if (time_domain != VK_TIME_DOMAIN_DEVICE_EXT && time_domain != VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT && + time_domain != VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT && time_domain != VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_EXT) { continue; } @@ -824,7 +828,8 @@ VkResult CalibratedTimestamps::get_timestamps() if (is_time_domain_init) { // Get calibrated timestamps: - return vkGetCalibratedTimestampsEXT(get_device().get_handle(), static_cast(time_domains.size()), timestamps_info.data(), timestamps.data(), &max_deviation); + return vkGetCalibratedTimestampsEXT(get_device().get_handle(), static_cast(time_domains.size()), timestamps_info.data(), timestamps.data(), + &max_deviation); } return VK_ERROR_UNKNOWN; } @@ -913,7 +918,8 @@ void CalibratedTimestamps::on_update_ui_overlay(vkb::Drawer &drawer) for (const auto &delta_timestamp : delta_timestamps) { - drawer.text("%s:\n %.1f Microseconds", delta_timestamp.second.tag.c_str(), static_cast(delta_timestamp.second.delta) * timestamp_period * 0.001f); + drawer.text("%s:\n %.1f Microseconds", delta_timestamp.second.tag.c_str(), + static_cast(delta_timestamp.second.delta) * timestamp_period * 0.001f); } } } diff --git a/samples/extensions/calibrated_timestamps/calibrated_timestamps.h b/samples/extensions/calibrated_timestamps/calibrated_timestamps.h index 31489939e8..4490c509a9 100644 --- a/samples/extensions/calibrated_timestamps/calibrated_timestamps.h +++ b/samples/extensions/calibrated_timestamps/calibrated_timestamps.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Holochip Corporation +/* Copyright (c) 2023-2026, Holochip Corporation * * SPDX-License-Identifier: Apache-2.0 * @@ -46,7 +46,8 @@ class CalibratedTimestamps : public ApiVulkanSample uint64_t delta = 0; std::string tag = "Untagged"; }; - std::vector timestamps_info{}; // This vector is essential to vkGetCalibratedTimestampsEXT, and only need to be registered once. + std::vector + timestamps_info{}; // This vector is essential to vkGetCalibratedTimestampsEXT, and only need to be registered once. std::unordered_map delta_timestamps{}; public: @@ -154,9 +155,9 @@ class CalibratedTimestamps : public ApiVulkanSample std::vector object_names{}; private: - void get_time_domains(); // this extracts total number of time domain the (physical device has, and then sync the time domain EXT data to its vector - VkResult get_timestamps(); // this creates local timestamps information vector, update timestamps vector and deviation vector - void get_device_time_domain(); // this gets the optimal time domain which has the minimal value on its max deviation. + void get_time_domains(); // this extracts total number of time domain the (physical device has, and then sync the time domain EXT data to its vector + VkResult get_timestamps(); // this creates local timestamps information vector, update timestamps vector and deviation vector + void get_device_time_domain(); // this gets the optimal time domain which has the minimal value on its max deviation. void timestamps_begin(const std::string &input_tag = "Untagged"); // this marks the timestamp begin and partially updates the delta_timestamps void timestamps_end(const std::string &input_tag = "Untagged"); // this marks the timestamp ends and updates the delta_timestamps diff --git a/samples/extensions/color_write_enable/color_write_enable.cpp b/samples/extensions/color_write_enable/color_write_enable.cpp index 3542bdface..9740fd0d13 100644 --- a/samples/extensions/color_write_enable/color_write_enable.cpp +++ b/samples/extensions/color_write_enable/color_write_enable.cpp @@ -78,10 +78,12 @@ void ColorWriteEnable::prepare_pipelines() VkPipelineVertexInputStateCreateInfo vertex_input = vkb::initializers::pipeline_vertex_input_state_create_info(); // Specify we will use triangle lists to draw geometry. - VkPipelineInputAssemblyStateCreateInfo input_assembly = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); // Specify rasterization state. - VkPipelineRasterizationStateCreateInfo raster = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE); + VkPipelineRasterizationStateCreateInfo raster = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE); // Prepare separate attachment for each color channel. std::array blend_attachment = { @@ -96,7 +98,8 @@ void ColorWriteEnable::prepare_pipelines() color_write_info.pColorWriteEnables = color_write_enables.data(); // Define color blend with an attachment for each color. Chain it with color_write_info. - VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(blend_attachment.size(), blend_attachment.data()); + VkPipelineColorBlendStateCreateInfo color_blend_state = + vkb::initializers::pipeline_color_blend_state_create_info(blend_attachment.size(), blend_attachment.data()); color_blend_state.pNext = &color_write_info; @@ -147,14 +150,17 @@ void ColorWriteEnable::prepare_pipelines() shader_stages[1] = load_shader("color_write_enable", "composition.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); // Specify we will use triangle lists to draw geometry. - VkPipelineInputAssemblyStateCreateInfo input_assembly = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); // Specify rasterization state. - VkPipelineRasterizationStateCreateInfo raster = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE); + VkPipelineRasterizationStateCreateInfo raster = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE); // Prepare separate attachment for each color channel. - VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // We will have one viewport and scissor box. VkPipelineViewportStateCreateInfo viewport = vkb::initializers::pipeline_viewport_state_create_info(1, 1); @@ -250,22 +256,18 @@ void ColorWriteEnable::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) } else { - throw std::runtime_error("When using Slang shaders, this sample requires support for reading storage images without format (shaderStorageImageReadWithoutFormat)"); + throw std::runtime_error( + "When using Slang shaders, this sample requires support for reading storage images without format (shaderStorageImageReadWithoutFormat)"); } } } void ColorWriteEnable::setup_descriptor_pool() { - std::vector poolSizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 3)}; + std::vector poolSizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 3)}; VkDescriptorPoolCreateInfo descriptorPoolInfo = - vkb::initializers::descriptor_pool_create_info( - static_cast(poolSizes.size()), - poolSizes.data(), - 1); + vkb::initializers::descriptor_pool_create_info(static_cast(poolSizes.size()), poolSizes.data(), 1); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptorPoolInfo, nullptr, &descriptor_pool)); } @@ -329,10 +331,8 @@ void ColorWriteEnable::setup_render_pass() } std::array color_references = { - VkAttachmentReference{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, - VkAttachmentReference{1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, - VkAttachmentReference{2, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, - VkAttachmentReference{3, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}}; + VkAttachmentReference{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, VkAttachmentReference{1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, + VkAttachmentReference{2, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, VkAttachmentReference{3, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}}; // Two subpasses are defined: std::array subpass_descriptions{}; @@ -344,10 +344,9 @@ void ColorWriteEnable::setup_render_pass() subpass_descriptions[0].pDepthStencilAttachment = nullptr; // - second, with a single attachment. It takes input from the attachments 1 to 3. - std::array input_references = { - VkAttachmentReference{1, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - VkAttachmentReference{2, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - VkAttachmentReference{3, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; + std::array input_references = {VkAttachmentReference{1, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + VkAttachmentReference{2, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + VkAttachmentReference{3, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; subpass_descriptions[1].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass_descriptions[1].colorAttachmentCount = 1; @@ -431,9 +430,10 @@ void ColorWriteEnable::setup_framebuffer() create_attachments(); - VkDescriptorImageInfo red = vkb::initializers::descriptor_image_info(samplers.red, attachments.red.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - VkDescriptorImageInfo green = vkb::initializers::descriptor_image_info(samplers.green, attachments.green.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - VkDescriptorImageInfo blue = vkb::initializers::descriptor_image_info(samplers.blue, attachments.blue.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkDescriptorImageInfo red = vkb::initializers::descriptor_image_info(samplers.red, attachments.red.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkDescriptorImageInfo green = + vkb::initializers::descriptor_image_info(samplers.green, attachments.green.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkDescriptorImageInfo blue = vkb::initializers::descriptor_image_info(samplers.blue, attachments.blue.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); std::vector writeDescriptorSets = { vkb::initializers::write_descriptor_set(descriptor_sets.composition, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 0, &red), @@ -547,9 +547,7 @@ void ColorWriteEnable::on_update_ui_overlay(vkb::Drawer &drawer) if (drawer.header("Background color")) { if (drawer.color_op("", background_color, 0, - ImGuiColorEditFlags_NoSidePreview | - ImGuiColorEditFlags_NoSmallPreview | - ImGuiColorEditFlags_Float | + ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR)) { rebuild_command_buffers(); diff --git a/samples/extensions/conditional_rendering/conditional_rendering.cpp b/samples/extensions/conditional_rendering/conditional_rendering.cpp index b98835b9a1..0c407f2896 100644 --- a/samples/extensions/conditional_rendering/conditional_rendering.cpp +++ b/samples/extensions/conditional_rendering/conditional_rendering.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2022-2025, Sascha Willems +/* Copyright (c) 2022-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -87,7 +87,8 @@ void ConditionalRendering::build_command_buffers() const auto &vertex_buffer_normal = node.sub_mesh->vertex_buffers.at("normal"); auto &index_buffer = node.sub_mesh->index_buffer; - // Start a conditional rendering block, commands in this block are only executed if the buffer at the current position is 1 at command buffer submission time + // Start a conditional rendering block, commands in this block are only executed if the buffer at the current position is 1 at command buffer + // submission time VkConditionalRenderingBeginInfoEXT conditional_rendering_info{}; conditional_rendering_info.sType = VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT; conditional_rendering_info.buffer = conditional_visibility_buffer->get_handle(); @@ -145,8 +146,7 @@ void ConditionalRendering::load_assets() void ConditionalRendering::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 1); @@ -163,10 +163,7 @@ void ConditionalRendering::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); // Pass scene node information via push constants VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT, sizeof(push_const_block), 0); @@ -178,11 +175,7 @@ void ConditionalRendering::setup_descriptor_set_layout() void ConditionalRendering::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -195,60 +188,30 @@ void ConditionalRendering::setup_descriptor_sets() void ConditionalRendering::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); - std::vector blend_attachment_states = { - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)}; + std::vector blend_attachment_states = {vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)}; pipeline_create_info.pInputAssemblyState = &input_assembly_state; pipeline_create_info.pRasterizationState = &rasterization_state; @@ -293,10 +256,7 @@ void ConditionalRendering::prepare_pipelines() void ConditionalRendering::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffer = std::make_unique(get_device(), - sizeof(uniform_data), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer = std::make_unique(get_device(), sizeof(uniform_data), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -315,10 +275,8 @@ void ConditionalRendering::prepare_visibility_buffer() // Conditional values are 32 bits wide and if it's zero the rendering commands are discarded // We therefore create a buffer that can hold int32 conditional values for all nodes in the glTF scene // The extension also introduces the new buffer usage flag VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT that we need to set - conditional_visibility_buffer = std::make_unique(get_device(), - sizeof(int32_t) * conditional_visibility_list.size(), - VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + conditional_visibility_buffer = std::make_unique(get_device(), sizeof(int32_t) * conditional_visibility_list.size(), + VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_visibility_buffer(); } diff --git a/samples/extensions/conservative_rasterization/conservative_rasterization.cpp b/samples/extensions/conservative_rasterization/conservative_rasterization.cpp index 2f18b1d623..f8a14bc09f 100644 --- a/samples/extensions/conservative_rasterization/conservative_rasterization.cpp +++ b/samples/extensions/conservative_rasterization/conservative_rasterization.cpp @@ -146,7 +146,8 @@ void ConservativeRasterization::prepare_offscreen() VK_CHECK(vkBindImageMemory(get_device().get_handle(), offscreen_pass.depth.image, offscreen_pass.depth.mem, 0)); // The depth format we get for the current device may not include a stencil part, which affects the aspect mask used by the image view - const VkImageAspectFlags aspect_mask = vkb::is_depth_only_format(framebuffer_depth_format) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + const VkImageAspectFlags aspect_mask = + vkb::is_depth_only_format(framebuffer_depth_format) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; VkImageViewCreateInfo depth_stencil_view = vkb::initializers::image_view_create_info(); depth_stencil_view.viewType = VK_IMAGE_VIEW_TYPE_2D; @@ -274,7 +275,8 @@ void ConservativeRasterization::build_command_buffers() vkCmdBeginRenderPass(draw_cmd_buffers[i], &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.scene, 0, 1, &descriptor_sets.scene, 0, nullptr); - vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, conservative_raster_enabled ? pipelines.triangle_conservative_raster : pipelines.triangle); + vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, + conservative_raster_enabled ? pipelines.triangle_conservative_raster : pipelines.triangle); VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(draw_cmd_buffers[i], 0, 1, triangle.vertices->get(), offsets); @@ -311,7 +313,8 @@ void ConservativeRasterization::build_command_buffers() // Low-res triangle from offscreen framebuffer vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.fullscreen); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.fullscreen, 0, 1, &descriptor_sets.fullscreen, 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.fullscreen, 0, 1, &descriptor_sets.fullscreen, 0, + nullptr); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); // Overlay actual triangle @@ -341,9 +344,7 @@ void ConservativeRasterization::load_assets() }; std::vector vertex_buffer = { - {{1.0f, 1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}}, - {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}}, - {{0.0f, -1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; + {{1.0f, 1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}}, {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 0.0f}}, {{0.0f, -1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; uint32_t vertex_buffer_size = static_cast(vertex_buffer.size()) * sizeof(Vertex); std::vector index_buffer = {0, 1, 2}; triangle.index_count = static_cast(index_buffer.size()); @@ -354,15 +355,11 @@ void ConservativeRasterization::load_assets() vkb::core::BufferC index_staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), index_buffer); // Device local destination buffers - triangle.vertices = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + triangle.vertices = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); - triangle.indices = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + triangle.indices = std::make_unique(get_device(), index_buffer_size, + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Copy from host to device get_device().copy_buffer(vertex_staging_buffer, *triangle.vertices, queue); @@ -371,11 +368,9 @@ void ConservativeRasterization::load_assets() void ConservativeRasterization::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; - VkDescriptorPoolCreateInfo descriptor_pool_info = - vkb::initializers::descriptor_pool_create_info(pool_sizes, 2); + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; + VkDescriptorPoolCreateInfo descriptor_pool_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_info, nullptr, &descriptor_pool)); } @@ -387,9 +382,12 @@ void ConservativeRasterization::setup_descriptor_set_layout() // Scene rendering set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), // Binding 0: Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), // Binding 1: Fragment shader image sampler - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 2) // Binding 2: Fragment shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, + 0), // Binding 0: Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, + 1), // Binding 1: Fragment shader image sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, + 2) // Binding 2: Fragment shader uniform buffer }; descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layouts.scene)); @@ -398,8 +396,10 @@ void ConservativeRasterization::setup_descriptor_set_layout() // Fullscreen pass set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), // Binding 0: Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1) // Binding 1: Fragment shader image sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, + 0), // Binding 0: Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, + 1) // Binding 1: Fragment shader image sampler }; descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layouts.fullscreen)); @@ -418,7 +418,8 @@ void ConservativeRasterization::setup_descriptor_set() std::vector offscreen_write_descriptor_sets = { vkb::initializers::write_descriptor_set(descriptor_sets.scene, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &scene_buffer_descriptor), }; - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(offscreen_write_descriptor_sets.size()), offscreen_write_descriptor_sets.data(), 0, nullptr); + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(offscreen_write_descriptor_sets.size()), offscreen_write_descriptor_sets.data(), 0, + nullptr); // Fullscreen pass descriptor_set_allocate_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.fullscreen, 1); @@ -437,31 +438,25 @@ void ConservativeRasterization::prepare_pipelines() VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); + VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); std::array shader_stages; - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info(pipeline_layouts.fullscreen, render_pass, 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layouts.fullscreen, render_pass, 0); // Conservative rasterization setup @@ -545,10 +540,8 @@ void ConservativeRasterization::prepare_pipelines() // Prepare and initialize uniform buffer containing shader uniforms void ConservativeRasterization::prepare_uniform_buffers() { - uniform_buffers.scene = std::make_unique(get_device(), - sizeof(ubo_scene), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.scene = + std::make_unique(get_device(), sizeof(ubo_scene), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers_scene(); } diff --git a/samples/extensions/debug_utils/debug_utils.cpp b/samples/extensions/debug_utils/debug_utils.cpp index 319a49cc5f..bd9eb37531 100644 --- a/samples/extensions/debug_utils/debug_utils.cpp +++ b/samples/extensions/debug_utils/debug_utils.cpp @@ -347,8 +347,10 @@ void DebugUtils::build_command_buffers() vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skysphere); push_const_block.object_type = 0; - vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layouts.models, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), &push_const_block); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.models, 0, 1, &descriptor_sets.skysphere, 0, NULL); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layouts.models, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(push_const_block), &push_const_block); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.models, 0, 1, &descriptor_sets.skysphere, 0, + NULL); draw_model(models.skysphere, draw_cmd_buffers[i]); } @@ -371,7 +373,8 @@ void DebugUtils::build_command_buffers() push_const_block.object_type = 1; push_const_block.offset = glm::vec4(mesh_offsets[j], 0.0f); push_const_block.color = glm::vec4(mesh_colors[j], 0.0f); - vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layouts.models, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), &push_const_block); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layouts.models, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(push_const_block), &push_const_block); cmd_insert_label(draw_cmd_buffers[i], "Draw sphere", {mesh_colors[j].r, mesh_colors[j].g, mesh_colors[j].b, 1.0f}); draw_model(models.scene, draw_cmd_buffers[i]); } @@ -411,7 +414,8 @@ void DebugUtils::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(filter_pass.width, filter_pass.height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, NULL); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, + NULL); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.bloom[1]); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); @@ -452,7 +456,8 @@ void DebugUtils::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, NULL); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, + NULL); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.composition); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); @@ -751,11 +756,10 @@ void DebugUtils::load_assets() void DebugUtils::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; - uint32_t num_descriptor_sets = 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; + uint32_t num_descriptor_sets = 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -774,13 +778,11 @@ void DebugUtils::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.models)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.models, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.models, 1); // Pass object offset and color via push constant - VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); + VkPushConstantRange push_constant_range = + vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); pipeline_layout_create_info.pushConstantRangeCount = 1; pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; @@ -792,7 +794,8 @@ void DebugUtils::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.bloom_filter)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.bloom_filter, 1); @@ -804,7 +807,8 @@ void DebugUtils::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.composition)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.composition, 1); @@ -813,11 +817,7 @@ void DebugUtils::setup_descriptor_set_layout() void DebugUtils::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.models, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.models, 1); // Sphere model object descriptor set VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.sphere)); @@ -875,57 +875,28 @@ void DebugUtils::setup_descriptor_sets() void DebugUtils::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layouts.models, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layouts.models, render_pass, 0); std::vector blend_attachment_states = { vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), @@ -1036,10 +1007,8 @@ void DebugUtils::prepare_pipelines() void DebugUtils::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffers.matrices = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.matrices = + std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -1054,7 +1023,8 @@ void DebugUtils::update_uniform_buffers() void DebugUtils::draw() { - queue_begin_label(queue, static_cast("Graphics queue command buffer " + std::to_string(current_buffer) + " submission").c_str(), {1.0f, 1.0f, 1.0f, 1.0f}); + queue_begin_label(queue, static_cast("Graphics queue command buffer " + std::to_string(current_buffer) + " submission").c_str(), + {1.0f, 1.0f, 1.0f, 1.0f}); ApiVulkanSample::prepare_frame(); submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &draw_cmd_buffers[current_buffer]; diff --git a/samples/extensions/descriptor_buffer_basic/descriptor_buffer_basic.cpp b/samples/extensions/descriptor_buffer_basic/descriptor_buffer_basic.cpp index b06195c652..a0ff048faf 100644 --- a/samples/extensions/descriptor_buffer_basic/descriptor_buffer_basic.cpp +++ b/samples/extensions/descriptor_buffer_basic/descriptor_buffer_basic.cpp @@ -143,7 +143,8 @@ void DescriptorBufferBasic::build_command_buffers() vkCmdSetDescriptorBufferOffsetsEXT(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 1, 1, &buffer_index_ubo, &buffer_offset); // Image (set 2) buffer_offset = j * image_binding_descriptor.size; - vkCmdSetDescriptorBufferOffsetsEXT(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 2, 1, &buffer_index_image, &buffer_offset); + vkCmdSetDescriptorBufferOffsetsEXT(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 2, 1, &buffer_index_image, + &buffer_offset); draw_model(models.cube, draw_cmd_buffers[i]); } @@ -188,9 +189,11 @@ void DescriptorBufferBasic::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &image_binding_descriptor.layout)); // Create a pipeline layout using set 0 = Camera UBO, set 1 = Model UBO and set 2 = Model combined image - const std::array descriptor_set_layouts = {uniform_binding_descriptor.layout, uniform_binding_descriptor.layout, image_binding_descriptor.layout}; + const std::array descriptor_set_layouts = {uniform_binding_descriptor.layout, uniform_binding_descriptor.layout, + image_binding_descriptor.layout}; - VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(descriptor_set_layouts.data(), static_cast(descriptor_set_layouts.size())); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = + vkb::initializers::pipeline_layout_create_info(descriptor_set_layouts.data(), static_cast(descriptor_set_layouts.size())); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); // Get set layout descriptor sizes. @@ -214,26 +217,21 @@ void DescriptorBufferBasic::prepare_pipelines() VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); + VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); // Vertex bindings and attributes const std::vector vertex_input_bindings = { @@ -276,16 +274,16 @@ void DescriptorBufferBasic::prepare_pipelines() void DescriptorBufferBasic::prepare_descriptor_buffer() { // This buffer will contain resource descriptors for all the uniform buffers (one per cube and one with global matrices) - uniform_binding_descriptor.buffer = std::make_unique(get_device(), - (static_cast(cubes.size()) + 1) * uniform_binding_descriptor.size, - VK_BUFFER_USAGE_RESOURCE_DESCRIPTOR_BUFFER_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_binding_descriptor.buffer = std::make_unique( + get_device(), (static_cast(cubes.size()) + 1) * uniform_binding_descriptor.size, + VK_BUFFER_USAGE_RESOURCE_DESCRIPTOR_BUFFER_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); - // Samplers and combined images need to be stored in a separate buffer due to different flags (VK_BUFFER_USAGE_SAMPLER_DESCRIPTOR_BUFFER_BIT_EXT) (one image per cube) - image_binding_descriptor.buffer = std::make_unique(get_device(), - static_cast(cubes.size()) * image_binding_descriptor.size, - VK_BUFFER_USAGE_RESOURCE_DESCRIPTOR_BUFFER_BIT_EXT | VK_BUFFER_USAGE_SAMPLER_DESCRIPTOR_BUFFER_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + // Samplers and combined images need to be stored in a separate buffer due to different flags (VK_BUFFER_USAGE_SAMPLER_DESCRIPTOR_BUFFER_BIT_EXT) (one image + // per cube) + image_binding_descriptor.buffer = std::make_unique( + get_device(), static_cast(cubes.size()) * image_binding_descriptor.size, + VK_BUFFER_USAGE_RESOURCE_DESCRIPTOR_BUFFER_BIT_EXT | VK_BUFFER_USAGE_SAMPLER_DESCRIPTOR_BUFFER_BIT_EXT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); // Put the descriptors into the above buffers @@ -307,7 +305,8 @@ void DescriptorBufferBasic::prepare_descriptor_buffer() // combinedImageSamplerDescriptorSingleArray property and separate the image descriptor part from the // sampler descriptor part. We would place all the image descriptors first, followed by all the samplers. - vkGetDescriptorEXT(get_device().get_handle(), &image_descriptor_info, descriptor_buffer_properties.combinedImageSamplerDescriptorSize, image_descriptor_buf_ptr + i * image_binding_descriptor.size + image_binding_descriptor.offset); + vkGetDescriptorEXT(get_device().get_handle(), &image_descriptor_info, descriptor_buffer_properties.combinedImageSamplerDescriptorSize, + image_descriptor_buf_ptr + i * image_binding_descriptor.size + image_binding_descriptor.offset); } // For uniform buffers we only need to put their buffer device addresses into the descriptor buffers @@ -322,7 +321,8 @@ void DescriptorBufferBasic::prepare_descriptor_buffer() VkDescriptorGetInfoEXT buffer_descriptor_info{VK_STRUCTURE_TYPE_DESCRIPTOR_GET_INFO_EXT}; buffer_descriptor_info.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; buffer_descriptor_info.data.pUniformBuffer = &addr_info; - vkGetDescriptorEXT(get_device().get_handle(), &buffer_descriptor_info, descriptor_buffer_properties.uniformBufferDescriptorSize, uniform_descriptor_buf_ptr); + vkGetDescriptorEXT(get_device().get_handle(), &buffer_descriptor_info, descriptor_buffer_properties.uniformBufferDescriptorSize, + uniform_descriptor_buf_ptr); // Per-cube uniform buffers // We use pointers to offset and align the data we put into the descriptor buffers @@ -334,25 +334,22 @@ void DescriptorBufferBasic::prepare_descriptor_buffer() cube_addr_info.format = VK_FORMAT_UNDEFINED; buffer_descriptor_info.data.pUniformBuffer = &cube_addr_info; - vkGetDescriptorEXT(get_device().get_handle(), &buffer_descriptor_info, descriptor_buffer_properties.uniformBufferDescriptorSize, uniform_descriptor_buf_ptr + (i + 1) * uniform_binding_descriptor.size + uniform_binding_descriptor.offset); + vkGetDescriptorEXT(get_device().get_handle(), &buffer_descriptor_info, descriptor_buffer_properties.uniformBufferDescriptorSize, + uniform_descriptor_buf_ptr + (i + 1) * uniform_binding_descriptor.size + uniform_binding_descriptor.offset); } } void DescriptorBufferBasic::prepare_uniform_buffers() { // Vertex shader scene uniform buffer block - uniform_buffers.scene = std::make_unique(get_device(), - sizeof(UboScene), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.scene = std::make_unique( + get_device(), sizeof(UboScene), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); // Vertex shader cube model uniform buffer blocks for (auto &cube : cubes) { - cube.uniform_buffer = std::make_unique(get_device(), - sizeof(glm::mat4), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + cube.uniform_buffer = std::make_unique( + get_device(), sizeof(glm::mat4), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } update_uniform_buffers(); @@ -422,7 +419,8 @@ bool DescriptorBufferBasic::prepare(const vkb::ApplicationOptions &options) if (descriptor_buffer_properties.maxResourceDescriptorBufferBindings < 2) { - LOGE("VkPhysicalDeviceDescriptorBufferPropertiesEXT.maxResourceDescriptorBufferBindings={}. Sample requires at least 2 to run.", descriptor_buffer_properties.maxResourceDescriptorBufferBindings); + LOGE("VkPhysicalDeviceDescriptorBufferPropertiesEXT.maxResourceDescriptorBufferBindings={}. Sample requires at least 2 to run.", + descriptor_buffer_properties.maxResourceDescriptorBufferBindings); return false; } diff --git a/samples/extensions/descriptor_indexing/descriptor_indexing.cpp b/samples/extensions/descriptor_indexing/descriptor_indexing.cpp index 6f8f60919a..9a21e12cf8 100644 --- a/samples/extensions/descriptor_indexing/descriptor_indexing.cpp +++ b/samples/extensions/descriptor_indexing/descriptor_indexing.cpp @@ -114,8 +114,10 @@ void DescriptorIndexing::render(float delta_time) for (unsigned i = 0; i < NumDescriptorsNonUniform; i++) { - VkDescriptorImageInfo image_info = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, test_images[i].image_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - VkWriteDescriptorSet write = vkb::initializers::write_descriptor_set(descriptors.descriptor_set_update_after_bind, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 0, &image_info); + VkDescriptorImageInfo image_info = + vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, test_images[i].image_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkWriteDescriptorSet write = + vkb::initializers::write_descriptor_set(descriptors.descriptor_set_update_after_bind, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 0, &image_info); // One way we can use VK_EXT_descriptor_indexing is to treat the update-after-bind descriptor set as a ring buffer where we write descriptors, // and we use push constants as a way to index into the "bindless" descriptor set. @@ -194,7 +196,8 @@ void DescriptorIndexing::create_bindless_descriptors() { uint32_t descriptorCount = descriptor_indexing_properties.maxDescriptorSetUpdateAfterBindSampledImages; - VkDescriptorSetLayoutBinding binding = vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT, 0, descriptorCount); + VkDescriptorSetLayoutBinding binding = + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT, 0, descriptorCount); VkDescriptorSetLayoutCreateInfo set_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(&binding, 1); // We're going to use update-after-bind, so we need to make sure the flag is set correctly in the set layout. @@ -216,11 +219,8 @@ void DescriptorIndexing::create_bindless_descriptors() // The only restriction is that the descriptor cannot actually be accessed by the GPU. // Typically, if you're using descriptor indexing, you will want to use all four of these, but all of these are separate feature bits. - const VkDescriptorBindingFlagsEXT flags = - VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT | - VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT | - VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT | - VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT; + const VkDescriptorBindingFlagsEXT flags = VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT | VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT | + VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT; // In unextended Vulkan, there is no way to pass down flags to a binding, so we're going to do so via a pNext. // Each pBinding has a corresponding pBindingFlags. @@ -233,7 +233,8 @@ void DescriptorIndexing::create_bindless_descriptors() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &set_layout_create_info, nullptr, &descriptors.set_layout)); // We're going to allocate two separate descriptor sets from the same pool, and here VARIABLE_DESCRIPTOR_COUNT comes in handy! - // For the non-uniform indexing part, we allocate few descriptors, and for the streaming case, we allocate a fairly large ring buffer of descriptors we can play around with. + // For the non-uniform indexing part, we allocate few descriptors, and for the streaming case, we allocate a fairly large ring buffer of descriptors we can + // play around with. uint32_t poolCount = NumDescriptorsStreaming + NumDescriptorsNonUniform; VkDescriptorPoolSize pool_size = vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, poolCount); @@ -282,19 +283,14 @@ void DescriptorIndexing::create_pipelines() vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); info.pVertexInputState = &vertex_input_state; info.pInputAssemblyState = &input_assembly_state; @@ -360,7 +356,8 @@ DescriptorIndexing::TestImage DescriptorIndexing::create_image(const float rgb[3 image_view.image = test_image.image; VK_CHECK(vkCreateImageView(get_device().get_handle(), &image_view, nullptr, &test_image.image_view)); - auto staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), image_info.extent.width * image_info.extent.height * sizeof(uint32_t), nullptr); + auto staging_buffer = + vkb::core::BufferC::create_staging_buffer(get_device(), image_info.extent.width * image_info.extent.height * sizeof(uint32_t), nullptr); // Generate a random texture. // Fairly simple, create different colors and some different patterns. @@ -478,9 +475,11 @@ void DescriptorIndexing::create_images() // prepare a descriptor set with all textures prepared ahead of time. for (unsigned i = 0; i < NumDescriptorsNonUniform; i++) { - VkDescriptorImageInfo image_info = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, test_images[i].image_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - VkWriteDescriptorSet write = vkb::initializers::write_descriptor_set(descriptors.descriptor_set_nonuniform, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 0, &image_info); - write.dstArrayElement = i; + VkDescriptorImageInfo image_info = + vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, test_images[i].image_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkWriteDescriptorSet write = + vkb::initializers::write_descriptor_set(descriptors.descriptor_set_nonuniform, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 0, &image_info); + write.dstArrayElement = i; vkUpdateDescriptorSets(get_device().get_handle(), 1, &write, 0, nullptr); } } diff --git a/samples/extensions/dynamic_blending/dynamic_blending.cpp b/samples/extensions/dynamic_blending/dynamic_blending.cpp index 22f279051d..9537baa2f4 100644 --- a/samples/extensions/dynamic_blending/dynamic_blending.cpp +++ b/samples/extensions/dynamic_blending/dynamic_blending.cpp @@ -97,61 +97,39 @@ void DynamicBlending::initialize_operator_names() void DynamicBlending::prepare_scene() { vertices = { - {{-1.0f, -1.0f, 1.0f}, {0.0f, 0.0f}}, - {{1.0f, -1.0f, 1.0f}, {1.0f, 0.0f}}, - {{1.0f, 1.0f, 1.0f}, {1.0f, 1.0f}}, - {{-1.0f, 1.0f, 1.0f}, {0.0f, 1.0f}}, - - {{-1.0f, -1.0f, -1.0f}, {0.0f, 0.0f}}, - {{1.0f, -1.0f, -1.0f}, {1.0f, 0.0f}}, - {{1.0f, 1.0f, -1.0f}, {1.0f, 1.0f}}, - {{-1.0f, 1.0f, -1.0f}, {0.0f, 1.0f}}, + {{-1.0f, -1.0f, 1.0f}, {0.0f, 0.0f}}, {{1.0f, -1.0f, 1.0f}, {1.0f, 0.0f}}, {{1.0f, 1.0f, 1.0f}, {1.0f, 1.0f}}, {{-1.0f, 1.0f, 1.0f}, {0.0f, 1.0f}}, + + {{-1.0f, -1.0f, -1.0f}, {0.0f, 0.0f}}, {{1.0f, -1.0f, -1.0f}, {1.0f, 0.0f}}, {{1.0f, 1.0f, -1.0f}, {1.0f, 1.0f}}, {{-1.0f, 1.0f, -1.0f}, {0.0f, 1.0f}}, }; - std::vector indices = { - 6, 5, 4, 4, 7, 6, - 0, 1, 2, 2, 3, 0}; + std::vector indices = {6, 5, 4, 4, 7, 6, 0, 1, 2, 2, 3, 0}; index_count = static_cast(indices.size()); vertex_buffer_size = static_cast(vertices.size() * sizeof(Vertex)); auto index_buffer_size = indices.size() * sizeof(uint32_t); - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, - VMA_MEMORY_USAGE_GPU_TO_CPU); + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_TO_CPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT, - VMA_MEMORY_USAGE_GPU_TO_CPU); + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_TO_CPU); index_buffer->update(indices.data(), index_buffer_size); face_preferences[0].index_offset = 0; face_preferences[0].index_count = index_count / 2; face_preferences[0].color_bit_enabled = {true, true, true, true}; - face_preferences[0].color = {{{1.0f, 0.0f, 0.0f, 1.0f}, - {0.0f, 1.0f, 0.0f, 1.0f}, - {0.0f, 0.0f, 1.0f, 1.0f}, - {0.0f, 0.0f, 0.0f, 1.0f}}}; + face_preferences[0].color = {{{1.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 1.0f, 0.0f, 1.0f}, {0.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}}; face_preferences[1].index_offset = index_count / 2; face_preferences[1].index_count = index_count / 2; face_preferences[1].color_bit_enabled = {true, true, true, true}; - face_preferences[1].color = {{{0.0f, 1.0f, 1.0f, 0.5f}, - {1.0f, 0.0f, 1.0f, 0.5f}, - {1.0f, 1.0f, 0.0f, 0.5f}, - {1.0f, 1.0f, 1.0f, 0.5f}}}; + face_preferences[1].color = {{{0.0f, 1.0f, 1.0f, 0.5f}, {1.0f, 0.0f, 1.0f, 0.5f}, {1.0f, 1.0f, 0.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 0.5f}}}; } void DynamicBlending::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) { // We must have this or the sample isn't useful - REQUEST_REQUIRED_FEATURE(gpu, - VkPhysicalDeviceExtendedDynamicState3FeaturesEXT, - extendedDynamicState3ColorBlendEnable); + REQUEST_REQUIRED_FEATURE(gpu, VkPhysicalDeviceExtendedDynamicState3FeaturesEXT, extendedDynamicState3ColorBlendEnable); // Only request the features that we support, and record which ones are available eds_feature_support.extendedDynamicState3ColorWriteMask = @@ -203,10 +181,7 @@ void DynamicBlending::setup_descriptor_pool() }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - static_cast(pool_sizes.size())); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), static_cast(pool_sizes.size())); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -242,45 +217,26 @@ void DynamicBlending::create_descriptor_set() void DynamicBlending::create_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, - VK_TRUE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_TRUE); VkPipelineColorBlendAdvancedStateCreateInfoEXT blendAdvancedEXT{}; blendAdvancedEXT.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_ADVANCED_STATE_CREATE_INFO_EXT; blendAdvancedEXT.blendOverlap = VK_BLEND_OVERLAP_UNCORRELATED_EXT; - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); std::vector dynamic_state_enables = { VK_DYNAMIC_STATE_VIEWPORT, @@ -314,10 +270,7 @@ void DynamicBlending::create_pipelines() } VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); const std::vector vertex_input_bindings = { vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), @@ -353,12 +306,7 @@ void DynamicBlending::create_pipelines() graphics_create.pStages = shader_stages.data(); graphics_create.layout = pipeline_layout; - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), - pipeline_cache, - 1, - &graphics_create, - VK_NULL_HANDLE, - &pipeline)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &graphics_create, VK_NULL_HANDLE, &pipeline)); } void DynamicBlending::update_pipeline() @@ -495,10 +443,8 @@ void DynamicBlending::build_command_buffer_for_plane(VkCommandBuffer &command_bu if (eds_feature_support.extendedDynamicState3ColorWriteMask) { std::array color_bit = { - (preferences.color_bit_enabled[0] ? VK_COLOR_COMPONENT_R_BIT : 0u) | - (preferences.color_bit_enabled[1] ? VK_COLOR_COMPONENT_G_BIT : 0u) | - (preferences.color_bit_enabled[2] ? VK_COLOR_COMPONENT_B_BIT : 0u) | - (preferences.color_bit_enabled[3] ? VK_COLOR_COMPONENT_A_BIT : 0u)}; + (preferences.color_bit_enabled[0] ? VK_COLOR_COMPONENT_R_BIT : 0u) | (preferences.color_bit_enabled[1] ? VK_COLOR_COMPONENT_G_BIT : 0u) | + (preferences.color_bit_enabled[2] ? VK_COLOR_COMPONENT_B_BIT : 0u) | (preferences.color_bit_enabled[3] ? VK_COLOR_COMPONENT_A_BIT : 0u)}; vkCmdSetColorWriteMaskEXT(command_buffer, 0, 1, color_bit.data()); } vkCmdDrawIndexed(command_buffer, preferences.index_count, 1, preferences.index_offset, 0, 0); @@ -616,12 +562,16 @@ void DynamicBlending::on_update_ui_overlay(vkb::Drawer &drawer) if (drawer.header("BlendEquationEXT")) { add_combo_with_button("Color operator", current_blend_color_operator_index, VK_BLEND_OP_ADD, VK_BLEND_OP_MAX, blend_operator.names); - add_combo_with_button("SrcColorBlendFactor", current_src_color_blend_factor, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, blend_factor_names); - add_combo_with_button("DstColorBlendFactor", current_dst_color_blend_factor, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, blend_factor_names); + add_combo_with_button("SrcColorBlendFactor", current_src_color_blend_factor, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, + blend_factor_names); + add_combo_with_button("DstColorBlendFactor", current_dst_color_blend_factor, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, + blend_factor_names); add_combo_with_button("Alpha operator", current_blend_alpha_operator_index, VK_BLEND_OP_ADD, VK_BLEND_OP_MAX, blend_operator.names); - add_combo_with_button("SrcAlphaBlendFactor", current_src_alpha_blend_factor, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, blend_factor_names); - add_combo_with_button("DstAlphaBlendFactor", current_dst_alpha_blend_factor, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, blend_factor_names); + add_combo_with_button("SrcAlphaBlendFactor", current_src_alpha_blend_factor, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, + blend_factor_names); + add_combo_with_button("DstAlphaBlendFactor", current_dst_alpha_blend_factor, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_SRC_ALPHA_SATURATE, + blend_factor_names); } } break; @@ -630,7 +580,8 @@ void DynamicBlending::on_update_ui_overlay(vkb::Drawer &drawer) { if (drawer.header("BlendAdvancedEXT")) { - add_combo_with_button("Operator", current_advanced_blend_operator_index, VK_BLEND_OP_ZERO_EXT, VK_BLEND_OP_BLUE_EXT, advanced_blend_operator.names); + add_combo_with_button("Operator", current_advanced_blend_operator_index, VK_BLEND_OP_ZERO_EXT, VK_BLEND_OP_BLUE_EXT, + advanced_blend_operator.names); if (drawer.checkbox("Src premultiplied", &src_premultiplied)) { update_color_uniform(); diff --git a/samples/extensions/dynamic_line_rasterization/dynamic_line_rasterization.cpp b/samples/extensions/dynamic_line_rasterization/dynamic_line_rasterization.cpp index ff519cf5ca..95db85a9c0 100644 --- a/samples/extensions/dynamic_line_rasterization/dynamic_line_rasterization.cpp +++ b/samples/extensions/dynamic_line_rasterization/dynamic_line_rasterization.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Mobica Limited +/* Copyright (c) 2023-2026, Mobica Limited * * SPDX-License-Identifier: Apache-2.0 * @@ -65,52 +65,28 @@ bool DynamicLineRasterization::prepare(const vkb::ApplicationOptions &options) void DynamicLineRasterization::prepare_scene() { - std::vector vertices = { - {-1.0f, -1.0f, 1.0f}, - {1.0f, -1.0f, 1.0f}, - {1.0f, 1.0f, 1.0f}, - {-1.0f, 1.0f, 1.0f}, + std::vector vertices = {{-1.0f, -1.0f, 1.0f}, {1.0f, -1.0f, 1.0f}, {1.0f, 1.0f, 1.0f}, {-1.0f, 1.0f, 1.0f}, - {-1.0f, -1.0f, -1.0f}, - {1.0f, -1.0f, -1.0f}, - {1.0f, 1.0f, -1.0f}, - {-1.0f, 1.0f, -1.0f}}; + {-1.0f, -1.0f, -1.0f}, {1.0f, -1.0f, -1.0f}, {1.0f, 1.0f, -1.0f}, {-1.0f, 1.0f, -1.0f}}; - std::vector cube_indices = { - 0, 1, 2, - 2, 3, 0, + std::vector cube_indices = {0, 1, 2, 2, 3, 0, - 4, 5, 6, - 6, 7, 4, + 4, 5, 6, 6, 7, 4, - 0, 3, 7, - 7, 4, 0, + 0, 3, 7, 7, 4, 0, - 1, 5, 6, - 6, 2, 1, + 1, 5, 6, 6, 2, 1, - 3, 2, 6, - 6, 7, 3, + 3, 2, 6, 6, 7, 3, - 0, 4, 5, - 5, 1, 0}; + 0, 4, 5, 5, 1, 0}; // Indices of the edges of the cube - std::vector edges_indices = { - 0, 1, - 1, 2, - 2, 3, - 3, 0, - - 4, 5, - 5, 6, - 6, 7, - 7, 4, - - 0, 4, - 1, 5, - 2, 6, - 3, 7}; + std::vector edges_indices = {0, 1, 1, 2, 2, 3, 3, 0, + + 4, 5, 5, 6, 6, 7, 7, 4, + + 0, 4, 1, 5, 2, 6, 3, 7}; cube_index_count = static_cast(cube_indices.size()); edges_index_count = static_cast(edges_indices.size()); @@ -118,22 +94,15 @@ void DynamicLineRasterization::prepare_scene() uint32_t cube_index_buffer_size = static_cast(cube_indices.size() * sizeof(uint32_t)); uint32_t edges_index_buffer_size = static_cast(edges_indices.size() * sizeof(uint32_t)); - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - cube_index_buffer = std::make_unique(get_device(), - cube_index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + cube_index_buffer = + std::make_unique(get_device(), cube_index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); cube_index_buffer->update(cube_indices.data(), cube_index_buffer_size); - edges_index_buffer = std::make_unique(get_device(), - edges_index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + edges_index_buffer = + std::make_unique(get_device(), edges_index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); edges_index_buffer->update(edges_indices.data(), edges_index_buffer_size); fill_color = glm::vec4(0.957f, 0.384f, 0.024f, 0.1f); @@ -151,32 +120,20 @@ void DynamicLineRasterization::setup_descriptor_pool() }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - static_cast(pool_sizes.size())); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), static_cast(pool_sizes.size())); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void DynamicLineRasterization::create_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, - VK_TRUE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_TRUE); blend_attachment_state.colorBlendOp = VK_BLEND_OP_ADD; blend_attachment_state.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; @@ -185,40 +142,26 @@ void DynamicLineRasterization::create_pipelines() blend_attachment_state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; blend_attachment_state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_NEVER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, - VK_DYNAMIC_STATE_POLYGON_MODE_EXT, - VK_DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT, - VK_DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT, - VK_DYNAMIC_STATE_LINE_STIPPLE_EXT, - VK_DYNAMIC_STATE_LINE_WIDTH}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_NEVER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR, + VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, + VK_DYNAMIC_STATE_POLYGON_MODE_EXT, + VK_DYNAMIC_STATE_LINE_RASTERIZATION_MODE_EXT, + VK_DYNAMIC_STATE_LINE_STIPPLE_ENABLE_EXT, + VK_DYNAMIC_STATE_LINE_STIPPLE_EXT, + VK_DYNAMIC_STATE_LINE_WIDTH}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); const std::vector vertex_input_bindings = { vkb::initializers::vertex_input_binding_description(0, sizeof(glm::vec3), VK_VERTEX_INPUT_RATE_VERTEX), @@ -253,12 +196,7 @@ void DynamicLineRasterization::create_pipelines() graphics_create.pStages = shader_stages.data(); graphics_create.layout = pipeline_layout; - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), - pipeline_cache, - 1, - &graphics_create, - VK_NULL_HANDLE, - &pipelines.object)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &graphics_create, VK_NULL_HANDLE, &pipelines.object)); shader_stages[0] = load_shader("dynamic_line_rasterization", "grid.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shader_stages[1] = load_shader("dynamic_line_rasterization", "grid.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); @@ -311,8 +249,7 @@ void DynamicLineRasterization::create_descriptor_set_layout() VkDescriptorSetLayoutCreateInfo descriptor_set_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_set_layout_create_info, nullptr, &descriptor_set_layout)); - VkPushConstantRange push_constant_range = - vkb::initializers::push_constant_range(VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(glm::vec4), 0); + VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(glm::vec4), 0); VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout); diff --git a/samples/extensions/dynamic_multisample_rasterization/dynamic_multisample_rasterization.cpp b/samples/extensions/dynamic_multisample_rasterization/dynamic_multisample_rasterization.cpp index 8217922cd7..9ed7f7b477 100644 --- a/samples/extensions/dynamic_multisample_rasterization/dynamic_multisample_rasterization.cpp +++ b/samples/extensions/dynamic_multisample_rasterization/dynamic_multisample_rasterization.cpp @@ -96,17 +96,12 @@ void DynamicMultisampleRasterization::prepare_supported_sample_count_list() // All possible sample counts are listed here from most to least preferred as default // On Mali GPUs 4X MSAA is recommended as best performance/quality trade-off - std::vector counts = {VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_2_BIT, VK_SAMPLE_COUNT_8_BIT, - VK_SAMPLE_COUNT_16_BIT, VK_SAMPLE_COUNT_32_BIT, VK_SAMPLE_COUNT_64_BIT, - VK_SAMPLE_COUNT_1_BIT}; + std::vector counts = {VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_2_BIT, VK_SAMPLE_COUNT_8_BIT, VK_SAMPLE_COUNT_16_BIT, + VK_SAMPLE_COUNT_32_BIT, VK_SAMPLE_COUNT_64_BIT, VK_SAMPLE_COUNT_1_BIT}; - std::copy_if(counts.begin(), - counts.end(), - std::back_inserter(supported_sample_count_list), + std::copy_if(counts.begin(), counts.end(), std::back_inserter(supported_sample_count_list), [&supported_by_depth_and_color](auto count) { return supported_by_depth_and_color & count; }); - std::transform(supported_sample_count_list.begin(), - supported_sample_count_list.end(), - std::back_inserter(gui_settings.sample_counts), + std::transform(supported_sample_count_list.begin(), supported_sample_count_list.end(), std::back_inserter(gui_settings.sample_counts), [](auto count) { return to_string(count); }); if (!supported_sample_count_list.empty()) { @@ -238,31 +233,16 @@ void DynamicMultisampleRasterization::build_command_buffers() render_info.layerCount = 1; render_info.pDepthAttachment = &attachments[1]; - vkb::image_layout_transition(draw_cmd_buffers[i], - swapchain_buffers[i].image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - 0, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - range); + vkb::image_layout_transition(draw_cmd_buffers[i], swapchain_buffers[i].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, range); - vkb::image_layout_transition(draw_cmd_buffers[i], - depth_stencil.image, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, + vkb::image_layout_transition(draw_cmd_buffers[i], depth_stencil.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, depth_range); - vkb::image_layout_transition(draw_cmd_buffers[i], - color_attachment.image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - 0, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - range); + vkb::image_layout_transition(draw_cmd_buffers[i], color_attachment.image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, range); vkCmdBeginRenderingKHR(draw_cmd_buffers[i], &render_info); vkCmdSetRasterizationSamplesEXT(draw_cmd_buffers[i], sample_count); // VK_EXT_extended_dynamic_state3 @@ -315,10 +295,7 @@ void DynamicMultisampleRasterization::build_command_buffers() vkCmdEndRenderingKHR(draw_cmd_buffers[i]); - vkb::image_layout_transition(draw_cmd_buffers[i], - swapchain_buffers[i].image, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + vkb::image_layout_transition(draw_cmd_buffers[i], swapchain_buffers[i].image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, range); VK_CHECK(vkEndCommandBuffer(draw_cmd_buffers[i])); @@ -399,7 +376,8 @@ void DynamicMultisampleRasterization::setup_descriptor_set_layout() { std::vector set_layout_bindings = { vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1, static_cast(image_infos.size())), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1, + static_cast(image_infos.size())), }; VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = @@ -407,10 +385,7 @@ void DynamicMultisampleRasterization::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); // Pass scene node information via push constants VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT, sizeof(push_const_block), 0); @@ -422,11 +397,7 @@ void DynamicMultisampleRasterization::setup_descriptor_set_layout() void DynamicMultisampleRasterization::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -564,25 +535,13 @@ void DynamicMultisampleRasterization::setup_depth_stencil() void DynamicMultisampleRasterization::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - VK_COLOR_COMPONENT_R_BIT | - VK_COLOR_COMPONENT_G_BIT | - VK_COLOR_COMPONENT_B_BIT | - VK_COLOR_COMPONENT_A_BIT, - VK_FALSE); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); blend_attachment_state.colorBlendOp = VK_BLEND_OP_ADD; blend_attachment_state.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; @@ -591,42 +550,25 @@ void DynamicMultisampleRasterization::prepare_pipelines() blend_attachment_state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; blend_attachment_state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, // disable multisampling during configuration - 0); + vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, // disable multisampling during configuration + 0); std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT /* VK_EXT_extended_dynamic_state3 */ + VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT /* VK_EXT_extended_dynamic_state3 */ }; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - VK_NULL_HANDLE, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, VK_NULL_HANDLE, 0); // Create graphics pipeline for dynamic rendering VkFormat color_rendering_format = get_render_context().get_format(); @@ -697,9 +639,8 @@ void DynamicMultisampleRasterization::prepare_pipelines() void DynamicMultisampleRasterization::prepare_gui_pipeline() { // Descriptor pool - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; - VkDescriptorPoolCreateInfo descriptorPoolInfo = vkb::initializers::descriptor_pool_create_info(pool_sizes, 2); + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; + VkDescriptorPoolCreateInfo descriptorPoolInfo = vkb::initializers::descriptor_pool_create_info(pool_sizes, 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptorPoolInfo, nullptr, &descriptor_pool_gui)); // Descriptor set layout @@ -712,10 +653,8 @@ void DynamicMultisampleRasterization::prepare_gui_pipeline() // Descriptor set VkDescriptorSetAllocateInfo descriptor_allocation = vkb::initializers::descriptor_set_allocate_info(descriptor_pool_gui, &descriptor_set_layout_gui, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_allocation, &descriptor_set_gui)); - VkDescriptorImageInfo font_descriptor = vkb::initializers::descriptor_image_info( - get_gui().get_sampler(), - get_gui().get_font_image_view(), - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkDescriptorImageInfo font_descriptor = + vkb::initializers::descriptor_image_info(get_gui().get_sampler(), get_gui().get_font_image_view(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); std::vector write_descriptor_sets = { vkb::initializers::write_descriptor_set(descriptor_set_gui, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &font_descriptor)}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); @@ -738,25 +677,19 @@ void DynamicMultisampleRasterization::prepare_gui_pipeline() blend_attachment_state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; blend_attachment_state.alphaBlendOp = VK_BLEND_OP_ADD; - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_ALWAYS); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT); std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT /* VK_EXT_extended_dynamic_state3 */ + VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_RASTERIZATION_SAMPLES_EXT /* VK_EXT_extended_dynamic_state3 */ }; - VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); + VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); std::vector shader_modules; @@ -827,10 +760,7 @@ void DynamicMultisampleRasterization::prepare_gui_pipeline() void DynamicMultisampleRasterization::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffer = std::make_unique(get_device(), - sizeof(uniform_data), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer = std::make_unique(get_device(), sizeof(uniform_data), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } diff --git a/samples/extensions/dynamic_primitive_clipping/dynamic_primitive_clipping.cpp b/samples/extensions/dynamic_primitive_clipping/dynamic_primitive_clipping.cpp index d924a29528..95d2d8ed84 100644 --- a/samples/extensions/dynamic_primitive_clipping/dynamic_primitive_clipping.cpp +++ b/samples/extensions/dynamic_primitive_clipping/dynamic_primitive_clipping.cpp @@ -59,7 +59,15 @@ bool DynamicPrimitiveClipping::prepare(const vkb::ApplicationOptions &options) load_assets(); // Setup parameters used on CPU. - visualization_names = {"World space X", "World space Y", "Half-space in world space coordinates", "Half-space in clip space coordinates", "Clip space X", "Clip space Y", "Euclidean distance to center", "Manhattan distance to center", "Chebyshev distance to center"}; + visualization_names = {"World space X", + "World space Y", + "Half-space in world space coordinates", + "Half-space in clip space coordinates", + "Clip space X", + "Clip space Y", + "Euclidean distance to center", + "Manhattan distance to center", + "Chebyshev distance to center"}; // Setup Vulkan objects required by GPU. prepare_uniform_buffers(); @@ -190,8 +198,7 @@ void DynamicPrimitiveClipping::on_update_ui_overlay(vkb::Drawer &drawer) rebuild_command_buffers(); } if (drawer.combo_box("Visualization", ¶ms.visualization, visualization_names)) - { - } + {} if (drawer.checkbox("Draw object 1", ¶ms.drawObject[0])) { rebuild_command_buffers(); @@ -240,10 +247,7 @@ void DynamicPrimitiveClipping::setup_layouts() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.models)); // Pipeline layout contains above defined descriptor set layout. - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.models, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.models, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.models)); } @@ -269,13 +273,16 @@ void DynamicPrimitiveClipping::prepare_pipelines() vertex_input.pVertexAttributeDescriptions = vertex_input_attributes.data(); // Specify we will use triangle lists to draw geometry. - VkPipelineInputAssemblyStateCreateInfo input_assembly = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); // Specify rasterization state. - VkPipelineRasterizationStateCreateInfo raster = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE); + VkPipelineRasterizationStateCreateInfo raster = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE); // Our attachment will write to all color channels, but no blending is enabled. - VkPipelineColorBlendAttachmentState blend_attachment = vkb::initializers::pipeline_color_blend_attachment_state(VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); VkPipelineColorBlendStateCreateInfo blend = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment); @@ -318,14 +325,10 @@ void DynamicPrimitiveClipping::prepare_pipelines() void DynamicPrimitiveClipping::prepare_uniform_buffers() { // We will render the same object twice using two different sets of parameters called "positive" and "negative". - uniform_buffers.buffer_positive = std::make_unique(get_device(), - sizeof(UBOVS), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); - uniform_buffers.buffer_negative = std::make_unique(get_device(), - sizeof(UBOVS), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.buffer_positive = + std::make_unique(get_device(), sizeof(UBOVS), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.buffer_negative = + std::make_unique(get_device(), sizeof(UBOVS), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -351,31 +354,25 @@ void DynamicPrimitiveClipping::update_uniform_buffers() void DynamicPrimitiveClipping::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2 * 4)}; - uint32_t num_descriptor_sets = 2 * 2 * 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2 * 4)}; + uint32_t num_descriptor_sets = 2 * 2 * 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void DynamicPrimitiveClipping::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.models, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.models, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.descriptor_positive)); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.descriptor_negative)); - std::vector descriptor_buffer_infos = { - create_descriptor(*uniform_buffers.buffer_positive), - create_descriptor(*uniform_buffers.buffer_negative)}; - std::vector write_descriptor_sets = { - vkb::initializers::write_descriptor_set(descriptor_sets.descriptor_positive, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &descriptor_buffer_infos[0]), - vkb::initializers::write_descriptor_set(descriptor_sets.descriptor_negative, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &descriptor_buffer_infos[1])}; + std::vector descriptor_buffer_infos = {create_descriptor(*uniform_buffers.buffer_positive), + create_descriptor(*uniform_buffers.buffer_negative)}; + std::vector write_descriptor_sets = { + vkb::initializers::write_descriptor_set(descriptor_sets.descriptor_positive, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &descriptor_buffer_infos[0]), + vkb::initializers::write_descriptor_set(descriptor_sets.descriptor_negative, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &descriptor_buffer_infos[1])}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); } diff --git a/samples/extensions/dynamic_rendering/dynamic_rendering.cpp b/samples/extensions/dynamic_rendering/dynamic_rendering.cpp index af98180959..1e5a14ec75 100644 --- a/samples/extensions/dynamic_rendering/dynamic_rendering.cpp +++ b/samples/extensions/dynamic_rendering/dynamic_rendering.cpp @@ -19,8 +19,7 @@ #include "dynamic_rendering.h" -DynamicRendering::DynamicRendering() : - enable_dynamic(true) +DynamicRendering::DynamicRendering() : enable_dynamic(true) { title = "Dynamic Rendering"; @@ -140,21 +139,14 @@ void DynamicRendering::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void DynamicRendering::create_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -169,11 +161,10 @@ void DynamicRendering::create_descriptor_sets() void DynamicRendering::create_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; - uint32_t num_descriptor_sets = 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; + uint32_t num_descriptor_sets = 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -181,55 +172,30 @@ void DynamicRendering::create_descriptor_pool() void DynamicRendering::create_pipeline() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); const auto color_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); - color_blend_state.attachmentCount = 1; - color_blend_state.pAttachments = &color_attachment_state; + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + color_blend_state.attachmentCount = 1; + color_blend_state.pAttachments = &color_attachment_state; // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Vertex bindings an attributes for model rendering // Binding description @@ -380,20 +346,11 @@ void DynamicRendering::build_command_buffers() if (enable_dynamic) { - vkb::image_layout_transition(draw_cmd_buffer, - swapchain_buffers[i].image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - 0, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - range); + vkb::image_layout_transition(draw_cmd_buffer, swapchain_buffers[i].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, range); - vkb::image_layout_transition(draw_cmd_buffer, - depth_stencil.image, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, + vkb::image_layout_transition(draw_cmd_buffer, depth_stencil.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, depth_range); VkRenderingAttachmentInfoKHR color_attachment_info = vkb::initializers::rendering_attachment_info(); @@ -427,10 +384,7 @@ void DynamicRendering::build_command_buffers() draw_ui(draw_cmd_buffer, i); - vkb::image_layout_transition(draw_cmd_buffer, - swapchain_buffers[i].image, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + vkb::image_layout_transition(draw_cmd_buffer, swapchain_buffers[i].image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, range); } else @@ -469,12 +423,10 @@ void DynamicRendering::render(float delta_time) } void DynamicRendering::view_changed() -{ -} +{} void DynamicRendering::on_update_ui_overlay(vkb::Drawer &drawer) -{ -} +{} std::unique_ptr create_dynamic_rendering() { diff --git a/samples/extensions/dynamic_rendering_local_read/dynamic_rendering_local_read.cpp b/samples/extensions/dynamic_rendering_local_read/dynamic_rendering_local_read.cpp index 9709d54d47..96608dd942 100644 --- a/samples/extensions/dynamic_rendering_local_read/dynamic_rendering_local_read.cpp +++ b/samples/extensions/dynamic_rendering_local_read/dynamic_rendering_local_read.cpp @@ -122,9 +122,11 @@ void DynamicRenderingLocalRead::setup_framebuffer() for (size_t i = 0; i < descriptor_image_infos.size(); i++) { - write_descriptor_sets.push_back(vkb::initializers::write_descriptor_set(composition_pass.descriptor_set, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, i, &descriptor_image_infos[i])); + write_descriptor_sets.push_back( + vkb::initializers::write_descriptor_set(composition_pass.descriptor_set, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, i, &descriptor_image_infos[i])); } - write_descriptor_sets.push_back(vkb::initializers::write_descriptor_set(scene_transparent_pass.descriptor_set, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 0, &descriptor_image_infos[0])); + write_descriptor_sets.push_back( + vkb::initializers::write_descriptor_set(scene_transparent_pass.descriptor_set, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 0, &descriptor_image_infos[0])); vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } @@ -220,14 +222,12 @@ void DynamicRenderingLocalRead::setup_render_pass() // First subpass: Fill G-Buffer components // ---------------------------------------------------------------------------------------- - VkAttachmentReference color_references[4] = { - {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, - {1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, - {2, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, - {3, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}}; + VkAttachmentReference color_references[4] = {{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, + {1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, + {2, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, + {3, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}}; - VkAttachmentReference depth_reference = - {4, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}; + VkAttachmentReference depth_reference = {4, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}; subpass_descriptions[0].pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass_descriptions[0].colorAttachmentCount = 4; @@ -434,8 +434,10 @@ void DynamicRenderingLocalRead::create_attachments() void DynamicRenderingLocalRead::prepare_buffers() { - buffers.ubo_vs = std::make_unique(get_device(), sizeof(shader_data_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); - buffers.ssbo_lights = std::make_unique(get_device(), lights.size() * sizeof(Light), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + buffers.ubo_vs = + std::make_unique(get_device(), sizeof(shader_data_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + buffers.ssbo_lights = + std::make_unique(get_device(), lights.size() * sizeof(Light), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffer(); update_lights_buffer(); @@ -451,9 +453,10 @@ void DynamicRenderingLocalRead::update_lights_buffer() for (auto &light : lights) { - light.position = glm::vec4(rnd_dist(rnd_gen) * light_range.x, 1.0f + std::abs(rnd_dist(rnd_gen)) * light_range.y, rnd_dist(rnd_gen) * light_range.z, 1.0f); - light.radius = 1.0f + std::abs(rnd_dist(rnd_gen)) * 3.0f; - light.color = glm::vec3(rnd_col(rnd_gen), rnd_col(rnd_gen), rnd_col(rnd_gen)) * 2.0f; + light.position = + glm::vec4(rnd_dist(rnd_gen) * light_range.x, 1.0f + std::abs(rnd_dist(rnd_gen)) * light_range.y, rnd_dist(rnd_gen) * light_range.z, 1.0f); + light.radius = 1.0f + std::abs(rnd_dist(rnd_gen)) * 3.0f; + light.color = glm::vec3(rnd_col(rnd_gen), rnd_col(rnd_gen), rnd_col(rnd_gen)) * 2.0f; } buffers.ssbo_lights->convert_and_update(lights); @@ -478,7 +481,8 @@ void DynamicRenderingLocalRead::prepare_layouts_and_descriptors() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &scene_opaque_pass.descriptor_set_layout)); // Transparent scene rendering (forward pass) @@ -488,7 +492,8 @@ void DynamicRenderingLocalRead::prepare_layouts_and_descriptors() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &scene_transparent_pass.descriptor_set_layout)); // Composition pass @@ -499,7 +504,8 @@ void DynamicRenderingLocalRead::prepare_layouts_and_descriptors() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 3), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &composition_pass.descriptor_set_layout)); // Pool @@ -593,15 +599,20 @@ void DynamicRenderingLocalRead::prepare_pipelines() VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &composition_pass.pipeline_layout)); // Pipelines - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo raster_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE); - VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); - VkPipelineColorBlendStateCreateInfo blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); - VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT); - std::array dynamic_states{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_states.data(), vkb::to_u32(dynamic_states.size())); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineRasterizationStateCreateInfo raster_state = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); + VkPipelineColorBlendStateCreateInfo blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1); + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT); + std::array dynamic_states{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic_state = + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_states.data(), vkb::to_u32(dynamic_states.size())); std::array shader_stages{}; // Vertex bindings an attributes for model rendering @@ -657,10 +668,8 @@ void DynamicRenderingLocalRead::prepare_pipelines() */ std::array blend_attachment_states = { - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)}; + vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), + vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)}; blend_state.attachmentCount = 4; blend_state.pAttachments = blend_attachment_states.data(); @@ -669,11 +678,8 @@ void DynamicRenderingLocalRead::prepare_pipelines() #if defined(USE_DYNAMIC_RENDERING) // For dynamic rendering, additional information muss be set at pipeline creation - VkFormat color_attachment_formats[4] = { - get_render_context().get_format(), - attachments.positionDepth.format, - attachments.normal.format, - attachments.albedo.format}; + VkFormat color_attachment_formats[4] = {get_render_context().get_format(), attachments.positionDepth.format, attachments.normal.format, + attachments.albedo.format}; pipeline_rendering_create_info.colorAttachmentCount = 4; pipeline_rendering_create_info.pColorAttachmentFormats = color_attachment_formats; @@ -750,10 +756,8 @@ void DynamicRenderingLocalRead::prepare_pipelines() #endif blend_attachment_states = { - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)}; + vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), + vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)}; pipeline_create_info.layout = composition_pass.pipeline_layout; @@ -840,7 +844,9 @@ void DynamicRenderingLocalRead::build_command_buffers() subresource_range_depth.levelCount = VK_REMAINING_MIP_LEVELS; subresource_range_depth.layerCount = VK_REMAINING_ARRAY_LAYERS; - vkb::image_layout_transition(cmd, swapchain_buffers[i].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, subresource_range_color); + vkb::image_layout_transition(cmd, swapchain_buffers[i].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, subresource_range_color); vkb::image_layout_transition(cmd, depth_stencil.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, subresource_range_depth); VkRenderingAttachmentInfoKHR color_attachment_info[4]{}; @@ -903,7 +909,8 @@ void DynamicRenderingLocalRead::build_command_buffers() vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, scene_opaque_pass.pipeline_layout, 0, 1, &scene_opaque_pass.descriptor_set, 0, nullptr); draw_scene(scenes.opaque, cmd, scene_opaque_pass.pipeline_layout); - // We want to read the input attachments in the next pass, with dynamic rendering local read this requires use of a barrier with the "by region" flag set + // We want to read the input attachments in the next pass, with dynamic rendering local read this requires use of a barrier with the "by region" flag + // set // A new feature of the dynamic rendering local read extension is the ability to use pipeline barriers in the dynamic render pass // to allow framebuffer-local dependencies (i.e. read-after-write) between draw calls using the "by region" flag @@ -934,7 +941,8 @@ void DynamicRenderingLocalRead::build_command_buffers() // Third draw // Render transparent geometry using a forward pass that compares against depth generated during the first draw vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, scene_transparent_pass.pipeline); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, scene_transparent_pass.pipeline_layout, 0, 1, &scene_transparent_pass.descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, scene_transparent_pass.pipeline_layout, 0, 1, &scene_transparent_pass.descriptor_set, 0, + nullptr); draw_scene(scenes.transparent, cmd, scene_transparent_pass.pipeline_layout); // End main rendering @@ -947,7 +955,8 @@ void DynamicRenderingLocalRead::build_command_buffers() Dynamic rendering end */ - vkb::image_layout_transition(cmd, swapchain_buffers[i].image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, subresource_range_color); + vkb::image_layout_transition(cmd, swapchain_buffers[i].image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + subresource_range_color); #else VkRenderPassBeginInfo render_pass_begin_info = vkb::initializers::render_pass_begin_info(); render_pass_begin_info.renderPass = render_pass; @@ -987,7 +996,8 @@ void DynamicRenderingLocalRead::build_command_buffers() vkCmdNextSubpass(cmd, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, scene_transparent_pass.pipeline); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, scene_transparent_pass.pipeline_layout, 0, 1, &scene_transparent_pass.descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, scene_transparent_pass.pipeline_layout, 0, 1, &scene_transparent_pass.descriptor_set, 0, + nullptr); draw_scene(scenes.transparent, cmd, scene_transparent_pass.pipeline_layout); draw_ui(draw_cmd_buffers[i]); diff --git a/samples/extensions/dynamic_rendering_local_read/dynamic_rendering_local_read.h b/samples/extensions/dynamic_rendering_local_read/dynamic_rendering_local_read.h index 1b34df5e92..c38d231c1f 100644 --- a/samples/extensions/dynamic_rendering_local_read/dynamic_rendering_local_read.h +++ b/samples/extensions/dynamic_rendering_local_read/dynamic_rendering_local_read.h @@ -107,8 +107,7 @@ class DynamicRenderingLocalRead : public ApiVulkanSample int32_t attachment_height{0}; std::array color_attachment_input_indices{VK_ATTACHMENT_UNUSED, 0, 1, 2}; - VkRenderingInputAttachmentIndexInfo rendering_attachment_index_info{VK_STRUCTURE_TYPE_RENDERING_INPUT_ATTACHMENT_INDEX_INFO_KHR, - nullptr, + VkRenderingInputAttachmentIndexInfo rendering_attachment_index_info{VK_STRUCTURE_TYPE_RENDERING_INPUT_ATTACHMENT_INDEX_INFO_KHR, nullptr, static_cast(color_attachment_input_indices.size()), color_attachment_input_indices.data()}; diff --git a/samples/extensions/extended_dynamic_state2/extended_dynamic_state2.cpp b/samples/extensions/extended_dynamic_state2/extended_dynamic_state2.cpp index 183ddc49b5..d4c5628e32 100644 --- a/samples/extensions/extended_dynamic_state2/extended_dynamic_state2.cpp +++ b/samples/extensions/extended_dynamic_state2/extended_dynamic_state2.cpp @@ -105,10 +105,7 @@ void ExtendedDynamicState2::load_assets() // Add node children to vector if they exist if (!node->get_children().empty()) { - node_scene_list.insert( - node_scene_list.end(), - node->get_children().begin(), - node->get_children().end()); + node_scene_list.insert(node_scene_list.end(), node->get_children().begin(), node->get_children().end()); } // If current node have mesh add it to scene_elements @@ -211,25 +208,16 @@ void ExtendedDynamicState2::create_pipelines() { /* Setup for first pipeline */ VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); rasterization_state.depthBiasConstantFactor = 1.0f; rasterization_state.depthBiasSlopeFactor = 1.0f; - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, - VK_TRUE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_TRUE); blend_attachment_state.colorBlendOp = VK_BLEND_OP_ADD; blend_attachment_state.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; @@ -238,28 +226,17 @@ void ExtendedDynamicState2::create_pipelines() blend_attachment_state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; blend_attachment_state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); /* Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept */ VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - VkPipelineTessellationStateCreateInfo tessellation_state = - vkb::initializers::pipeline_tessellation_state_create_info(3); + VkPipelineTessellationStateCreateInfo tessellation_state = vkb::initializers::pipeline_tessellation_state_create_info(3); std::vector dynamic_state_enables = { VK_DYNAMIC_STATE_VIEWPORT, @@ -270,10 +247,7 @@ void ExtendedDynamicState2::create_pipelines() VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE_EXT, }; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); /* Vertex bindings and attributes for model rendering */ /* Binding description */ @@ -318,12 +292,7 @@ void ExtendedDynamicState2::create_pipelines() graphics_create.pNext = VK_NULL_HANDLE; graphics_create.renderPass = render_pass; - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), - pipeline_cache, - 1, - &graphics_create, - VK_NULL_HANDLE, - &pipeline.baseline)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &graphics_create, VK_NULL_HANDLE, &pipeline.baseline)); /* Setup for second pipeline */ graphics_create.layout = pipeline_layouts.background; @@ -342,14 +311,9 @@ void ExtendedDynamicState2::create_pipelines() /* Attribute descriptions */ std::vector vertex_input_attributes_background = { - vkb::initializers::vertex_input_attribute_description(0, - 0, - VK_FORMAT_R32G32B32_SFLOAT, - 0), // Position - vkb::initializers::vertex_input_attribute_description(0, - 1, - VK_FORMAT_R32G32B32_SFLOAT, - offsetof(Vertex, normal)), // Normal + vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, + 0), // Position + vkb::initializers::vertex_input_attribute_description(0, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, normal)), // Normal }; vertex_input_state.vertexBindingDescriptionCount = static_cast(vertex_input_bindings_background.size()); @@ -362,12 +326,7 @@ void ExtendedDynamicState2::create_pipelines() shader_stages[0] = load_shader("extended_dynamic_state2", "background.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shader_stages[1] = load_shader("extended_dynamic_state2", "background.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), - pipeline_cache, - 1, - &graphics_create, - VK_NULL_HANDLE, - &pipeline.background)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &graphics_create, VK_NULL_HANDLE, &pipeline.background)); /* Setup for third pipeline */ graphics_create.pTessellationState = &tessellation_state; @@ -400,12 +359,7 @@ void ExtendedDynamicState2::create_pipelines() depth_stencil_state.depthTestEnable = VK_TRUE; /* Flip cull mode */ rasterization_state.cullMode = VK_CULL_MODE_FRONT_BIT; - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), - pipeline_cache, - 1, - &graphics_create, - VK_NULL_HANDLE, - &pipeline.tesselation)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &graphics_create, VK_NULL_HANDLE, &pipeline.tesselation)); } /** @@ -449,28 +403,14 @@ void ExtendedDynamicState2::build_command_buffers() vkCmdSetScissor(draw_cmd_buffer, 0, 1, &scissor); /* Binding background pipeline and descriptor sets */ - vkCmdBindDescriptorSets(draw_cmd_buffer, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layouts.background, - 0, - 1, - &descriptor_sets.background, - 0, - nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.background, 0, 1, &descriptor_sets.background, 0, nullptr); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.background); /* Drawing background */ draw_model(background_model, draw_cmd_buffer); /* Changing bindings to baseline pipeline and descriptor sets */ - vkCmdBindDescriptorSets(draw_cmd_buffer, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layouts.baseline, - 0, - 1, - &descriptor_sets.baseline, - 0, - nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.baseline, 0, 1, &descriptor_sets.baseline, 0, nullptr); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.baseline); /* Setting topology to triangle list and disabling primitive restart functionality */ @@ -488,14 +428,7 @@ void ExtendedDynamicState2::build_command_buffers() draw_created_model(draw_cmd_buffer); /* Changing bindings to tessellation pipeline */ - vkCmdBindDescriptorSets(draw_cmd_buffer, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layouts.tesselation, - 0, - 1, - &descriptor_sets.tesselation, - 0, - nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.tesselation, 0, 1, &descriptor_sets.tesselation, 0, nullptr); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.tesselation); /* Change topology to patch list and setting patch control points value */ @@ -527,10 +460,7 @@ void ExtendedDynamicState2::create_descriptor_pool() }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 3); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 3); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -543,96 +473,55 @@ void ExtendedDynamicState2::setup_descriptor_set_layout() { /* First descriptor set */ std::vector set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 1), }; VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), - &descriptor_layout_create_info, - nullptr, - &descriptor_set_layouts.baseline)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.baseline)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.baseline, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.baseline, 1); /* Pass scene node information via push constants */ - VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT, - sizeof(push_const_block), - 0); + VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT, sizeof(push_const_block), 0); pipeline_layout_create_info.pushConstantRangeCount = 1; pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; - VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), - &pipeline_layout_create_info, - nullptr, - &pipeline_layouts.baseline)); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.baseline)); /* Second descriptor set */ set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_VERTEX_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, 1), }; descriptor_layout_create_info.pBindings = set_layout_bindings.data(); descriptor_layout_create_info.bindingCount = static_cast(set_layout_bindings.size()); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), - &descriptor_layout_create_info, - nullptr, - &descriptor_set_layouts.tesselation)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.tesselation)); pipeline_layout_create_info.pSetLayouts = &descriptor_set_layouts.tesselation; pipeline_layout_create_info.setLayoutCount = 1; push_constant_range.stageFlags = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT; - VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), - &pipeline_layout_create_info, - nullptr, - &pipeline_layouts.tesselation)); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.tesselation)); /* Third descriptor set */ set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; descriptor_layout_create_info.pBindings = set_layout_bindings.data(); descriptor_layout_create_info.bindingCount = static_cast(set_layout_bindings.size()); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), - &descriptor_layout_create_info, - nullptr, - &descriptor_set_layouts.background)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.background)); pipeline_layout_create_info.pSetLayouts = &descriptor_set_layouts.background; pipeline_layout_create_info.setLayoutCount = 1; pipeline_layout_create_info.pushConstantRangeCount = 0; pipeline_layout_create_info.pPushConstantRanges = VK_NULL_HANDLE; - VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), - &pipeline_layout_create_info, - nullptr, - &pipeline_layouts.background)); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.background)); } /** @@ -642,11 +531,7 @@ void ExtendedDynamicState2::setup_descriptor_set_layout() void ExtendedDynamicState2::create_descriptor_sets() { /* First descriptor set */ - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.baseline, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.baseline, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.baseline)); @@ -654,71 +539,36 @@ void ExtendedDynamicState2::create_descriptor_sets() VkDescriptorBufferInfo matrix_baseline_buffer_descriptor = create_descriptor(*uniform_buffers.baseline); std::vector write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - descriptor_sets.baseline, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &matrix_common_buffer_descriptor), - vkb::initializers::write_descriptor_set( - descriptor_sets.baseline, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 1, - &matrix_baseline_buffer_descriptor)}; - - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkb::initializers::write_descriptor_set(descriptor_sets.baseline, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_common_buffer_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets.baseline, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &matrix_baseline_buffer_descriptor)}; + + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); /* Second descriptor set */ - alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.tesselation, - 1); + alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.tesselation, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.tesselation)); VkDescriptorBufferInfo matrix_tess_buffer_descriptor = create_descriptor(*uniform_buffers.tesselation); write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - descriptor_sets.tesselation, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &matrix_common_buffer_descriptor), - vkb::initializers::write_descriptor_set( - descriptor_sets.tesselation, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 1, - &matrix_tess_buffer_descriptor)}; - - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkb::initializers::write_descriptor_set(descriptor_sets.tesselation, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_common_buffer_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets.tesselation, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &matrix_tess_buffer_descriptor)}; + + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); /* Third descriptor set */ - alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.background, - 1); + alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.background, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.background)); VkDescriptorImageInfo background_image_descriptor = create_descriptor(textures.envmap); write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - descriptor_sets.background, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &matrix_common_buffer_descriptor), - vkb::initializers::write_descriptor_set( - descriptor_sets.background, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - 1, - &background_image_descriptor)}; - - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkb::initializers::write_descriptor_set(descriptor_sets.background, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_common_buffer_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets.background, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &background_image_descriptor)}; + + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); } /** @@ -897,12 +747,7 @@ void ExtendedDynamicState2::draw_from_scene(VkCommandBuffer command_buffer, std: { push_const_block.color = node_material->base_color_factor; } - vkCmdPushConstants(command_buffer, - pipeline_layouts.baseline, - VK_SHADER_STAGE_VERTEX_BIT, - 0, - sizeof(push_const_block), - &push_const_block); + vkCmdPushConstants(command_buffer, pipeline_layouts.baseline, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(push_const_block), &push_const_block); VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffer_pos.get(), offsets); @@ -923,12 +768,7 @@ void ExtendedDynamicState2::draw_created_model(VkCommandBuffer commandBuffer) { VkDeviceSize offsets[1] = {0}; push_const_block.color = glm::vec4{0.5f, 1.0f, 1.0f, 1.0f}; - vkCmdPushConstants(commandBuffer, - pipeline_layouts.baseline, - VK_SHADER_STAGE_VERTEX_BIT, - 0, - sizeof(push_const_block), - &push_const_block); + vkCmdPushConstants(commandBuffer, pipeline_layouts.baseline, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(push_const_block), &push_const_block); vkCmdBindVertexBuffers(commandBuffer, 0, 1, cube.vertices_pos->get(), offsets); vkCmdBindVertexBuffers(commandBuffer, 1, 1, cube.vertices_norm->get(), offsets); vkCmdBindIndexBuffer(commandBuffer, cube.indices->get_handle(), 0, VK_INDEX_TYPE_UINT32); @@ -986,37 +826,20 @@ void ExtendedDynamicState2::model_data_creation() cube.index_count = index_count; /* Array with vertices indexes for corresponding triangles */ - std::array indices{0, 4, 3, 7, - UINT32_MAX, - 1, 0, 2, 3, - UINT32_MAX, - 2, 6, 1, 5, - UINT32_MAX, - 1, 5, 0, 4, - UINT32_MAX, - 4, 5, 7, 6, - UINT32_MAX, - 2, 3, 6, 7}; + std::array indices{0, 4, 3, 7, UINT32_MAX, 1, 0, 2, 3, UINT32_MAX, 2, 6, 1, 5, UINT32_MAX, + 1, 5, 0, 4, UINT32_MAX, 4, 5, 7, 6, UINT32_MAX, 2, 3, 6, 7}; vkb::core::BufferC vertex_pos_staging = vkb::core::BufferC::create_staging_buffer(get_device(), vertices_pos); vkb::core::BufferC vertex_norm_staging = vkb::core::BufferC::create_staging_buffer(get_device(), vertices_norm); vkb::core::BufferC index_staging = vkb::core::BufferC::create_staging_buffer(get_device(), indices); - cube.vertices_pos = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | - VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); - - cube.vertices_norm = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | - VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); - - cube.indices = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + cube.vertices_pos = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + + cube.vertices_norm = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + + cube.indices = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); /* Copy from staging buffers */ @@ -1025,27 +848,12 @@ void ExtendedDynamicState2::model_data_creation() VkBufferCopy copy_region = {}; copy_region.size = vertex_buffer_size; - vkCmdCopyBuffer( - copy_command, - vertex_pos_staging.get_handle(), - cube.vertices_pos->get_handle(), - 1, - ©_region); - - vkCmdCopyBuffer( - copy_command, - vertex_norm_staging.get_handle(), - cube.vertices_norm->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, vertex_pos_staging.get_handle(), cube.vertices_pos->get_handle(), 1, ©_region); + + vkCmdCopyBuffer(copy_command, vertex_norm_staging.get_handle(), cube.vertices_norm->get_handle(), 1, ©_region); copy_region.size = index_buffer_size; - vkCmdCopyBuffer( - copy_command, - index_staging.get_handle(), - cube.indices->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, index_staging.get_handle(), cube.indices->get_handle(), 1, ©_region); get_device().flush_command_buffer(copy_command, queue, true); } @@ -1061,9 +869,9 @@ void ExtendedDynamicState2::cube_animation(float delta_time) constexpr float move_step = 0.0005f; static float time_pass = 0.0f; time_pass += delta_time; - static auto &transform = - std::ranges::find_if(scene_elements_baseline, [](SceneNode const &scene_node) { return scene_node.node->get_name() == "Cube_1"; }) - ->node->get_transform(); + static auto &transform = std::ranges::find_if(scene_elements_baseline, [](SceneNode const &scene_node) { + return scene_node.node->get_name() == "Cube_1"; + })->node->get_transform(); static auto translation = transform.get_translation(); static float difference = 0.0f; static bool rising = true; diff --git a/samples/extensions/fragment_density_map/fragment_density_map.cpp b/samples/extensions/fragment_density_map/fragment_density_map.cpp index 73801fc1cd..2cba0975cc 100644 --- a/samples/extensions/fragment_density_map/fragment_density_map.cpp +++ b/samples/extensions/fragment_density_map/fragment_density_map.cpp @@ -145,53 +145,29 @@ void FragmentDensityMap::setup_samplers() void FragmentDensityMap::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: A reversed depth buffer is used for increased precision, so larger depth values are retained. VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); // Specify that these states will be dynamic, i.e. not part of the pipeline state object. - std::array dynamic_state_enables{ - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::array dynamic_state_enables{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - vkb::to_u32(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), vkb::to_u32(dynamic_state_enables.size()), 0); VkDevice device_handle = get_device().get_handle(); // Load our SPIR-V shaders. @@ -199,11 +175,7 @@ void FragmentDensityMap::prepare_pipelines() VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - main_pass.meshes.pipeline.pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(main_pass.meshes.pipeline.pipeline_layout, render_pass, 0); pipeline_create_info.pInputAssemblyState = &input_assembly_state; pipeline_create_info.pRasterizationState = &rasterization_state; @@ -235,9 +207,8 @@ void FragmentDensityMap::prepare_pipelines() vertex_input_state.vertexAttributeDescriptionCount = attribute_descriptions.size(); shader_stages[0] = load_shader("fragment_density_map/forward.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); - shader_stages[1] = load_shader( - is_debug_fdm_enabled() ? "fragment_density_map/forward_debug.frag.spv" : "fragment_density_map/forward.frag.spv", - VK_SHADER_STAGE_FRAGMENT_BIT); + shader_stages[1] = load_shader(is_debug_fdm_enabled() ? "fragment_density_map/forward_debug.frag.spv" : "fragment_density_map/forward.frag.spv", + VK_SHADER_STAGE_FRAGMENT_BIT); pipeline_create_info.layout = main_pass.meshes.pipeline.pipeline_layout; pipeline_create_info.renderPass = render_pass; @@ -257,9 +228,8 @@ void FragmentDensityMap::prepare_pipelines() depth_stencil_state.depthWriteEnable = VK_FALSE; depth_stencil_state.depthTestEnable = VK_FALSE; shader_stages[0] = quad_uvw_shader_stage; - shader_stages[1] = load_shader( - is_debug_fdm_enabled() ? "fragment_density_map/sky_debug.frag.spv" : "fragment_density_map/sky.frag.spv", - VK_SHADER_STAGE_FRAGMENT_BIT); + shader_stages[1] = + load_shader(is_debug_fdm_enabled() ? "fragment_density_map/sky_debug.frag.spv" : "fragment_density_map/sky.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); // The vertex shader generates a full-screen quad procedurally. // No vertex buffers are required because the vertex positions are computed in the shader itself. @@ -305,7 +275,8 @@ void FragmentDensityMap::prepare_pipelines() .layout = fdm.generate.pipeline.pipeline_layout, }; VK_CHECK(vkCreateComputePipelines(device_handle, VK_NULL_HANDLE, 1, &pipeline_create_info, nullptr, &fdm.generate.pipeline.pipeline)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE, get_object_handle(fdm.generate.pipeline.pipeline), "Generate FDM Pipeline (compute)"); + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE, get_object_handle(fdm.generate.pipeline.pipeline), + "Generate FDM Pipeline (compute)"); } else { @@ -321,7 +292,8 @@ void FragmentDensityMap::prepare_pipelines() shader_stages[1] = load_shader("fragment_density_map/generate_density_map.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK(vkCreateGraphicsPipelines(device_handle, pipeline_cache, 1, &pipeline_create_info, nullptr, &fdm.generate.pipeline.pipeline)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE, get_object_handle(fdm.generate.pipeline.pipeline), "Generate FDM Pipeline (fragment)"); + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE, get_object_handle(fdm.generate.pipeline.pipeline), + "Generate FDM Pipeline (fragment)"); } } } @@ -342,11 +314,14 @@ void FragmentDensityMap::build_command_buffers() render_pass_begin_info.pClearValues = clear_values.data(); assert((main_pass.extend.height > 0) && (main_pass.extend.width > 0)); - VkRect2D main_scissor = vkb::initializers::rect2D(main_pass.extend.width, main_pass.extend.height, 0, 0); - VkViewport main_viewport = vkb::initializers::viewport(static_cast(main_scissor.extent.width), static_cast(main_scissor.extent.height), 0.0f, 1.0f); + VkRect2D main_scissor = vkb::initializers::rect2D(main_pass.extend.width, main_pass.extend.height, 0, 0); + VkViewport main_viewport = + vkb::initializers::viewport(static_cast(main_scissor.extent.width), static_cast(main_scissor.extent.height), 0.0f, 1.0f); - VkRect2D present_scissor = vkb::initializers::rect2D(get_render_context().get_surface_extent().width, get_render_context().get_surface_extent().height, 0, 0); - VkViewport present_viewport = vkb::initializers::viewport(static_cast(present_scissor.extent.width), static_cast(present_scissor.extent.height), 0.0f, 1.0f); + VkRect2D present_scissor = + vkb::initializers::rect2D(get_render_context().get_surface_extent().width, get_render_context().get_surface_extent().height, 0, 0); + VkViewport present_viewport = + vkb::initializers::viewport(static_cast(present_scissor.extent.width), static_cast(present_scissor.extent.height), 0.0f, 1.0f); for (int32_t i = 0; i < draw_cmd_buffers.size(); ++i) { @@ -394,28 +369,19 @@ void FragmentDensityMap::build_command_buffers() debug_utils.cmd_begin_label(cmd_buffer, mesh_data.submesh->get_name().c_str(), glm::vec4()); - vkCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, main_pass.meshes.pipeline.pipeline_layout, 0, 1, &main_pass.meshes.descriptor_sets[mesh_idx], 0, NULL); + vkCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, main_pass.meshes.pipeline.pipeline_layout, 0, 1, + &main_pass.meshes.descriptor_sets[mesh_idx], 0, NULL); - auto &vertex_buffer = mesh_data.submesh->vertex_buffers.at("position"); - auto &normal_buffer = mesh_data.submesh->vertex_buffers.at("normal"); - auto &uv_buffer = mesh_data.submesh->vertex_buffers.at("texcoord_0"); - std::array vertex_buffers = { - vertex_buffer.get_handle(), - normal_buffer.get_handle(), - uv_buffer.get_handle()}; + auto &vertex_buffer = mesh_data.submesh->vertex_buffers.at("position"); + auto &normal_buffer = mesh_data.submesh->vertex_buffers.at("normal"); + auto &uv_buffer = mesh_data.submesh->vertex_buffers.at("texcoord_0"); + std::array vertex_buffers = {vertex_buffer.get_handle(), normal_buffer.get_handle(), uv_buffer.get_handle()}; std::array vertex_offsets = {0, 0, 0}; - vkCmdBindVertexBuffers(cmd_buffer, 0, - vertex_buffers.size(), - vertex_buffers.data(), - vertex_offsets.data()); - vkCmdBindIndexBuffer(cmd_buffer, - mesh_data.submesh->index_buffer->get_handle(), - mesh_data.submesh->index_offset, + vkCmdBindVertexBuffers(cmd_buffer, 0, vertex_buffers.size(), vertex_buffers.data(), vertex_offsets.data()); + vkCmdBindIndexBuffer(cmd_buffer, mesh_data.submesh->index_buffer->get_handle(), mesh_data.submesh->index_offset, mesh_data.submesh->index_type); - vkCmdDrawIndexed(cmd_buffer, - mesh_data.submesh->vertex_indices, - 1, 0, 0, 0); + vkCmdDrawIndexed(cmd_buffer, mesh_data.submesh->vertex_indices, 1, 0, 0, 0); debug_utils.cmd_end_label(cmd_buffer); } @@ -432,15 +398,9 @@ void FragmentDensityMap::build_command_buffers() { VkImageSubresourceRange subresource_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - vkb::image_layout_transition(cmd_buffer, - fdm.image.image, - VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - subresource_range); + vkb::image_layout_transition(cmd_buffer, fdm.image.image, VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); } render_pass_begin_info.renderArea.extent = present_scissor.extent; render_pass_begin_info.renderPass = present.render_pass; @@ -470,15 +430,10 @@ void FragmentDensityMap::build_command_buffers() if (is_show_fdm_enabled() && !is_update_fdm_enabled()) { VkImageSubresourceRange subresource_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - vkb::image_layout_transition(cmd_buffer, - fdm.image.image, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, - VK_ACCESS_SHADER_READ_BIT, - VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, - subresource_range); + vkb::image_layout_transition(cmd_buffer, fdm.image.image, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, VK_ACCESS_SHADER_READ_BIT, + VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, subresource_range); } debug_utils.cmd_end_label(cmd_buffer); } @@ -625,15 +580,11 @@ void FragmentDensityMap::load_assets() bool negative_scale = glm::any(glm::lessThanEqual(node->get_transform().get_scale(), glm::vec3(0.0f))); const auto &color_texture_it = mesh_material->textures.find("base_color_texture"); // Cull double-sided/transparent/negatively-scaled/non-textured meshes. - if (!negative_scale && - !mesh_material->double_sided && - mesh_material->alpha_mode == vkb::sg::AlphaMode::Opaque && + if (!negative_scale && !mesh_material->double_sided && mesh_material->alpha_mode == vkb::sg::AlphaMode::Opaque && color_texture_it != mesh_material->textures.end()) { SubmeshData &mesh_data = scene_data.emplace_back(std::move(SubmeshData{ - .submesh = submesh, - .world_matrix = node->get_transform().get_world_matrix(), - .base_color_texture = color_texture_it->second})); + .submesh = submesh, .world_matrix = node->get_transform().get_world_matrix(), .base_color_texture = color_texture_it->second})); } else { @@ -651,19 +602,17 @@ void FragmentDensityMap::setup_descriptor_pool_main_pass() assert(main_pass.descriptor_pool == VK_NULL_HANDLE); const uint32_t max_sets = vkb::to_u32(scene_data.size()); - std::array pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, vkb::to_u32(scene_data.size())), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, vkb::to_u32(scene_data.size())), - }; + std::array pool_sizes = { + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, vkb::to_u32(scene_data.size())), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, vkb::to_u32(scene_data.size())), + }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - vkb::to_u32(pool_sizes.size()), - pool_sizes.data(), max_sets); + vkb::initializers::descriptor_pool_create_info(vkb::to_u32(pool_sizes.size()), pool_sizes.data(), max_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &main_pass.descriptor_pool)); - debug_utils.set_debug_name(get_device().get_handle(), VK_OBJECT_TYPE_DESCRIPTOR_POOL, get_object_handle(main_pass.descriptor_pool), "Main pass descriptor pool"); + debug_utils.set_debug_name(get_device().get_handle(), VK_OBJECT_TYPE_DESCRIPTOR_POOL, get_object_handle(main_pass.descriptor_pool), + "Main pass descriptor pool"); } void FragmentDensityMap::setup_additional_descriptor_pool() @@ -671,17 +620,14 @@ void FragmentDensityMap::setup_additional_descriptor_pool() vkDestroyDescriptorPool(get_device().get_handle(), descriptor_pool, nullptr); const uint32_t max_sets = 2; // generate_fdm + present. - std::array pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1), - }; + std::array pool_sizes = { + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1), + }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - vkb::to_u32(pool_sizes.size()), - pool_sizes.data(), max_sets); + vkb::initializers::descriptor_pool_create_info(vkb::to_u32(pool_sizes.size()), pool_sizes.data(), max_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); debug_utils.set_debug_name(get_device().get_handle(), VK_OBJECT_TYPE_DESCRIPTOR_POOL, get_object_handle(descriptor_pool), "Additional Descriptor Pool"); @@ -695,58 +641,44 @@ void FragmentDensityMap::setup_descriptor_set_layout_main_pass() // Main pass glTF-submesh. { - std::array set_layout_bindings = - { - // Binding 0 : Vertex shader uniform buffer. - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - // Binding 1 : Fragment shader combined sampler. - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), - }; + std::array set_layout_bindings = { + // Binding 0 : Vertex shader uniform buffer. + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Fragment shader combined sampler. + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), + }; descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - vkb::to_u32(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), vkb::to_u32(set_layout_bindings.size())); - pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &main_pass.meshes.pipeline.set_layout, 1); + pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&main_pass.meshes.pipeline.set_layout, 1); assert(main_pass.meshes.pipeline.set_layout == VK_NULL_HANDLE); VK_CHECK(vkCreateDescriptorSetLayout(device_handle, &descriptor_layout_create_info, nullptr, &main_pass.meshes.pipeline.set_layout)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, - get_object_handle(main_pass.meshes.pipeline.set_layout), "Submeshes Descriptor Set Layout"); + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, get_object_handle(main_pass.meshes.pipeline.set_layout), + "Submeshes Descriptor Set Layout"); assert(main_pass.meshes.pipeline.pipeline_layout == VK_NULL_HANDLE); VK_CHECK(vkCreatePipelineLayout(device_handle, &pipeline_layout_create_info, nullptr, &main_pass.meshes.pipeline.pipeline_layout)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE_LAYOUT, - get_object_handle(main_pass.meshes.pipeline.pipeline_layout), "Submeshes Pipeline Layout"); + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE_LAYOUT, get_object_handle(main_pass.meshes.pipeline.pipeline_layout), + "Submeshes Pipeline Layout"); } // Sky { - descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info(nullptr, 0); + descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(nullptr, 0); - pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &main_pass.sky_pipeline.set_layout, 1); + pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&main_pass.sky_pipeline.set_layout, 1); assert(main_pass.sky_pipeline.set_layout == VK_NULL_HANDLE); VK_CHECK(vkCreateDescriptorSetLayout(device_handle, &descriptor_layout_create_info, nullptr, &main_pass.sky_pipeline.set_layout)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, - get_object_handle(main_pass.sky_pipeline.set_layout), "Sky Descriptor Set Layout"); + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, get_object_handle(main_pass.sky_pipeline.set_layout), + "Sky Descriptor Set Layout"); assert(main_pass.sky_pipeline.pipeline_layout == VK_NULL_HANDLE); VK_CHECK(vkCreatePipelineLayout(device_handle, &pipeline_layout_create_info, nullptr, &main_pass.sky_pipeline.pipeline_layout)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE_LAYOUT, - get_object_handle(main_pass.sky_pipeline.pipeline_layout), "Sky Pipeline Layout"); + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE_LAYOUT, get_object_handle(main_pass.sky_pipeline.pipeline_layout), + "Sky Pipeline Layout"); } } @@ -754,55 +686,36 @@ void FragmentDensityMap::setup_descriptor_set_layout_fdm() { VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info; VkPipelineLayoutCreateInfo pipeline_layout_create_info; - VkDevice device_handle = get_device().get_handle(); - std::array compute_set_layout_bindings = - { - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_COMPUTE_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, - VK_SHADER_STAGE_COMPUTE_BIT, - 1), - }; - std::array fragment_set_layout_bindings = - { - // Binding 0: Fragment shader uniform buffer. - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 0)}; + VkDevice device_handle = get_device().get_handle(); + std::array compute_set_layout_bindings = { + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 1), + }; + std::array fragment_set_layout_bindings = { + // Binding 0: Fragment shader uniform buffer. + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 0)}; if (is_generate_fdm_compute()) { descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info( - compute_set_layout_bindings.data(), - vkb::to_u32(compute_set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(compute_set_layout_bindings.data(), vkb::to_u32(compute_set_layout_bindings.size())); } else { descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info( - fragment_set_layout_bindings.data(), - vkb::to_u32(fragment_set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(fragment_set_layout_bindings.data(), vkb::to_u32(fragment_set_layout_bindings.size())); } - pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &fdm.generate.pipeline.set_layout, 1); + pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&fdm.generate.pipeline.set_layout, 1); vkDestroyDescriptorSetLayout(device_handle, fdm.generate.pipeline.set_layout, nullptr); VK_CHECK(vkCreateDescriptorSetLayout(device_handle, &descriptor_layout_create_info, nullptr, &fdm.generate.pipeline.set_layout)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, - get_object_handle(fdm.generate.pipeline.set_layout), + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, get_object_handle(fdm.generate.pipeline.set_layout), is_generate_fdm_compute() ? "Generate FDM (Compute) Descriptor Set Layout" : "Generate FDM (Fragment) Descriptor Set Layout"); vkDestroyPipelineLayout(device_handle, fdm.generate.pipeline.pipeline_layout, nullptr); VK_CHECK(vkCreatePipelineLayout(device_handle, &pipeline_layout_create_info, nullptr, &fdm.generate.pipeline.pipeline_layout)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE_LAYOUT, - get_object_handle(fdm.generate.pipeline.pipeline_layout), + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_PIPELINE_LAYOUT, get_object_handle(fdm.generate.pipeline.pipeline_layout), is_generate_fdm_compute() ? "Generate FDM (Compute) Pipeline Layout" : "Generate FDM (Fragment) Pipeline Layout"); } @@ -810,30 +723,22 @@ void FragmentDensityMap::setup_descriptor_set_layout_present() { VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info; VkPipelineLayoutCreateInfo pipeline_layout_create_info; - VkDevice device_handle = get_device().get_handle(); - std::array set_layout_bindings = - { - // Binding 0 : Fragment shader combined sampler. - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 0), - }; - - descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - vkb::to_u32(set_layout_bindings.size())); - - pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &present.pipeline.set_layout, 1); + VkDevice device_handle = get_device().get_handle(); + std::array set_layout_bindings = { + // Binding 0 : Fragment shader combined sampler. + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0), + }; + + descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), vkb::to_u32(set_layout_bindings.size())); + + pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&present.pipeline.set_layout, 1); set_layout_bindings[0].pImmutableSamplers = (is_fdm_enabled() && !is_show_fdm_enabled()) ? &samplers.subsampled_nearest : &samplers.nearest; vkDestroyDescriptorSetLayout(device_handle, present.pipeline.set_layout, nullptr); VK_CHECK(vkCreateDescriptorSetLayout(device_handle, &descriptor_layout_create_info, nullptr, &present.pipeline.set_layout)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, get_object_handle(present.pipeline.set_layout), "Present Descriptor Set Layout"); + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, get_object_handle(present.pipeline.set_layout), + "Present Descriptor Set Layout"); vkDestroyPipelineLayout(device_handle, present.pipeline.pipeline_layout, nullptr); VK_CHECK(vkCreatePipelineLayout(device_handle, &pipeline_layout_create_info, nullptr, &present.pipeline.pipeline_layout)); @@ -850,7 +755,8 @@ void FragmentDensityMap::setup_descriptor_set_main_pass() auto &mesh_data = scene_data[i]; auto &mesh_descriptor = main_pass.meshes.descriptor_sets[i]; - VkDescriptorSetAllocateInfo descriptor_set_alloc_info = vkb::initializers::descriptor_set_allocate_info(main_pass.descriptor_pool, &main_pass.meshes.pipeline.set_layout, 1); + VkDescriptorSetAllocateInfo descriptor_set_alloc_info = + vkb::initializers::descriptor_set_allocate_info(main_pass.descriptor_pool, &main_pass.meshes.pipeline.set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(device_handle, &descriptor_set_alloc_info, &mesh_descriptor)); std::string debug_name = fmt::format("Descriptor Set glTF submesh-{} <{}>", i, mesh_data.submesh->get_name()); @@ -859,13 +765,13 @@ void FragmentDensityMap::setup_descriptor_set_main_pass() VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*mesh_data.vertex_ubo); VkDescriptorImageInfo image_descriptor = vkb::initializers::descriptor_image_info( mesh_data.base_color_texture->get_sampler()->get_core_sampler().get_handle(), - mesh_data.base_color_texture->get_image()->get_vk_image_view().get_handle(), - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - std::array write_descriptor_sets = - { - vkb::initializers::write_descriptor_set(mesh_descriptor, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer. - vkb::initializers::write_descriptor_set(mesh_descriptor, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &image_descriptor) // Binding 1 : Color map. - }; + mesh_data.base_color_texture->get_image()->get_vk_image_view().get_handle(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + std::array write_descriptor_sets = { + vkb::initializers::write_descriptor_set(mesh_descriptor, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, + &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer. + vkb::initializers::write_descriptor_set(mesh_descriptor, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, + &image_descriptor) // Binding 1 : Color map. + }; vkUpdateDescriptorSets(device_handle, vkb::to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); } } @@ -874,44 +780,33 @@ void FragmentDensityMap::setup_descriptor_set_fdm() { VkDescriptorSetAllocateInfo descriptor_set_alloc_info; VkDevice device_handle = get_device().get_handle(); - descriptor_set_alloc_info = vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, &fdm.generate.pipeline.set_layout, 1); + descriptor_set_alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &fdm.generate.pipeline.set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(device_handle, &descriptor_set_alloc_info, &fdm.generate.set)); - debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET, - get_object_handle(fdm.generate.set), - is_generate_fdm_compute() ? "Descriptor set Generate FDM (Compute)" : - "Descriptor set Generate FDM (Fragment)"); + debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET, get_object_handle(fdm.generate.set), + is_generate_fdm_compute() ? "Descriptor set Generate FDM (Compute)" : "Descriptor set Generate FDM (Fragment)"); - VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*fdm.ubo); - VkDescriptorImageInfo image_descriptor = vkb::initializers::descriptor_image_info( - samplers.nearest, - fdm.image.view, - VK_IMAGE_LAYOUT_GENERAL); + VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*fdm.ubo); + VkDescriptorImageInfo image_descriptor = vkb::initializers::descriptor_image_info(samplers.nearest, fdm.image.view, VK_IMAGE_LAYOUT_GENERAL); std::array write_descriptor_sets = { vkb::initializers::write_descriptor_set(fdm.generate.set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), vkb::initializers::write_descriptor_set(fdm.generate.set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor)}; - vkUpdateDescriptorSets(device_handle, - is_generate_fdm_compute() ? vkb::to_u32(write_descriptor_sets.size()) : 1u, - write_descriptor_sets.data(), 0, NULL); + vkUpdateDescriptorSets(device_handle, is_generate_fdm_compute() ? vkb::to_u32(write_descriptor_sets.size()) : 1u, write_descriptor_sets.data(), 0, NULL); } void FragmentDensityMap::setup_descriptor_set_present() { VkDescriptorSetAllocateInfo descriptor_set_alloc_info; VkDevice device_handle = get_device().get_handle(); - descriptor_set_alloc_info = vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, &present.pipeline.set_layout, 1); + descriptor_set_alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &present.pipeline.set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(device_handle, &descriptor_set_alloc_info, &present.set)); debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_DESCRIPTOR_SET, get_object_handle(present.set), "Descriptor set Present"); - VkDescriptorImageInfo image_descriptor = vkb::initializers::descriptor_image_info( - (is_fdm_enabled() && !is_show_fdm_enabled()) ? samplers.subsampled_nearest : samplers.nearest, - is_show_fdm_enabled() ? fdm.image.view : main_pass.image.view, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + VkDescriptorImageInfo image_descriptor = + vkb::initializers::descriptor_image_info((is_fdm_enabled() && !is_show_fdm_enabled()) ? samplers.subsampled_nearest : samplers.nearest, + is_show_fdm_enabled() ? fdm.image.view : main_pass.image.view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); std::array write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - present.set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &image_descriptor)}; + vkb::initializers::write_descriptor_set(present.set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &image_descriptor)}; vkUpdateDescriptorSets(device_handle, vkb::to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } @@ -920,15 +815,14 @@ void FragmentDensityMap::prepare_uniform_buffers_main_pass() // Create uniform buffers for each glTF-submesh. for (auto &mesh_data : scene_data) { - mesh_data.vertex_ubo = std::make_unique( - get_device(), sizeof(UBOVS), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + mesh_data.vertex_ubo = + std::make_unique(get_device(), sizeof(UBOVS), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } } void FragmentDensityMap::prepare_uniform_buffers_fdm() { - fdm.ubo = std::make_unique( - get_device(), sizeof(FDMUBO), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + fdm.ubo = std::make_unique(get_device(), sizeof(FDMUBO), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); fdm.ubo_data = {}; // Reset so that the GPU UBO is updated. update_uniform_buffer(0.0f); } @@ -937,8 +831,7 @@ void FragmentDensityMap::update_uniform_buffer(float delta_time) { // Main pass glTF-submeshes UBO. { - UBOVS ubo_vs{ - .projection = camera.matrices.perspective}; + UBOVS ubo_vs{.projection = camera.matrices.perspective}; for (auto &mesh_data : scene_data) { @@ -968,11 +861,10 @@ void FragmentDensityMap::update_uniform_buffer(float delta_time) const float rotating_center_radius = 0.12f * min_dimension; FDMUBO new_fdm_data{ - .eye_center = { - static_cast(fdm.extend.width) * 0.5f + rotating_center_radius * sin(frame_angle), - static_cast(fdm.extend.height) * 0.5f + rotating_center_radius * cos(frame_angle), - 0.0f, 0.0f}, - .circle_radius = {min_dimension * radius_factor_1x1, min_dimension * radius_factor_1x2, min_dimension * radius_factor_2x2, min_dimension * radius_factor_2x4}, + .eye_center = {static_cast(fdm.extend.width) * 0.5f + rotating_center_radius * sin(frame_angle), + static_cast(fdm.extend.height) * 0.5f + rotating_center_radius * cos(frame_angle), 0.0f, 0.0f}, + .circle_radius = {min_dimension * radius_factor_1x1, min_dimension * radius_factor_1x2, min_dimension * radius_factor_2x2, + min_dimension * radius_factor_2x4}, }; if (fdm.ubo_data != new_fdm_data) @@ -1012,8 +904,7 @@ void FragmentDensityMap::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) available_options.supports_fdm = false; if (gpu.is_extension_supported(VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME)) { - const auto &supported_extension_features = - gpu.get_extension_features(); + const auto &supported_extension_features = gpu.get_extension_features(); if (!supported_extension_features.fragmentDensityMap) { @@ -1048,22 +939,20 @@ void FragmentDensityMap::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) else { VkPhysicalDeviceProperties2KHR device_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - VkPhysicalDeviceFragmentDensityMapPropertiesEXT physical_device_FRAGMENT_DENSITY_MAP_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_PROPERTIES_EXT}; + VkPhysicalDeviceFragmentDensityMapPropertiesEXT physical_device_FRAGMENT_DENSITY_MAP_properties{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_PROPERTIES_EXT}; device_properties.pNext = &physical_device_FRAGMENT_DENSITY_MAP_properties; vkGetPhysicalDeviceProperties2KHR(gpu.get_handle(), &device_properties); - LOGI("FDM enable: FDM min texel size={}x{} FDM max texel size={}x{}", - physical_device_FRAGMENT_DENSITY_MAP_properties.minFragmentDensityTexelSize.width, + LOGI("FDM enable: FDM min texel size={}x{} FDM max texel size={}x{}", physical_device_FRAGMENT_DENSITY_MAP_properties.minFragmentDensityTexelSize.width, physical_device_FRAGMENT_DENSITY_MAP_properties.minFragmentDensityTexelSize.height, physical_device_FRAGMENT_DENSITY_MAP_properties.maxFragmentDensityTexelSize.width, physical_device_FRAGMENT_DENSITY_MAP_properties.maxFragmentDensityTexelSize.height); - fdm.texel_size.width = std::clamp(fdm.texel_size.width, - physical_device_FRAGMENT_DENSITY_MAP_properties.minFragmentDensityTexelSize.width, + fdm.texel_size.width = std::clamp(fdm.texel_size.width, physical_device_FRAGMENT_DENSITY_MAP_properties.minFragmentDensityTexelSize.width, physical_device_FRAGMENT_DENSITY_MAP_properties.maxFragmentDensityTexelSize.width); - fdm.texel_size.height = std::clamp(fdm.texel_size.height, - physical_device_FRAGMENT_DENSITY_MAP_properties.minFragmentDensityTexelSize.height, + fdm.texel_size.height = std::clamp(fdm.texel_size.height, physical_device_FRAGMENT_DENSITY_MAP_properties.minFragmentDensityTexelSize.height, physical_device_FRAGMENT_DENSITY_MAP_properties.maxFragmentDensityTexelSize.height); } last_options = current_options; @@ -1077,15 +966,8 @@ void FragmentDensityMap::write_density_map(VkCommandBuffer cmd_buffer) VkImageSubresourceRange subresource_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; // Clear the density map buffer by transitioning it from UNDEFINED. - vkb::image_layout_transition(cmd_buffer, - fdm.image.image, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - {}, - VK_ACCESS_SHADER_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_GENERAL, - subresource_range); + vkb::image_layout_transition(cmd_buffer, fdm.image.image, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, {}, + VK_ACCESS_SHADER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, subresource_range); vkCmdBindPipeline(cmd_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, fdm.generate.pipeline.pipeline); vkCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, fdm.generate.pipeline.pipeline_layout, 0, 1, &fdm.generate.set, 0, nullptr); @@ -1097,15 +979,9 @@ void FragmentDensityMap::write_density_map(VkCommandBuffer cmd_buffer) if (is_fdm_enabled()) { - vkb::image_layout_transition(cmd_buffer, - fdm.image.image, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, - VK_IMAGE_LAYOUT_GENERAL, - VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, - subresource_range); + vkb::image_layout_transition(cmd_buffer, fdm.image.image, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT, + VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT, VK_IMAGE_LAYOUT_GENERAL, + VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, subresource_range); } debug_utils.cmd_end_label(cmd_buffer); } @@ -1113,10 +989,9 @@ void FragmentDensityMap::write_density_map(VkCommandBuffer cmd_buffer) { debug_utils.cmd_begin_label(cmd_buffer, "Write FDM (fragment)", glm::vec4()); - VkClearValue clear_value{ - .color = {{0.0f, 0.0f, 0.0f, 0.0f}}}; - VkRect2D scissor = vkb::initializers::rect2D(fdm.extend.width, fdm.extend.height, 0, 0); - VkViewport viewport = vkb::initializers::viewport(static_cast(scissor.extent.width), static_cast(scissor.extent.height), 0.0f, 1.0f); + VkClearValue clear_value{.color = {{0.0f, 0.0f, 0.0f, 0.0f}}}; + VkRect2D scissor = vkb::initializers::rect2D(fdm.extend.width, fdm.extend.height, 0, 0); + VkViewport viewport = vkb::initializers::viewport(static_cast(scissor.extent.width), static_cast(scissor.extent.height), 0.0f, 1.0f); VkRenderPassBeginInfo render_pass_begin_info = vkb::initializers::render_pass_begin_info(); render_pass_begin_info.renderPass = fdm.generate.render_pass; @@ -1129,12 +1004,7 @@ void FragmentDensityMap::write_density_map(VkCommandBuffer cmd_buffer) vkCmdBeginRenderPass(cmd_buffer, &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, fdm.generate.pipeline.pipeline); - vkCmdBindDescriptorSets(cmd_buffer, - VK_PIPELINE_BIND_POINT_GRAPHICS, - fdm.generate.pipeline.pipeline_layout, - 0, 1, - &fdm.generate.set, - 0, nullptr); + vkCmdBindDescriptorSets(cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, fdm.generate.pipeline.pipeline_layout, 0, 1, &fdm.generate.set, 0, nullptr); vkCmdSetViewport(cmd_buffer, 0, 1, &viewport); vkCmdSetScissor(cmd_buffer, 0, 1, &scissor); @@ -1158,95 +1028,85 @@ void FragmentDensityMap::setup_render_pass() VkDevice device_handle = get_device().get_handle(); // Main render pass (forward render). { - std::array attachments{ - // Color attachment. - VkAttachmentDescription2{ - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, - .pNext = nullptr, - .flags = 0, - .format = get_render_context().get_format(), - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - // Depth attachment. - VkAttachmentDescription2{ - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, - .pNext = nullptr, - .flags = 0, - .format = depth_format, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}, - - // Density map attachment. - VkAttachmentDescription2{ - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, - .pNext = nullptr, - .flags = 0, - .format = VK_FORMAT_R8G8_UNORM, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, - .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = density_map_initial_layout, - .finalLayout = density_map_initial_layout}}; - - VkAttachmentReference2 color_attachment_ref{ - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, - .pNext = nullptr, - .attachment = 0, - .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT}; - - VkAttachmentReference2 depth_reference = { - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, - .pNext = nullptr, - .attachment = 1, - .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT}; - - VkSubpassDescription2 subpass{ - .sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2, - .pNext = nullptr, - .flags = 0, - .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, - .viewMask = 0u, - .inputAttachmentCount = 0, - .pInputAttachments = nullptr, - .colorAttachmentCount = 1, - .pColorAttachments = &color_attachment_ref, - .pResolveAttachments = nullptr, - .pDepthStencilAttachment = &depth_reference, - .preserveAttachmentCount = 0, - .pPreserveAttachments = nullptr}; - - VkSubpassDependency2 dependency{ - .sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, - .pNext = nullptr, - .srcSubpass = 0, - .dstSubpass = VK_SUBPASS_EXTERNAL, - .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - .dstAccessMask = VK_ACCESS_SHADER_READ_BIT, - .dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT, - .viewOffset = 0}; + std::array attachments{// Color attachment. + VkAttachmentDescription2{.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, + .pNext = nullptr, + .flags = 0, + .format = get_render_context().get_format(), + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + // Depth attachment. + VkAttachmentDescription2{.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, + .pNext = nullptr, + .flags = 0, + .format = depth_format, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}, + + // Density map attachment. + VkAttachmentDescription2{.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, + .pNext = nullptr, + .flags = 0, + .format = VK_FORMAT_R8G8_UNORM, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = density_map_initial_layout, + .finalLayout = density_map_initial_layout}}; + + VkAttachmentReference2 color_attachment_ref{.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, + .pNext = nullptr, + .attachment = 0, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT}; + + VkAttachmentReference2 depth_reference = {.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, + .pNext = nullptr, + .attachment = 1, + .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT}; + + VkSubpassDescription2 subpass{.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2, + .pNext = nullptr, + .flags = 0, + .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, + .viewMask = 0u, + .inputAttachmentCount = 0, + .pInputAttachments = nullptr, + .colorAttachmentCount = 1, + .pColorAttachments = &color_attachment_ref, + .pResolveAttachments = nullptr, + .pDepthStencilAttachment = &depth_reference, + .preserveAttachmentCount = 0, + .pPreserveAttachments = nullptr}; + + VkSubpassDependency2 dependency{.sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, + .pNext = nullptr, + .srcSubpass = 0, + .dstSubpass = VK_SUBPASS_EXTERNAL, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + .dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT, + .viewOffset = 0}; VkRenderPassFragmentDensityMapCreateInfoEXT density_map_info{ .sType = VK_STRUCTURE_TYPE_RENDER_PASS_FRAGMENT_DENSITY_MAP_CREATE_INFO_EXT, .pNext = nullptr, - .fragmentDensityMapAttachment{ - .attachment = 2, - .layout = density_map_initial_layout}, + .fragmentDensityMapAttachment{.attachment = 2, .layout = density_map_initial_layout}, }; VkRenderPassCreateInfo2 render_pass_info{ @@ -1271,66 +1131,60 @@ void FragmentDensityMap::setup_render_pass() // Write FDM (fragment). if (is_fdm_enabled() && !is_generate_fdm_compute()) { - std::array attachments{ - VkAttachmentDescription2{ - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, - .pNext = nullptr, - .flags = 0, - .format = VK_FORMAT_R8G8_UNORM, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .finalLayout = VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT}}; - - VkAttachmentReference2 attachment_ref{ - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, - .pNext = nullptr, - .attachment = 0, - .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT}; - - VkSubpassDescription2 subpass{ - .sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2, - .pNext = nullptr, - .flags = 0, - .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, - .viewMask = 0, - .inputAttachmentCount = 0, - .pInputAttachments = nullptr, - .colorAttachmentCount = 1, - .pColorAttachments = &attachment_ref, - .pResolveAttachments = nullptr, - .pDepthStencilAttachment = nullptr, - .preserveAttachmentCount = 0, - .pPreserveAttachments = nullptr}; - - VkSubpassDependency2 dependency{ - .sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, - .pNext = nullptr, - .srcSubpass = VK_SUBPASS_EXTERNAL, - .dstSubpass = 0, - .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .srcAccessMask = 0, - .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - .dependencyFlags = 0, - .viewOffset = 0}; - - VkRenderPassCreateInfo2 render_pass_info{ - .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2, - .pNext = nullptr, - .flags = 0, - .attachmentCount = attachments.size(), - .pAttachments = attachments.data(), - .subpassCount = 1, - .pSubpasses = &subpass, - .dependencyCount = 1, - .pDependencies = &dependency, - .correlatedViewMaskCount = 0, - .pCorrelatedViewMasks = nullptr}; + std::array attachments{VkAttachmentDescription2{.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, + .pNext = nullptr, + .flags = 0, + .format = VK_FORMAT_R8G8_UNORM, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .finalLayout = VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT}}; + + VkAttachmentReference2 attachment_ref{.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, + .pNext = nullptr, + .attachment = 0, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT}; + + VkSubpassDescription2 subpass{.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2, + .pNext = nullptr, + .flags = 0, + .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, + .viewMask = 0, + .inputAttachmentCount = 0, + .pInputAttachments = nullptr, + .colorAttachmentCount = 1, + .pColorAttachments = &attachment_ref, + .pResolveAttachments = nullptr, + .pDepthStencilAttachment = nullptr, + .preserveAttachmentCount = 0, + .pPreserveAttachments = nullptr}; + + VkSubpassDependency2 dependency{.sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, + .pNext = nullptr, + .srcSubpass = VK_SUBPASS_EXTERNAL, + .dstSubpass = 0, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dependencyFlags = 0, + .viewOffset = 0}; + + VkRenderPassCreateInfo2 render_pass_info{.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2, + .pNext = nullptr, + .flags = 0, + .attachmentCount = attachments.size(), + .pAttachments = attachments.data(), + .subpassCount = 1, + .pSubpasses = &subpass, + .dependencyCount = 1, + .pDependencies = &dependency, + .correlatedViewMaskCount = 0, + .pCorrelatedViewMasks = nullptr}; vkDestroyRenderPass(device_handle, fdm.generate.render_pass, nullptr); VK_CHECK(vkCreateRenderPass2KHR(device_handle, &render_pass_info, nullptr, &fdm.generate.render_pass)); @@ -1338,66 +1192,60 @@ void FragmentDensityMap::setup_render_pass() } // Present { - std::array attachments{ - VkAttachmentDescription2{ - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, - .pNext = nullptr, - .flags = 0, - .format = get_render_context().get_format(), - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR}}; - - VkAttachmentReference2 attachment_ref{ - .sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, - .pNext = nullptr, - .attachment = 0, - .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT}; - - VkSubpassDescription2 subpass{ - .sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2, - .pNext = nullptr, - .flags = 0, - .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, - .viewMask = 0, - .inputAttachmentCount = 0, - .pInputAttachments = nullptr, - .colorAttachmentCount = 1, - .pColorAttachments = &attachment_ref, - .pResolveAttachments = nullptr, - .pDepthStencilAttachment = nullptr, - .preserveAttachmentCount = 0, - .pPreserveAttachments = nullptr}; - - VkSubpassDependency2 dependency{ - .sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, - .pNext = nullptr, - .srcSubpass = VK_SUBPASS_EXTERNAL, - .dstSubpass = 0, - .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .srcAccessMask = 0, - .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - .dependencyFlags = 0, - .viewOffset = 0}; - - VkRenderPassCreateInfo2 render_pass_info{ - .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2, - .pNext = nullptr, - .flags = 0, - .attachmentCount = attachments.size(), - .pAttachments = attachments.data(), - .subpassCount = 1, - .pSubpasses = &subpass, - .dependencyCount = 1, - .pDependencies = &dependency, - .correlatedViewMaskCount = 0, - .pCorrelatedViewMasks = nullptr}; + std::array attachments{VkAttachmentDescription2{.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2, + .pNext = nullptr, + .flags = 0, + .format = get_render_context().get_format(), + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR}}; + + VkAttachmentReference2 attachment_ref{.sType = VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, + .pNext = nullptr, + .attachment = 0, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT}; + + VkSubpassDescription2 subpass{.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2, + .pNext = nullptr, + .flags = 0, + .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, + .viewMask = 0, + .inputAttachmentCount = 0, + .pInputAttachments = nullptr, + .colorAttachmentCount = 1, + .pColorAttachments = &attachment_ref, + .pResolveAttachments = nullptr, + .pDepthStencilAttachment = nullptr, + .preserveAttachmentCount = 0, + .pPreserveAttachments = nullptr}; + + VkSubpassDependency2 dependency{.sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, + .pNext = nullptr, + .srcSubpass = VK_SUBPASS_EXTERNAL, + .dstSubpass = 0, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dependencyFlags = 0, + .viewOffset = 0}; + + VkRenderPassCreateInfo2 render_pass_info{.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2, + .pNext = nullptr, + .flags = 0, + .attachmentCount = attachments.size(), + .pAttachments = attachments.data(), + .subpassCount = 1, + .pSubpasses = &subpass, + .dependencyCount = 1, + .pDependencies = &dependency, + .correlatedViewMaskCount = 0, + .pCorrelatedViewMasks = nullptr}; vkDestroyRenderPass(device_handle, present.render_pass, nullptr); VK_CHECK(vkCreateRenderPass2KHR(device_handle, &render_pass_info, nullptr, &present.render_pass)); @@ -1410,19 +1258,16 @@ void FragmentDensityMap::setup_framebuffer() // Main pass framebuffer. { - std::array attachments{ - main_pass.image.view, - depth_stencil.view, - fdm.image.view}; - VkFramebufferCreateInfo framebuffer_create_info{ - .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, - .pNext = nullptr, - .renderPass = render_pass, - .attachmentCount = is_fdm_enabled() ? vkb::to_u32(attachments.size()) : (vkb::to_u32(attachments.size()) - 1u), - .pAttachments = attachments.data(), - .width = main_pass.extend.width, - .height = main_pass.extend.height, - .layers = 1}; + std::array attachments{main_pass.image.view, depth_stencil.view, fdm.image.view}; + VkFramebufferCreateInfo framebuffer_create_info{.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, + .pNext = nullptr, + .renderPass = render_pass, + .attachmentCount = + is_fdm_enabled() ? vkb::to_u32(attachments.size()) : (vkb::to_u32(attachments.size()) - 1u), + .pAttachments = attachments.data(), + .width = main_pass.extend.width, + .height = main_pass.extend.height, + .layers = 1}; vkDestroyFramebuffer(device_handle, main_pass.framebuffer, nullptr); VK_CHECK(vkCreateFramebuffer(device_handle, &framebuffer_create_info, nullptr, &main_pass.framebuffer)); @@ -1440,14 +1285,13 @@ void FragmentDensityMap::setup_framebuffer() } } - VkFramebufferCreateInfo framebuffer_create_info{ - .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, - .pNext = nullptr, - .renderPass = present.render_pass, - .attachmentCount = 1, - .width = get_render_context().get_surface_extent().width, - .height = get_render_context().get_surface_extent().height, - .layers = 1}; + VkFramebufferCreateInfo framebuffer_create_info{.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, + .pNext = nullptr, + .renderPass = present.render_pass, + .attachmentCount = 1, + .width = get_render_context().get_surface_extent().width, + .height = get_render_context().get_surface_extent().height, + .layers = 1}; // Create framebuffers for every swap chain image. framebuffers.resize(get_render_context().get_render_frames().size()); @@ -1470,15 +1314,14 @@ void FragmentDensityMap::setup_framebuffer() if (is_fdm_enabled() && !is_generate_fdm_compute()) { std::array attachments{fdm.image.view}; - VkFramebufferCreateInfo framebuffer_create_info{ - .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, - .pNext = nullptr, - .renderPass = fdm.generate.render_pass, - .attachmentCount = vkb::to_u32(attachments.size()), - .pAttachments = attachments.data(), - .width = fdm.extend.width, - .height = fdm.extend.height, - .layers = 1}; + VkFramebufferCreateInfo framebuffer_create_info{.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, + .pNext = nullptr, + .renderPass = fdm.generate.render_pass, + .attachmentCount = vkb::to_u32(attachments.size()), + .pAttachments = attachments.data(), + .width = fdm.extend.width, + .height = fdm.extend.height, + .layers = 1}; VK_CHECK(vkCreateFramebuffer(device_handle, &framebuffer_create_info, nullptr, &fdm.generate.framebuffer)); debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_FRAMEBUFFER, get_object_handle(fdm.generate.framebuffer), "Write FDM Framebuffer"); @@ -1494,16 +1337,13 @@ void FragmentDensityMap::update_extents() { // Rendering at 4× the resolution to make performance improvements more noticeable. glm::vec2 rendering_factor{4.0f, 4.0f}; - fdm.extend = { - std::max(1u, - static_cast(std::ceil(static_cast(rendering_factor.x * get_render_context().get_surface_extent().width) / static_cast(fdm.texel_size.width)))), - std::max(1u, - static_cast(std::ceil(static_cast(rendering_factor.y * get_render_context().get_surface_extent().height) / static_cast(fdm.texel_size.height)))), - 1}; + fdm.extend = {std::max(1u, static_cast(std::ceil(static_cast(rendering_factor.x * get_render_context().get_surface_extent().width) / + static_cast(fdm.texel_size.width)))), + std::max(1u, static_cast(std::ceil(static_cast(rendering_factor.y * get_render_context().get_surface_extent().height) / + static_cast(fdm.texel_size.height)))), + 1}; - main_pass.extend = { - fdm.extend.width * fdm.texel_size.width, - fdm.extend.height * fdm.texel_size.height}; + main_pass.extend = {fdm.extend.width * fdm.texel_size.width, fdm.extend.height * fdm.texel_size.height}; camera.update_aspect_ratio(static_cast(main_pass.extend.width) / static_cast(main_pass.extend.height)); } @@ -1520,17 +1360,16 @@ void FragmentDensityMap::setup_depth_stencil() // Create depth stencil image. { // This sample needs to add the subsampled flag so we cannot use the framework function. - VkImageCreateInfo image_create_info{ - .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, - .flags = is_fdm_enabled() ? VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT : 0u, - .imageType = VK_IMAGE_TYPE_2D, - .format = depth_format, - .extent{main_pass.extend.width, main_pass.extend.height, 1}, - .mipLevels = 1, - .arrayLayers = 1, - .samples = VK_SAMPLE_COUNT_1_BIT, - .tiling = VK_IMAGE_TILING_OPTIMAL, - .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT}; + VkImageCreateInfo image_create_info{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .flags = is_fdm_enabled() ? VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT : 0u, + .imageType = VK_IMAGE_TYPE_2D, + .format = depth_format, + .extent{main_pass.extend.width, main_pass.extend.height, 1}, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT}; VkDevice device_handle = get_device().get_handle(); VK_CHECK(vkCreateImage(device_handle, &image_create_info, nullptr, &depth_stencil.image)); @@ -1539,10 +1378,10 @@ void FragmentDensityMap::setup_depth_stencil() VkMemoryRequirements memReqs{}; vkGetImageMemoryRequirements(device_handle, depth_stencil.image, &memReqs); - VkMemoryAllocateInfo memory_allocation{ - .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - .allocationSize = memReqs.size, - .memoryTypeIndex = get_device().get_gpu().get_memory_type(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)}; + VkMemoryAllocateInfo memory_allocation{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = memReqs.size, + .memoryTypeIndex = + get_device().get_gpu().get_memory_type(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)}; VK_CHECK(vkAllocateMemory(device_handle, &memory_allocation, nullptr, &depth_stencil.mem)); VK_CHECK(vkBindImageMemory(device_handle, depth_stencil.image, depth_stencil.mem, 0)); @@ -1551,12 +1390,7 @@ void FragmentDensityMap::setup_depth_stencil() .image = depth_stencil.image, .viewType = VK_IMAGE_VIEW_TYPE_2D, .format = depth_format, - .subresourceRange{ - .aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1}}; + .subresourceRange{.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}}; // Stencil aspect should only be set on depth + stencil formats. if (depth_format >= VK_FORMAT_D16_UNORM_S8_UINT) { @@ -1577,17 +1411,16 @@ void FragmentDensityMap::setup_color() // Create images used to render the framebuffer. // Note: We need to add the subsampled flag. - VkImageCreateInfo image_create_info{ - .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, - .flags = is_fdm_enabled() ? VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT : 0u, - .imageType = VK_IMAGE_TYPE_2D, - .format = get_render_context().get_format(), - .extent{main_pass.extend.width, main_pass.extend.height, 1}, - .mipLevels = 1, - .arrayLayers = 1, - .samples = VK_SAMPLE_COUNT_1_BIT, - .tiling = VK_IMAGE_TILING_OPTIMAL, - .usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT}; + VkImageCreateInfo image_create_info{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .flags = is_fdm_enabled() ? VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT : 0u, + .imageType = VK_IMAGE_TYPE_2D, + .format = get_render_context().get_format(), + .extent{main_pass.extend.width, main_pass.extend.height, 1}, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT}; VkDevice device_handle = get_device().get_handle(); VK_CHECK(vkCreateImage(device_handle, &image_create_info, nullptr, &main_pass.image.image)); @@ -1597,27 +1430,25 @@ void FragmentDensityMap::setup_color() VkMemoryRequirements mem_reqs{}; vkGetImageMemoryRequirements(device_handle, main_pass.image.image, &mem_reqs); - VkMemoryAllocateInfo mem_alloc{ - .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - .allocationSize = mem_reqs.size, - .memoryTypeIndex = get_device().get_gpu().get_memory_type(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)}; + VkMemoryAllocateInfo mem_alloc{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = mem_reqs.size, + .memoryTypeIndex = get_device().get_gpu().get_memory_type(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)}; VK_CHECK(vkAllocateMemory(device_handle, &mem_alloc, nullptr, &main_pass.image.mem)); VK_CHECK(vkBindImageMemory(device_handle, main_pass.image.image, main_pass.image.mem, 0)); - VkImageViewCreateInfo image_view_create_info{ - .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, - .pNext = nullptr, - .image = main_pass.image.image, - .viewType = VK_IMAGE_VIEW_TYPE_2D, - .format = get_render_context().get_format(), - .components = vkb::initializers::component_mapping(), - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }}; + VkImageViewCreateInfo image_view_create_info{.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .pNext = nullptr, + .image = main_pass.image.image, + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = get_render_context().get_format(), + .components = vkb::initializers::component_mapping(), + .subresourceRange = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }}; VK_CHECK(vkCreateImageView(device_handle, &image_view_create_info, nullptr, &main_pass.image.view)); debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_IMAGE_VIEW, get_object_handle(main_pass.image.view), "Main pass color image view"); } @@ -1668,17 +1499,16 @@ void FragmentDensityMap::setup_fragment_density_map() return; } - VkImageCreateInfo image_create_info{ - .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, - .flags = 0u, - .imageType = VK_IMAGE_TYPE_2D, - .format = VK_FORMAT_R8G8_UNORM, - .extent = fdm.extend, - .mipLevels = 1, - .arrayLayers = 1, - .samples = VK_SAMPLE_COUNT_1_BIT, - .tiling = VK_IMAGE_TILING_OPTIMAL, - .usage = 0u}; + VkImageCreateInfo image_create_info{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .flags = 0u, + .imageType = VK_IMAGE_TYPE_2D, + .format = VK_FORMAT_R8G8_UNORM, + .extent = fdm.extend, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = 0u}; if (is_generate_fdm_compute()) { @@ -1706,28 +1536,26 @@ void FragmentDensityMap::setup_fragment_density_map() VkMemoryRequirements mem_reqs{}; vkGetImageMemoryRequirements(device_handle, fdm.image.image, &mem_reqs); - VkMemoryAllocateInfo mem_alloc{ - .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - .allocationSize = mem_reqs.size, - .memoryTypeIndex = get_device().get_gpu().get_memory_type(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)}; + VkMemoryAllocateInfo mem_alloc{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = mem_reqs.size, + .memoryTypeIndex = get_device().get_gpu().get_memory_type(mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)}; VK_CHECK(vkAllocateMemory(device_handle, &mem_alloc, nullptr, &fdm.image.mem)); VK_CHECK(vkBindImageMemory(device_handle, fdm.image.image, fdm.image.mem, 0)); - VkImageViewCreateInfo image_view_create_info{ - .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, - .pNext = nullptr, - .flags = is_update_fdm_enabled() ? VK_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT : 0u, - .image = fdm.image.image, - .viewType = VK_IMAGE_VIEW_TYPE_2D, - .format = VK_FORMAT_R8G8_UNORM, - .components = vkb::initializers::component_mapping(), - .subresourceRange = { - .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }}; + VkImageViewCreateInfo image_view_create_info{.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .pNext = nullptr, + .flags = is_update_fdm_enabled() ? VK_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT : 0u, + .image = fdm.image.image, + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = VK_FORMAT_R8G8_UNORM, + .components = vkb::initializers::component_mapping(), + .subresourceRange = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }}; VK_CHECK(vkCreateImageView(device_handle, &image_view_create_info, nullptr, &fdm.image.view)); debug_utils.set_debug_name(device_handle, VK_OBJECT_TYPE_IMAGE_VIEW, get_object_handle(fdm.image.view), "FDM Image View"); @@ -1735,19 +1563,18 @@ void FragmentDensityMap::setup_fragment_density_map() void FragmentDensityMap::prepare_gui() { - vkb::CounterSamplingConfig config{ - .mode = vkb::CounterSamplingMode::Continuous, - .speed = 0.1f}; - get_stats().request_stats({ - vkb::StatIndex::frame_times, - vkb::StatIndex::gpu_cycles, - }, - config); + vkb::CounterSamplingConfig config{.mode = vkb::CounterSamplingMode::Continuous, .speed = 0.1f}; + get_stats().request_stats( + { + vkb::StatIndex::frame_times, + vkb::StatIndex::gpu_cycles, + }, + config); create_gui(*window, &get_stats(), 15.0f, true); - get_gui().prepare(pipeline_cache, present.render_pass, - {load_shader("uioverlay/uioverlay.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), - load_shader("uioverlay/uioverlay.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}); + get_gui().prepare( + pipeline_cache, present.render_pass, + {load_shader("uioverlay/uioverlay.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), load_shader("uioverlay/uioverlay.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}); } void FragmentDensityMap::on_update_ui_overlay(vkb::Drawer &drawer) diff --git a/samples/extensions/fragment_shader_barycentric/fragment_shader_barycentric.cpp b/samples/extensions/fragment_shader_barycentric/fragment_shader_barycentric.cpp index 8661eaf56d..37ba884cf2 100644 --- a/samples/extensions/fragment_shader_barycentric/fragment_shader_barycentric.cpp +++ b/samples/extensions/fragment_shader_barycentric/fragment_shader_barycentric.cpp @@ -103,10 +103,9 @@ void FragmentShaderBarycentric::prepare_uniform_buffers() */ void FragmentShaderBarycentric::create_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -138,14 +137,10 @@ void FragmentShaderBarycentric::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); // Pass selected effect information via push constants - VkPushConstantRange push_constant_range = - vkb::initializers::push_constant_range(VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(gui_settings.selected_effect), 0); + VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(gui_settings.selected_effect), 0); pipeline_layout_create_info.pushConstantRangeCount = 1; pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; @@ -158,11 +153,7 @@ void FragmentShaderBarycentric::setup_descriptor_set_layout() */ void FragmentShaderBarycentric::create_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.skybox)); @@ -188,51 +179,26 @@ void FragmentShaderBarycentric::create_descriptor_sets() void FragmentShaderBarycentric::create_pipeline() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Vertex bindings an attributes for model rendering // Binding description @@ -337,7 +303,8 @@ void FragmentShaderBarycentric::build_command_buffers() // object vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_sets.object, 0, nullptr); - vkCmdPushConstants(draw_cmd_buffer, pipeline_layout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(gui_settings.selected_effect), &gui_settings.selected_effect); + vkCmdPushConstants(draw_cmd_buffer, pipeline_layout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(gui_settings.selected_effect), + &gui_settings.selected_effect); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.object); draw_model(object, draw_cmd_buffer); diff --git a/samples/extensions/fragment_shader_barycentric/fragment_shader_barycentric.h b/samples/extensions/fragment_shader_barycentric/fragment_shader_barycentric.h index 63f8c6c0cb..49bae3bbb6 100644 --- a/samples/extensions/fragment_shader_barycentric/fragment_shader_barycentric.h +++ b/samples/extensions/fragment_shader_barycentric/fragment_shader_barycentric.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Mobica Limited +/* Copyright (c) 2023-2026, Mobica Limited * * SPDX-License-Identifier: Apache-2.0 * @@ -37,10 +37,7 @@ class FragmentShaderBarycentric : public ApiVulkanSample struct GUI_settings { int selected_effect = 0; /* default interpolation */ - const std::vector effect_names = {"Color interpolation", - "Perspective vs non-perspective", - "Wireframe", - "Interpolate to mass center", + const std::vector effect_names = {"Color interpolation", "Perspective vs non-perspective", "Wireframe", "Interpolate to mass center", "Barycoord texture"}; } gui_settings; diff --git a/samples/extensions/fragment_shading_rate/fragment_shading_rate.cpp b/samples/extensions/fragment_shading_rate/fragment_shading_rate.cpp index 3edfc0064f..64b2855c79 100644 --- a/samples/extensions/fragment_shading_rate/fragment_shading_rate.cpp +++ b/samples/extensions/fragment_shading_rate/fragment_shading_rate.cpp @@ -77,9 +77,11 @@ void FragmentShadingRate::create_shading_rate_attachment() // Shading rate image size depends on shading rate texel size // For each texel in the target image, there is a corresponding shading texel size width x height block in the shading rate image VkExtent3D image_extent{}; - image_extent.width = static_cast(ceil(width / static_cast(physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.width))); - image_extent.height = static_cast(ceil(height / static_cast(physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.height))); - image_extent.depth = 1; + image_extent.width = static_cast( + ceil(width / static_cast(physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.width))); + image_extent.height = static_cast( + ceil(height / static_cast(physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.height))); + image_extent.depth = 1; VkImageCreateInfo image_create_info{}; image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; @@ -192,8 +194,8 @@ void FragmentShadingRate::create_shading_rate_attachment() vkCmdCopyBufferToImage(copy_cmd, staging_buffer.get_handle(), shading_rate_image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); // Transfer image layout to fragment shading rate attachment layout required to access this in the renderpass - vkb::image_layout_transition( - copy_cmd, shading_rate_image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR); + vkb::image_layout_transition(copy_cmd, shading_rate_image.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR); get_device().flush_command_buffer(copy_cmd, queue, true); } @@ -278,8 +280,10 @@ void FragmentShadingRate::setup_render_pass() VkFragmentShadingRateAttachmentInfoKHR fragment_shading_rate_attachment_info = {}; fragment_shading_rate_attachment_info.sType = VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR; fragment_shading_rate_attachment_info.pFragmentShadingRateAttachment = &fragment_shading_rate_reference; - fragment_shading_rate_attachment_info.shadingRateAttachmentTexelSize.width = physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.width; - fragment_shading_rate_attachment_info.shadingRateAttachmentTexelSize.height = physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.height; + fragment_shading_rate_attachment_info.shadingRateAttachmentTexelSize.width = + physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.width; + fragment_shading_rate_attachment_info.shadingRateAttachmentTexelSize.height = + physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.height; VkSubpassDescription2KHR subpass_description = {}; subpass_description.sType = VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2; @@ -297,21 +301,25 @@ void FragmentShadingRate::setup_render_pass() // Subpass dependencies for layout transitions std::array dependencies = {}; - dependencies[0].sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2; - dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; - dependencies[0].dstSubpass = 0; - dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; - dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + dependencies[0].sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2; + dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; + dependencies[0].dstSubpass = 0; + dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[0].dstStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; + dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - dependencies[1].sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2; - dependencies[1].srcSubpass = 0; - dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; - dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; - dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + dependencies[1].sType = VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2; + dependencies[1].srcSubpass = 0; + dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; + dependencies[1].srcStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; @@ -442,7 +450,8 @@ void FragmentShadingRate::build_command_buffers() { vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skysphere); push_const_block.object_type = 0; - vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), &push_const_block); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), + &push_const_block); vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr); draw_model(models.skysphere, draw_cmd_buffers[i]); } @@ -458,7 +467,8 @@ void FragmentShadingRate::build_command_buffers() { push_const_block.object_type = 1; push_const_block.offset = glm::vec4(mesh_offsets[j], 0.0f); - vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), &push_const_block); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), + &push_const_block); draw_model(models.scene, draw_cmd_buffers[i]); } @@ -480,11 +490,10 @@ void FragmentShadingRate::load_assets() void FragmentShadingRate::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; - uint32_t num_descriptor_sets = 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; + uint32_t num_descriptor_sets = 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -503,11 +512,11 @@ void FragmentShadingRate::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); // Pass object offset and color via push constant - VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); + VkPushConstantRange push_constant_range = + vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); pipeline_layout_create_info.pushConstantRangeCount = 1; pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; @@ -517,8 +526,7 @@ void FragmentShadingRate::setup_descriptor_set_layout() void FragmentShadingRate::setup_descriptor_sets() { // Shared model object descriptor set - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -536,59 +544,30 @@ void FragmentShadingRate::setup_descriptor_sets() void FragmentShadingRate::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - // Add fragment shading rate dynamic state, so we can easily toggle this at runtime - VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, + // Add fragment shading rate dynamic state, so we can easily toggle this at runtime + VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); std::vector blend_attachment_states = { vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), @@ -643,10 +622,8 @@ void FragmentShadingRate::prepare_pipelines() void FragmentShadingRate::prepare_uniform_buffers() { - uniform_buffers.scene = std::make_unique(get_device(), - sizeof(ubo_scene), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.scene = + std::make_unique(get_device(), sizeof(ubo_scene), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } diff --git a/samples/extensions/fragment_shading_rate_dynamic/fragment_shading_rate_dynamic.cpp b/samples/extensions/fragment_shading_rate_dynamic/fragment_shading_rate_dynamic.cpp index b7858d9717..93ab4f7a3c 100644 --- a/samples/extensions/fragment_shading_rate_dynamic/fragment_shading_rate_dynamic.cpp +++ b/samples/extensions/fragment_shading_rate_dynamic/fragment_shading_rate_dynamic.cpp @@ -17,8 +17,7 @@ #include "fragment_shading_rate_dynamic.h" -FragmentShadingRateDynamic::FragmentShadingRateDynamic() : - pipeline_layout(VK_NULL_HANDLE), pipelines(), descriptor_set_layout(), subpass_extent() +FragmentShadingRateDynamic::FragmentShadingRateDynamic() : pipeline_layout(VK_NULL_HANDLE), pipelines(), descriptor_set_layout(), subpass_extent() { title = "Dynamic fragment shading rate"; @@ -79,9 +78,8 @@ void FragmentShadingRateDynamic::create_shading_rate_attachment() compute_buffers.clear(); compute_buffers.resize(draw_cmd_buffers.size()); - subpass_extent = VkExtent2D{ - static_cast(ceil(static_cast(width) / static_cast(subpass_extent_ratio))), - static_cast(ceil(static_cast(height) / static_cast(subpass_extent_ratio)))}; + subpass_extent = VkExtent2D{static_cast(ceil(static_cast(width) / static_cast(subpass_extent_ratio))), + static_cast(ceil(static_cast(height) / static_cast(subpass_extent_ratio)))}; for (auto &&compute_buffer : compute_buffers) { @@ -104,31 +102,23 @@ void FragmentShadingRateDynamic::create_shading_rate_attachment() // which we label here for clarity const uint32_t frame_width = width, frame_height = height; VkExtent3D image_extent{}; - image_extent.width = static_cast(ceil(static_cast(frame_width) / - static_cast(physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.width))); - image_extent.height = static_cast(ceil(static_cast(frame_height) / - static_cast(physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.height))); - image_extent.depth = 1; + image_extent.width = + static_cast(ceil(static_cast(frame_width) / + static_cast(physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.width))); + image_extent.height = + static_cast(ceil(static_cast(frame_height) / + static_cast(physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.height))); + image_extent.depth = 1; auto create_shading_rate = [&](VkImageUsageFlags image_usage, VkFormat format) { - return std::make_unique(get_device(), - image_extent, - format, - image_usage, - VMA_MEMORY_USAGE_GPU_ONLY, - VK_SAMPLE_COUNT_1_BIT); + return std::make_unique(get_device(), image_extent, format, image_usage, VMA_MEMORY_USAGE_GPU_ONLY, VK_SAMPLE_COUNT_1_BIT); }; - shading_rate_image = create_shading_rate( - VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR | VK_IMAGE_USAGE_TRANSFER_DST_BIT, - VK_FORMAT_R8_UINT); - shading_rate_image_compute = create_shading_rate( - VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, - VK_FORMAT_R8_UINT); + shading_rate_image = create_shading_rate(VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_FORMAT_R8_UINT); + shading_rate_image_compute = create_shading_rate(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_FORMAT_R8_UINT); uint32_t fragment_shading_rate_count = 0; - vkGetPhysicalDeviceFragmentShadingRatesKHR(get_device().get_gpu().get_handle(), &fragment_shading_rate_count, - nullptr); + vkGetPhysicalDeviceFragmentShadingRatesKHR(get_device().get_gpu().get_handle(), &fragment_shading_rate_count, nullptr); if (fragment_shading_rate_count > 0) { fragment_shading_rates.resize(fragment_shading_rate_count); @@ -136,14 +126,12 @@ void FragmentShadingRateDynamic::create_shading_rate_attachment() { fragment_shading_rate.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_KHR; } - vkGetPhysicalDeviceFragmentShadingRatesKHR(get_device().get_gpu().get_handle(), - &fragment_shading_rate_count, fragment_shading_rates.data()); + vkGetPhysicalDeviceFragmentShadingRatesKHR(get_device().get_gpu().get_handle(), &fragment_shading_rate_count, fragment_shading_rates.data()); } // initialize to the lowest shading rate, equal to (min_shading_rate >> 1) | (min_shading_rate << 1)); const auto min_shading_rate = fragment_shading_rates.front().fragmentSize; - std::vector temp_buffer(frame_height * frame_width, - (min_shading_rate.height >> 1) | ((min_shading_rate.width << 1) & 12)); + std::vector temp_buffer(frame_height * frame_width, (min_shading_rate.height >> 1) | ((min_shading_rate.width << 1) & 12)); auto staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), temp_buffer); auto cmd = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); @@ -154,11 +142,11 @@ void FragmentShadingRateDynamic::create_shading_rate_attachment() buffer_copy_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; buffer_copy_region.imageSubresource.layerCount = 1; buffer_copy_region.imageExtent = image_extent; - vkCmdCopyBufferToImage(cmd, staging_buffer.get_handle(), shading_rate_image->get_handle(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &buffer_copy_region); + vkCmdCopyBufferToImage(cmd, staging_buffer.get_handle(), shading_rate_image->get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, + &buffer_copy_region); - vkb::image_layout_transition( - cmd, shading_rate_image->get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR); + vkb::image_layout_transition(cmd, shading_rate_image->get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR); VK_CHECK(vkEndCommandBuffer(cmd)); @@ -178,12 +166,9 @@ void FragmentShadingRateDynamic::create_shading_rate_attachment() frequency_image_extent.width = this->width; frequency_image_extent.height = this->height; frequency_image_extent.depth = 1; - frequency_content_image = - std::make_unique(get_device(), - frequency_image_extent, - VK_FORMAT_R8G8_UINT, - VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + frequency_content_image = std::make_unique( + get_device(), frequency_image_extent, VK_FORMAT_R8G8_UINT, + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY); frequency_content_image_view = std::make_unique(*frequency_content_image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R8G8_UINT); { @@ -288,11 +273,12 @@ void FragmentShadingRateDynamic::setup_render_pass() fragment_shading_rate_reference.layout = VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR; // Set up the attachment info for the shading rate image, which will be added to the sub pass via structure chaining (in pNext) - VkFragmentShadingRateAttachmentInfoKHR fragment_shading_rate_attachment_info = { - VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR}; - fragment_shading_rate_attachment_info.pFragmentShadingRateAttachment = &fragment_shading_rate_reference; - fragment_shading_rate_attachment_info.shadingRateAttachmentTexelSize.width = physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.width; - fragment_shading_rate_attachment_info.shadingRateAttachmentTexelSize.height = physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.height; + VkFragmentShadingRateAttachmentInfoKHR fragment_shading_rate_attachment_info = {VK_STRUCTURE_TYPE_FRAGMENT_SHADING_RATE_ATTACHMENT_INFO_KHR}; + fragment_shading_rate_attachment_info.pFragmentShadingRateAttachment = &fragment_shading_rate_reference; + fragment_shading_rate_attachment_info.shadingRateAttachmentTexelSize.width = + physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.width; + fragment_shading_rate_attachment_info.shadingRateAttachmentTexelSize.height = + physical_device_fragment_shading_rate_properties.maxFragmentShadingRateAttachmentTexelSize.height; VkAttachmentReference2KHR color_reference = {VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2}; color_reference.attachment = 0; @@ -399,8 +385,7 @@ void FragmentShadingRateDynamic::setup_framebuffer() assert(render_pass && fragment_render_pass); std::array render_passes{&render_pass, &fragment_render_pass}; - std::array>, 2> framebuffer_refs{framebuffers, - fragment_framebuffers}; + std::array>, 2> framebuffer_refs{framebuffers, fragment_framebuffers}; for (auto use_fragment_shading_rate : {false, true}) { @@ -499,8 +484,7 @@ void FragmentShadingRateDynamic::build_command_buffers() vkCmdSetScissor(render_target._command_buffer, 0, 1, &scissor); VkDescriptorSet descriptor_set = render_target._descriptor_set; - vkCmdBindDescriptorSets(render_target._command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, - &descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(render_target._command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr); // Set the fragment shading rate state for the current pipeline VkExtent2D fragment_size = {1, 1}; @@ -526,17 +510,14 @@ void FragmentShadingRateDynamic::build_command_buffers() { vkCmdBindPipeline(render_target._command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skysphere); push_const_block.object_type = 0; - vkCmdPushConstants(render_target._command_buffer, pipeline_layout, - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), - &push_const_block); - vkCmdBindDescriptorSets(render_target._command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, - 1, &descriptor_set, 0, nullptr); + vkCmdPushConstants(render_target._command_buffer, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(push_const_block), &push_const_block); + vkCmdBindDescriptorSets(render_target._command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr); draw_model(models.skysphere, render_target._command_buffer); } vkCmdBindPipeline(render_target._command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.sphere); - vkCmdBindDescriptorSets(render_target._command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, - &descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(render_target._command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr); std::vector mesh_offsets = { glm::vec3(-2.5f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), @@ -546,9 +527,8 @@ void FragmentShadingRateDynamic::build_command_buffers() { push_const_block.object_type = 1; push_const_block.offset = glm::vec4(mesh_offsets[j], 0.0f); - vkCmdPushConstants(render_target._command_buffer, pipeline_layout, - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), - &push_const_block); + vkCmdPushConstants(render_target._command_buffer, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(push_const_block), &push_const_block); draw_model(models.scene, render_target._command_buffer); } @@ -575,11 +555,9 @@ void FragmentShadingRateDynamic::build_command_buffers() // small_command_buffers are not controlled by ApiVulkanSample, that is we need to explicitly reset them here! VK_CHECK(vkResetCommandBuffer(small_command_buffers[i], 0)); - assert(subpass_extent.width > 0 && subpass_extent.width <= width && subpass_extent.height > 0 && - subpass_extent.height <= height); - RenderTarget small_target{ - small_command_buffers[i], fragment_framebuffers[i], framebuffers[i], render_descriptor_sets[i], - fragment_render_pass, subpass_extent, false, false}; + assert(subpass_extent.width > 0 && subpass_extent.width <= width && subpass_extent.height > 0 && subpass_extent.height <= height); + RenderTarget small_target{small_command_buffers[i], fragment_framebuffers[i], framebuffers[i], render_descriptor_sets[i], + fragment_render_pass, subpass_extent, false, false}; RenderTarget full_target{ draw_cmd_buffers[i], fragment_framebuffers[i], framebuffers[i], render_descriptor_sets[i], fragment_render_pass, {width, height}, true, true}; build_command_buffer(small_target); @@ -605,62 +583,48 @@ void FragmentShadingRateDynamic::setup_descriptor_pool() descriptor_pool = VK_NULL_HANDLE; } - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4 * N), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6 * N), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 4 * N)}; - uint32_t num_descriptor_sets = std::max(static_cast(4), N); - VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), - num_descriptor_sets); - VK_CHECK( - vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4 * N), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6 * N), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 4 * N)}; + uint32_t num_descriptor_sets = std::max(static_cast(4), N); + VkDescriptorPoolCreateInfo descriptor_pool_create_info = + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); + VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void FragmentShadingRateDynamic::setup_descriptor_set_layout() { // Scene rendering descriptors std::vector set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, 1), // sampler env map - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, 2), // sampler sphere - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, - VK_SHADER_STAGE_FRAGMENT_BIT, + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), // sampler env map + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), // sampler sphere + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT, 3), // input_frequency - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, - VK_SHADER_STAGE_FRAGMENT_BIT, + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_FRAGMENT_BIT, 4) // output_sampling_rate }; VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, - &descriptor_set_layout)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); // Pass object offset and color via push constant - VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range( - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); + VkPushConstantRange push_constant_range = + vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); pipeline_layout_create_info.pushConstantRangeCount = 1; pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; - VK_CHECK( - vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void FragmentShadingRateDynamic::setup_descriptor_sets() { // Shared model object descriptor set - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); render_descriptor_sets.resize(draw_cmd_buffers.size(), VK_NULL_HANDLE); assert(!compute_buffers.empty()); @@ -679,28 +643,19 @@ void FragmentShadingRateDynamic::setup_descriptor_sets() VkDescriptorImageInfo sphere_image_descriptor = create_descriptor(textures.scene); // We want to visualize the previous frame's frequency and shading rate image - VkDescriptorImageInfo frequency_descriptor = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, - compute_buffers[prev_frame].frequency_content_image_view->get_handle(), - VK_IMAGE_LAYOUT_GENERAL); - VkDescriptorImageInfo shading_image = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, - compute_buffers[prev_frame].shading_rate_image_compute_view->get_handle(), - VK_IMAGE_LAYOUT_GENERAL); - - std::vector - write_descriptor_sets = { - vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, - &scene_buffer_descriptor), - vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, - &environment_image_descriptor), - vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, - &sphere_image_descriptor), - vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 3, - &frequency_descriptor), - vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 4, - &shading_image), - }; - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, nullptr); + VkDescriptorImageInfo frequency_descriptor = vkb::initializers::descriptor_image_info( + VK_NULL_HANDLE, compute_buffers[prev_frame].frequency_content_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL); + VkDescriptorImageInfo shading_image = vkb::initializers::descriptor_image_info( + VK_NULL_HANDLE, compute_buffers[prev_frame].shading_rate_image_compute_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL); + + std::vector write_descriptor_sets = { + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &scene_buffer_descriptor), + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &environment_image_descriptor), + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &sphere_image_descriptor), + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 3, &frequency_descriptor), + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 4, &shading_image), + }; + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } } @@ -708,24 +663,17 @@ void FragmentShadingRateDynamic::create_compute_pipeline() { // Descriptor set layout std::vector set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, - VK_SHADER_STAGE_COMPUTE_BIT, 0), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, - VK_SHADER_STAGE_COMPUTE_BIT, 1), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, - VK_SHADER_STAGE_COMPUTE_BIT, 2), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 2), }; - VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings); + VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, VK_NULL_HANDLE, - &compute.descriptor_set_layout)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, VK_NULL_HANDLE, &compute.descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info( - &compute.descriptor_set_layout, 1); - VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, VK_NULL_HANDLE, - &compute.pipeline_layout)); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&compute.descriptor_set_layout, 1); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, VK_NULL_HANDLE, &compute.pipeline_layout)); // Descriptor pool if (compute.descriptor_pool) @@ -734,28 +682,23 @@ void FragmentShadingRateDynamic::create_compute_pipeline() compute.descriptor_pool = VK_NULL_HANDLE; } - const auto N = static_cast(draw_cmd_buffers.size()); - std::vector sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 4 * N), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4 * N)}; - const auto pool_create = vkb::initializers::descriptor_pool_create_info(sizes, N); + const auto N = static_cast(draw_cmd_buffers.size()); + std::vector sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 4 * N), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4 * N)}; + const auto pool_create = vkb::initializers::descriptor_pool_create_info(sizes, N); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &pool_create, VK_NULL_HANDLE, &compute.descriptor_pool)); // Descriptor sets for (auto &&compute_buffer : compute_buffers) { - VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info( - compute.descriptor_pool, &compute.descriptor_set_layout, 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(compute.descriptor_pool, &compute.descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &compute_buffer.descriptor_set)); } // Pipeline - VkComputePipelineCreateInfo pipeline_create_info = vkb::initializers::compute_pipeline_create_info( - compute.pipeline_layout); - pipeline_create_info.stage = load_shader("fragment_shading_rate_dynamic/generate_shading_rate.comp.spv", - VK_SHADER_STAGE_COMPUTE_BIT); - VK_CHECK(vkCreateComputePipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, VK_NULL_HANDLE, - &compute.pipeline)); + VkComputePipelineCreateInfo pipeline_create_info = vkb::initializers::compute_pipeline_create_info(compute.pipeline_layout); + pipeline_create_info.stage = load_shader("fragment_shading_rate_dynamic/generate_shading_rate.comp.spv", VK_SHADER_STAGE_COMPUTE_BIT); + VK_CHECK(vkCreateComputePipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, VK_NULL_HANDLE, &compute.pipeline)); for (auto &&compute_buffer : compute_buffers) { @@ -783,21 +726,15 @@ void FragmentShadingRateDynamic::update_compute_pipeline() assert(max_rate_x && max_rate_y); FrequencyInformation params{ glm::uvec2(subpass_extent.width, subpass_extent.height), - glm::uvec2(compute_buffers[0].shading_rate_image->get_extent().width, - compute_buffers[0].shading_rate_image->get_extent().height), - glm::uvec2(max_rate_x, max_rate_y), - static_cast(fragment_shading_rates.size()), - static_cast(0)}; + glm::uvec2(compute_buffers[0].shading_rate_image->get_extent().width, compute_buffers[0].shading_rate_image->get_extent().height), + glm::uvec2(max_rate_x, max_rate_y), static_cast(fragment_shading_rates.size()), static_cast(0)}; // Transfer frequency information to buffer - const uint32_t buffer_size = - static_cast(sizeof(FrequencyInformation) + shading_rates_u_vec_2.size() * sizeof(shading_rates_u_vec_2[0])); - frequency_information_params = std::make_unique(get_device(), buffer_size, - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + const uint32_t buffer_size = static_cast(sizeof(FrequencyInformation) + shading_rates_u_vec_2.size() * sizeof(shading_rates_u_vec_2[0])); + frequency_information_params = + std::make_unique(get_device(), buffer_size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); frequency_information_params->update(¶ms, sizeof(FrequencyInformation), 0); - frequency_information_params->update(shading_rates_u_vec_2.data(), - shading_rates_u_vec_2.size() * sizeof(shading_rates_u_vec_2[0]), + frequency_information_params->update(shading_rates_u_vec_2.data(), shading_rates_u_vec_2.size() * sizeof(shading_rates_u_vec_2[0]), sizeof(FrequencyInformation)); // Update descriptor sets @@ -810,22 +747,16 @@ void FragmentShadingRateDynamic::update_compute_pipeline() auto &shading_rate_image_compute = compute_buffer.shading_rate_image_compute; auto &shading_rate_image_compute_view = compute_buffer.shading_rate_image_compute_view; - VkDescriptorImageInfo frequency_image = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, - frequency_content_image_view->get_handle(), - VK_IMAGE_LAYOUT_GENERAL); - VkDescriptorImageInfo shading_image = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, - shading_rate_image_compute_view->get_handle(), - VK_IMAGE_LAYOUT_GENERAL); + VkDescriptorImageInfo frequency_image = + vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, frequency_content_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL); + VkDescriptorImageInfo shading_image = + vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, shading_rate_image_compute_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL); VkDescriptorBufferInfo buffer_info = create_descriptor(*frequency_information_params); std::array write_descriptor_sets = { - vkb::initializers::write_descriptor_set(compute_buffer.descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, - 0, &frequency_image), - vkb::initializers::write_descriptor_set(compute_buffer.descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, - 1, &shading_image), - vkb::initializers::write_descriptor_set(compute_buffer.descriptor_set, - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2, &buffer_info)}; - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkb::initializers::write_descriptor_set(compute_buffer.descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, &frequency_image), + vkb::initializers::write_descriptor_set(compute_buffer.descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &shading_image), + vkb::initializers::write_descriptor_set(compute_buffer.descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2, &buffer_info)}; + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); // Command Buffer assert(compute_buffer.command_buffer); @@ -835,12 +766,11 @@ void FragmentShadingRateDynamic::update_compute_pipeline() VK_CHECK(vkBeginCommandBuffer(command_buffer, &begin)); const auto fragment_extent = compute_buffer.shading_rate_image->get_extent(); - const uint32_t fragment_width = std::max(static_cast(1), fragment_extent.width), fragment_height = std::max( - static_cast(1), fragment_extent.height); + const uint32_t fragment_width = std::max(static_cast(1), fragment_extent.width), + fragment_height = std::max(static_cast(1), fragment_extent.height); vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline); - vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline_layout, 0, 1, - &compute_buffer.descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline_layout, 0, 1, &compute_buffer.descriptor_set, 0, nullptr); vkCmdDispatch(command_buffer, 1 + (fragment_width - 1) / 8, 1 + (fragment_height - 1) / 8, 1); VkImageCopy image_copy; @@ -850,53 +780,38 @@ void FragmentShadingRateDynamic::update_compute_pipeline() image_copy.extent = shading_rate_image->get_extent(); image_copy.srcOffset = {0, 0, 0}; - vkb::image_layout_transition( - command_buffer, shading_rate_image->get_handle(), VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + vkb::image_layout_transition(command_buffer, shading_rate_image->get_handle(), VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); VkImageSubresourceRange subresource_range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - vkb::image_layout_transition(command_buffer, - shading_rate_image_compute->get_handle(), - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_SHADER_WRITE_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - subresource_range); + vkb::image_layout_transition(command_buffer, shading_rate_image_compute->get_handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_GENERAL, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); - vkCmdCopyImage(command_buffer, shading_rate_image_compute->get_handle(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - shading_rate_image->get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy); + vkCmdCopyImage(command_buffer, shading_rate_image_compute->get_handle(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, shading_rate_image->get_handle(), + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_copy); - vkb::image_layout_transition( - command_buffer, shading_rate_image->get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR); + vkb::image_layout_transition(command_buffer, shading_rate_image->get_handle(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR); - vkb::image_layout_transition(command_buffer, - shading_rate_image_compute->get_handle(), - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - {}, - {}, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_IMAGE_LAYOUT_GENERAL, + vkb::image_layout_transition(command_buffer, shading_rate_image_compute->get_handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, {}, {}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresource_range); VK_CHECK(vkEndCommandBuffer(compute_buffer.command_buffer)); if (debug_utils_supported) { - auto set_name = [device{get_device().get_handle()}](VkObjectType object_type, const char *name, - const void *handle) { + auto set_name = [device{get_device().get_handle()}](VkObjectType object_type, const char *name, const void *handle) { VkDebugUtilsObjectNameInfoEXT name_info = {VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT}; name_info.objectType = object_type; name_info.objectHandle = (uint64_t) handle; name_info.pObjectName = name; vkSetDebugUtilsObjectNameEXT(device, &name_info); }; - set_name(VK_OBJECT_TYPE_IMAGE_VIEW, "shading_rate_image_compute_view", - reinterpret_cast(shading_rate_image_compute_view->get_handle())); + set_name(VK_OBJECT_TYPE_IMAGE_VIEW, "shading_rate_image_compute_view", reinterpret_cast(shading_rate_image_compute_view->get_handle())); set_name(VK_OBJECT_TYPE_IMAGE_VIEW, "shading_rate_image_view", reinterpret_cast(shading_rate_image_view->get_handle())); - set_name(VK_OBJECT_TYPE_IMAGE_VIEW, "frequency_content_image_view", - reinterpret_cast(frequency_content_image_view->get_handle())); + set_name(VK_OBJECT_TYPE_IMAGE_VIEW, "frequency_content_image_view", reinterpret_cast(frequency_content_image_view->get_handle())); set_name(VK_OBJECT_TYPE_IMAGE, "shading_rate_image_compute", reinterpret_cast(shading_rate_image_compute->get_handle())); set_name(VK_OBJECT_TYPE_IMAGE, "shading_rate_image", reinterpret_cast(shading_rate_image->get_handle())); set_name(VK_OBJECT_TYPE_IMAGE, "frequency_content_image", reinterpret_cast(frequency_content_image->get_handle())); @@ -907,59 +822,31 @@ void FragmentShadingRateDynamic::update_compute_pipeline() void FragmentShadingRateDynamic::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); - std::vector blend_attachment_state(2, - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE)); + std::vector blend_attachment_state(2, vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)); VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - static_cast(blend_attachment_state.size()), - blend_attachment_state.data()); + vkb::initializers::pipeline_color_blend_state_create_info(static_cast(blend_attachment_state.size()), blend_attachment_state.data()); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - // Add fragment shading rate dynamic state, so we can easily toggle this at runtime - VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, + // Add fragment shading rate dynamic state, so we can easily toggle this at runtime + VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - fragment_render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, fragment_render_pass, 0); std::vector blend_attachment_states = { vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), @@ -1004,8 +891,7 @@ void FragmentShadingRateDynamic::prepare_pipelines() shader_stages[0] = load_shader("fragment_shading_rate_dynamic/scene.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shader_stages[1] = load_shader("fragment_shading_rate_dynamic/scene.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, - &pipelines.skysphere)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, &pipelines.skysphere)); // Objects // Enable depth test and write @@ -1013,16 +899,13 @@ void FragmentShadingRateDynamic::prepare_pipelines() depth_stencil_state.depthTestEnable = VK_TRUE; // Flip cull mode rasterization_state.cullMode = VK_CULL_MODE_FRONT_BIT; - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, - &pipelines.sphere)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, &pipelines.sphere)); } void FragmentShadingRateDynamic::prepare_uniform_buffers() { - uniform_buffers.scene = std::make_unique(get_device(), - sizeof(ubo_scene), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.scene = + std::make_unique(get_device(), sizeof(ubo_scene), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -1057,8 +940,7 @@ void FragmentShadingRateDynamic::draw() VK_CHECK(vkQueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE)); ApiVulkanSample::submit_frame(); - const std::array small_wait_mask = {VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT}; + const std::array small_wait_mask = {VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT}; VkSemaphore small_semaphore{VK_NULL_HANDLE}; vkCreateSemaphore(get_device().get_handle(), &semaphore_create, VK_NULL_HANDLE, &small_semaphore); submit_info.pCommandBuffers = &small_command_buffers[current_buffer]; @@ -1106,9 +988,9 @@ bool FragmentShadingRateDynamic::prepare(const vkb::ApplicationOptions &options) } const auto enabled_instance_extensions = get_instance().get_enabled_extensions(); - debug_utils_supported = - std::ranges::find_if(enabled_instance_extensions, [](std::string const &ext) { return ext == VK_EXT_DEBUG_UTILS_EXTENSION_NAME; }) != - enabled_instance_extensions.cend(); + debug_utils_supported = std::ranges::find_if(enabled_instance_extensions, [](std::string const &ext) { + return ext == VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + }) != enabled_instance_extensions.cend(); camera.type = vkb::CameraType::FirstPerson; camera.set_position(glm::vec3(0.0f, 0.0f, -4.0f)); @@ -1156,16 +1038,15 @@ void FragmentShadingRateDynamic::on_update_ui_overlay(vkb::Drawer &drawer) static const std::vector frequency_decimation_rates = {"1", "2", "4", "8", "16"}; - int32_t selection = std::min(static_cast(frequency_decimation_rates.size()) - 1, - static_cast(log2f(static_cast(subpass_extent_ratio)))); + int32_t selection = + std::min(static_cast(frequency_decimation_rates.size()) - 1, static_cast(log2f(static_cast(subpass_extent_ratio)))); if (drawer.combo_box("Subpass size reduction", &selection, frequency_decimation_rates)) { subpass_extent_ratio = (1 << selection); resize(width, height); } - static const std::vector shading_rate_names = {"Render output", "Shading Rates", - "Frequency channel"}; + static const std::vector shading_rate_names = {"Render output", "Shading Rates", "Frequency channel"}; if (drawer.combo_box("Data visualize", &ubo_scene.color_shading_rate, shading_rate_names)) { update_uniform_buffers(); diff --git a/samples/extensions/full_screen_exclusive/full_screen_exclusive.cpp b/samples/extensions/full_screen_exclusive/full_screen_exclusive.cpp index 6bb41bf52e..a3cd896b1d 100644 --- a/samples/extensions/full_screen_exclusive/full_screen_exclusive.cpp +++ b/samples/extensions/full_screen_exclusive/full_screen_exclusive.cpp @@ -21,7 +21,8 @@ #include "platform/window.h" #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) -static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, VkDebugUtilsMessageTypeFlagsEXT message_type, +static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT message_severity, + VkDebugUtilsMessageTypeFlagsEXT message_type, const VkDebugUtilsMessengerCallbackDataEXT *callback_data, void *user_data) { @@ -69,7 +70,8 @@ bool FullScreenExclusive::validate_extensions(const std::vector &r return true; } -void FullScreenExclusive::init_instance(const std::vector &required_instance_extensions, const std::vector &required_validation_layers) +void FullScreenExclusive::init_instance(const std::vector &required_instance_extensions, + const std::vector &required_validation_layers) { LOGI("Initializing vulkan instance.") @@ -143,9 +145,9 @@ void FullScreenExclusive::init_instance(const std::vector &require #if defined(VKB_DEBUG) || defined(VKB_VALIDATION_LAYERS) VkDebugUtilsMessengerCreateInfoEXT debug_utils_create_info = {VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; - debug_utils_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT; - debug_utils_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; - debug_utils_create_info.pfnUserCallback = debug_callback; + debug_utils_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT; + debug_utils_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + debug_utils_create_info.pfnUserCallback = debug_callback; instance_info.pNext = &debug_utils_create_info; #endif @@ -498,9 +500,7 @@ VkShaderModule FullScreenExclusive::load_shader_module(const char *path) const std::vector spirv = vkb::fs::read_shader_binary_u32(path); VkShaderModuleCreateInfo module_info{ - .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, - .codeSize = spirv.size() * sizeof(uint32_t), - .pCode = spirv.data()}; + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = spirv.size() * sizeof(uint32_t), .pCode = spirv.data()}; VkShaderModule shader_module; VK_CHECK(vkCreateShaderModule(context.device, &module_info, nullptr, &shader_module)); @@ -667,8 +667,7 @@ void FullScreenExclusive::render_triangle(uint32_t swapchain_index) if (context.per_frame[swapchain_index].swapchain_release_semaphore == VK_NULL_HANDLE) { VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; - VK_CHECK(vkCreateSemaphore(context.device, &semaphore_info, nullptr, - &context.per_frame[swapchain_index].swapchain_release_semaphore)); + VK_CHECK(vkCreateSemaphore(context.device, &semaphore_info, nullptr, &context.per_frame[swapchain_index].swapchain_release_semaphore)); } VkPipelineStageFlags wait_stage{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; @@ -805,9 +804,10 @@ void FullScreenExclusive::initialize_windows() surface_full_screen_exclusive_Win32_info_EXT.pNext = nullptr; surface_full_screen_exclusive_Win32_info_EXT.hmonitor = MonitorFromWindow(HWND_application_window, MONITOR_DEFAULTTONEAREST); - surface_full_screen_exclusive_info_EXT.sType = VK_STRUCTURE_TYPE_SURFACE_FULL_SCREEN_EXCLUSIVE_INFO_EXT; - surface_full_screen_exclusive_info_EXT.pNext = &surface_full_screen_exclusive_Win32_info_EXT; - surface_full_screen_exclusive_info_EXT.fullScreenExclusive = VK_FULL_SCREEN_EXCLUSIVE_DEFAULT_EXT; // Set the fullScreenExclusive stage to default when initializing + surface_full_screen_exclusive_info_EXT.sType = VK_STRUCTURE_TYPE_SURFACE_FULL_SCREEN_EXCLUSIVE_INFO_EXT; + surface_full_screen_exclusive_info_EXT.pNext = &surface_full_screen_exclusive_Win32_info_EXT; + surface_full_screen_exclusive_info_EXT.fullScreenExclusive = + VK_FULL_SCREEN_EXCLUSIVE_DEFAULT_EXT; // Set the fullScreenExclusive stage to default when initializing // Windows placement should only be registered ONCE: GetWindowPlacement(HWND_application_window, &wpc); @@ -1045,7 +1045,8 @@ void FullScreenExclusive::recreate() { VkResult result = vkAcquireFullScreenExclusiveModeEXT(context.device, context.swapchain); if (result != VK_SUCCESS) - LOGI("vkAcquireFullScreenExclusiveModeEXT: " + vkb::to_string(result)) // it would be necessary to learn the result on an unsuccessful attempt + LOGI("vkAcquireFullScreenExclusiveModeEXT: " + + vkb::to_string(result)) // it would be necessary to learn the result on an unsuccessful attempt } } } diff --git a/samples/extensions/full_screen_exclusive/full_screen_exclusive.h b/samples/extensions/full_screen_exclusive/full_screen_exclusive.h index f1d68eab41..8ad9db6617 100644 --- a/samples/extensions/full_screen_exclusive/full_screen_exclusive.h +++ b/samples/extensions/full_screen_exclusive/full_screen_exclusive.h @@ -77,30 +77,32 @@ class FullScreenExclusive : public vkb::Application private: Context context{}; - HWND HWND_application_window{}; // sync the application HWND handle - bool is_windowed = true; // this is to tell if the application window is already set in the desired mode - WINDOWPLACEMENT wpc{}; // window placement information - LONG HWND_style = 0; // current Hwnd style - LONG HWND_extended_style = 0; // previous Hwnd style - VkSurfaceFullScreenExclusiveInfoEXT surface_full_screen_exclusive_info_EXT{}; // it can be created locally, however, it is a good reminder that they are declared here as a class variable + HWND HWND_application_window{}; // sync the application HWND handle + bool is_windowed = true; // this is to tell if the application window is already set in the desired mode + WINDOWPLACEMENT wpc{}; // window placement information + LONG HWND_style = 0; // current Hwnd style + LONG HWND_extended_style = 0; // previous Hwnd style + VkSurfaceFullScreenExclusiveInfoEXT surface_full_screen_exclusive_info_EXT{}; // it can be created locally, however, it is a good reminder that they + // are declared here as a class variable VkSurfaceFullScreenExclusiveWin32InfoEXT surface_full_screen_exclusive_Win32_info_EXT{}; - bool is_full_screen_exclusive = false; // this is to tell if the screen is in full screen EXCLUSIVE or not - ApplicationWindowMode application_window_status = ApplicationWindowMode::Windowed; // declare and initialize the application window mode - SwapchainMode full_screen_status = SwapchainMode::Default; // declare and initialize the swapchain mode + bool is_full_screen_exclusive = false; // this is to tell if the screen is in full screen EXCLUSIVE or not + ApplicationWindowMode application_window_status = ApplicationWindowMode::Windowed; // declare and initialize the application window mode + SwapchainMode full_screen_status = SwapchainMode::Default; // declare and initialize the swapchain mode private: - VkExtent2D get_current_max_image_extent() const; // This detects the maximum surface resolution and return them in vkExtent2D format - void input_event(const vkb::InputEvent &input_event) override; // This is to introduce a customized input events for switching application window and swapchain modes. - void update_application_window(); // This switches application window modes corresponding to the selected swapchain modes - void recreate(); // to recreate the swapchain and related per switch of display mode + VkExtent2D get_current_max_image_extent() const; // This detects the maximum surface resolution and return them in vkExtent2D format + void input_event(const vkb::InputEvent &input_event) + override; // This is to introduce a customized input events for switching application window and swapchain modes. + void update_application_window(); // This switches application window modes corresponding to the selected swapchain modes + void recreate(); // to recreate the swapchain and related per switch of display mode public: FullScreenExclusive() = default; ~FullScreenExclusive() override; - void initialize_windows(); - bool prepare(const vkb::ApplicationOptions &options) override; // This syncs all required extensions and booleans is a Windows platform is detected - void update(float delta_time) override; - bool resize(uint32_t width, uint32_t height) override; + void initialize_windows(); + bool prepare(const vkb::ApplicationOptions &options) override; // This syncs all required extensions and booleans is a Windows platform is detected + void update(float delta_time) override; + bool resize(uint32_t width, uint32_t height) override; static bool validate_extensions(const std::vector &required, const std::vector &available); void init_instance(const std::vector &required_instance_extensions, const std::vector &required_validation_layers); void init_device(const std::vector &required_device_extensions); diff --git a/samples/extensions/graphics_pipeline_library/graphics_pipeline_library.cpp b/samples/extensions/graphics_pipeline_library/graphics_pipeline_library.cpp index e5db356165..7aa418011d 100644 --- a/samples/extensions/graphics_pipeline_library/graphics_pipeline_library.cpp +++ b/samples/extensions/graphics_pipeline_library/graphics_pipeline_library.cpp @@ -165,10 +165,9 @@ void GraphicsPipelineLibrary::load_assets() void GraphicsPipelineLibrary::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1)}; - uint32_t num_descriptor_sets = 1; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1)}; + uint32_t num_descriptor_sets = 1; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -184,8 +183,7 @@ void GraphicsPipelineLibrary::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); // Pass random colors using push constants VkPushConstantRange push_constant_range{}; @@ -201,8 +199,7 @@ void GraphicsPipelineLibrary::setup_descriptor_set_layout() void GraphicsPipelineLibrary::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -229,7 +226,8 @@ void GraphicsPipelineLibrary::prepare_pipeline_library() library_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT; library_info.flags = VK_GRAPHICS_PIPELINE_LIBRARY_VERTEX_INPUT_INTERFACE_BIT_EXT; - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); std::vector vertex_input_bindings = { vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), @@ -252,7 +250,8 @@ void GraphicsPipelineLibrary::prepare_pipeline_library() pipeline_library_create_info.pInputAssemblyState = &input_assembly_state; pipeline_library_create_info.pVertexInputState = &vertex_input_state; - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_library_create_info, nullptr, &pipeline_library.vertex_input_interface)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_library_create_info, nullptr, + &pipeline_library.vertex_input_interface)); } // Create a pipeline library for the vertex shader stage @@ -261,9 +260,7 @@ void GraphicsPipelineLibrary::prepare_pipeline_library() library_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT; library_info.flags = VK_GRAPHICS_PIPELINE_LIBRARY_PRE_RASTERIZATION_SHADERS_BIT_EXT; - VkDynamicState vertexDynamicStates[2] = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + VkDynamicState vertexDynamicStates[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamicInfo{}; dynamicInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; @@ -275,7 +272,8 @@ void GraphicsPipelineLibrary::prepare_pipeline_library() viewportState.viewportCount = 1; viewportState.scissorCount = 1; - VkPipelineRasterizationStateCreateInfo rasterizationState = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); + VkPipelineRasterizationStateCreateInfo rasterizationState = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); // Using the pipeline library extension, we can skip the pipeline shader module creation and directly pass the shader code to the pipeline std::vector spirv; @@ -304,7 +302,8 @@ void GraphicsPipelineLibrary::prepare_pipeline_library() pipeline_library_create_info.pViewportState = &viewportState; pipeline_library_create_info.pRasterizationState = &rasterizationState; - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_library_create_info, nullptr, &pipeline_library.pre_rasterization_shaders)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_library_create_info, nullptr, + &pipeline_library.pre_rasterization_shaders)); } // Create a pipeline library for the fragment output interface @@ -326,7 +325,8 @@ void GraphicsPipelineLibrary::prepare_pipeline_library() pipeline_library_create_info.pColorBlendState = &color_blend_state; pipeline_library_create_info.pMultisampleState = &multisample_state; - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_library_create_info, nullptr, &pipeline_library.fragment_output_interface)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_library_create_info, nullptr, + &pipeline_library.fragment_output_interface)); } } @@ -337,8 +337,9 @@ void GraphicsPipelineLibrary::prepare_new_pipeline() library_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_LIBRARY_CREATE_INFO_EXT; library_info.flags = VK_GRAPHICS_PIPELINE_LIBRARY_FRAGMENT_SHADER_BIT_EXT; - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); - VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT); + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT); // Using the pipeline library extension, we can skip the pipeline shader module creation and directly pass the shader code to the pipeline std::vector spirv; @@ -388,11 +389,8 @@ void GraphicsPipelineLibrary::prepare_new_pipeline() // Create the pipeline using the pre-built pipeline library parts // Except for above fragment shader part all parts have been pre-built and will be re-used - std::vector libraries = { - pipeline_library.vertex_input_interface, - pipeline_library.pre_rasterization_shaders, - fragment_shader, - pipeline_library.fragment_output_interface}; + std::vector libraries = {pipeline_library.vertex_input_interface, pipeline_library.pre_rasterization_shaders, fragment_shader, + pipeline_library.fragment_output_interface}; // Link the library parts into a graphics pipeline VkPipelineLibraryCreateInfoKHR linking_info{}; @@ -407,8 +405,8 @@ void GraphicsPipelineLibrary::prepare_new_pipeline() executable_pipeline_create_info.renderPass = render_pass; if (link_time_optimization) { - // If link time optimization is activated in the UI, we set the VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT flag which will let the implementation do additional optimizations at link time - // This trades in pipeline creation time for run-time performance + // If link time optimization is activated in the UI, we set the VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT flag which will let the implementation + // do additional optimizations at link time This trades in pipeline creation time for run-time performance executable_pipeline_create_info.flags = VK_PIPELINE_CREATE_LINK_TIME_OPTIMIZATION_BIT_EXT; } @@ -425,17 +423,15 @@ void GraphicsPipelineLibrary::prepare_new_pipeline() void GraphicsPipelineLibrary::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffer = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } void GraphicsPipelineLibrary::update_uniform_buffers() { - camera.set_perspective(45.0f, (static_cast(width) / static_cast(split_x)) / (static_cast(height) / static_cast(split_y)), 0.1f, 256.0f); + camera.set_perspective(45.0f, (static_cast(width) / static_cast(split_x)) / (static_cast(height) / static_cast(split_y)), 0.1f, + 256.0f); ubo_vs.projection = camera.matrices.perspective; ubo_vs.modelview = camera.matrices.view * glm::rotate(glm::mat4(1.0f), glm::radians(accumulated_time * 360.0f), glm::vec3(0.0f, 1.0f, 0.0f)); diff --git a/samples/extensions/gshader_to_mshader/gshader_to_mshader.cpp b/samples/extensions/gshader_to_mshader/gshader_to_mshader.cpp index a85327311a..e31e2d6b3f 100644 --- a/samples/extensions/gshader_to_mshader/gshader_to_mshader.cpp +++ b/samples/extensions/gshader_to_mshader/gshader_to_mshader.cpp @@ -161,16 +161,10 @@ void GshaderToMshader::prepare_pipelines() mesh_stages[1] = load_shader("gshader_to_mshader", "gshader_to_mshader_mesh.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); // Dynamic State - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_LINE_WIDTH}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Vertex bindings an attributes for model rendering @@ -193,69 +187,45 @@ void GshaderToMshader::prepare_pipelines() // Input assembly VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); // Viewwport and scissors - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); // Rasterizer VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE, 0); rasterization_state.depthBiasConstantFactor = 1.0f; rasterization_state.depthBiasSlopeFactor = 1.0f; // Multisampling - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - multisample_state.minSampleShading = 1.0f; + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + multisample_state.minSampleShading = 1.0f; // Color Blending - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Depth Stencil VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); // Pipeline layout made in descriptors layout // Graphics Pipeline - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); - pipeline_create_info.pStages = model_stages.data(); - pipeline_create_info.stageCount = static_cast(model_stages.size()); - pipeline_create_info.pVertexInputState = &vertex_input_state; - pipeline_create_info.pInputAssemblyState = &input_assembly_state; - pipeline_create_info.pViewportState = &viewport_state; - pipeline_create_info.pRasterizationState = &rasterization_state; - pipeline_create_info.pMultisampleState = &multisample_state; - pipeline_create_info.pDepthStencilState = &depth_stencil_state; - pipeline_create_info.pColorBlendState = &color_blend_state; - pipeline_create_info.pDynamicState = &dynamic_state; + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); + pipeline_create_info.pStages = model_stages.data(); + pipeline_create_info.stageCount = static_cast(model_stages.size()); + pipeline_create_info.pVertexInputState = &vertex_input_state; + pipeline_create_info.pInputAssemblyState = &input_assembly_state; + pipeline_create_info.pViewportState = &viewport_state; + pipeline_create_info.pRasterizationState = &rasterization_state; + pipeline_create_info.pMultisampleState = &multisample_state; + pipeline_create_info.pDepthStencilState = &depth_stencil_state; + pipeline_create_info.pColorBlendState = &color_blend_state; + pipeline_create_info.pDynamicState = &dynamic_state; VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, &model_pipeline)); @@ -335,9 +305,8 @@ void GshaderToMshader::build_command_buffers() */ void GshaderToMshader::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 1); @@ -363,10 +332,7 @@ void GshaderToMshader::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } @@ -376,11 +342,7 @@ void GshaderToMshader::setup_descriptor_set_layout() */ void GshaderToMshader::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); diff --git a/samples/extensions/host_image_copy/host_image_copy.cpp b/samples/extensions/host_image_copy/host_image_copy.cpp index 9e68e72906..ef8e7c5ea8 100644 --- a/samples/extensions/host_image_copy/host_image_copy.cpp +++ b/samples/extensions/host_image_copy/host_image_copy.cpp @@ -307,9 +307,8 @@ void HostImageCopy::draw() void HostImageCopy::setup_descriptor_pool() { // Example uses one ubo and one image sampler - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); @@ -319,28 +318,25 @@ void HostImageCopy::setup_descriptor_pool() void HostImageCopy::setup_descriptor_set_layout() { - std::vector set_layout_bindings = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), - // Binding 1 : Fragment shader image sampler - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1)}; + std::vector set_layout_bindings = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Fragment shader image sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1)}; VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void HostImageCopy::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -366,30 +362,25 @@ void HostImageCopy::prepare_pipelines() VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - const std::array shader_stages = { - load_shader("texture_loading", "texture.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), - load_shader("texture_loading", "texture.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}; + const std::array shader_stages = {load_shader("texture_loading", "texture.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), + load_shader("texture_loading", "texture.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}; // Vertex bindings and attributes const std::vector vertex_input_bindings = { @@ -406,8 +397,7 @@ void HostImageCopy::prepare_pipelines() vertex_input_state.vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -427,10 +417,7 @@ void HostImageCopy::prepare_pipelines() void HostImageCopy::prepare_uniform_buffers() { // Vertex shader uniform buffer block - uniform_buffer_vs = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer_vs = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } diff --git a/samples/extensions/host_image_copy/host_image_copy.h b/samples/extensions/host_image_copy/host_image_copy.h index f727132df1..64c9cdc754 100644 --- a/samples/extensions/host_image_copy/host_image_copy.h +++ b/samples/extensions/host_image_copy/host_image_copy.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2024-2025, Sascha Willems +/* Copyright (c) 2024-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -25,7 +25,8 @@ class HostImageCopy : public ApiVulkanSample { public: // Contains all Vulkan objects that are required to store and use a texture - // Note that this repository contains a texture class (vulkan_texture.h) that encapsulates texture loading functionality in a class that is used in subsequent demos + // Note that this repository contains a texture class (vulkan_texture.h) that encapsulates texture loading functionality in a class that is used in + // subsequent demos struct Texture { VkSampler sampler; diff --git a/samples/extensions/hpp_push_descriptors/hpp_push_descriptors.cpp b/samples/extensions/hpp_push_descriptors/hpp_push_descriptors.cpp index 62591e34ad..712fbf174c 100644 --- a/samples/extensions/hpp_push_descriptors/hpp_push_descriptors.cpp +++ b/samples/extensions/hpp_push_descriptors/hpp_push_descriptors.cpp @@ -64,7 +64,8 @@ bool HPPPushDescriptors::prepare(const vkb::ApplicationOptions &options) */ // Get device push descriptor properties (to display them) - auto property_chain = get_device().get_gpu().get_handle().getProperties2(); + auto property_chain = + get_device().get_gpu().get_handle().getProperties2(); max_push_descriptors = property_chain.get().maxPushDescriptors; /* @@ -137,10 +138,9 @@ void HPPPushDescriptors::build_command_buffers() // Note: dstSet for each descriptor set write is left at nullptr as this is ignored when using push descriptors vk::DescriptorBufferInfo cube_buffer_descriptor{cube.uniform_buffer->get_handle(), 0, vk::WholeSize}; - vk::DescriptorImageInfo cube_image_descriptor{cube.texture.sampler, - cube.texture.image->get_vk_image_view().get_handle(), - descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, - cube.texture.image->get_vk_image_view().get_format())}; + vk::DescriptorImageInfo cube_image_descriptor{ + cube.texture.sampler, cube.texture.image->get_vk_image_view().get_handle(), + descriptor_type_to_image_layout(vk::DescriptorType::eCombinedImageSampler, cube.texture.image->get_vk_image_view().get_format())}; std::array write_descriptor_sets = { {{.dstBinding = 0, .descriptorCount = 1, .descriptorType = vk::DescriptorType::eUniformBuffer, .pBufferInfo = &scene_buffer_descriptor}, @@ -190,9 +190,10 @@ void HPPPushDescriptors::render(float delta_time) void HPPPushDescriptors::create_descriptor_set_layout() { - std::array set_layout_bindings = {{{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex}, - {1, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex}, - {2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}}}; + std::array set_layout_bindings = { + {{0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex}, + {1, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex}, + {2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment}}}; vk::DescriptorSetLayoutCreateInfo descriptor_layout_create_info{.flags = vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR, .bindingCount = static_cast(set_layout_bindings.size()), @@ -223,36 +224,22 @@ void HPPPushDescriptors::create_pipeline() vk::PipelineDepthStencilStateCreateInfo depth_stencil_state{ .depthTestEnable = true, .depthWriteEnable = true, .depthCompareOp = vk::CompareOp::eGreater, .back = {.compareOp = vk::CompareOp::eAlways}}; - pipeline = vkb::common::create_graphics_pipeline(get_device().get_handle(), - pipeline_cache, - shader_stages, - vertex_input_state, - vk::PrimitiveTopology::eTriangleList, - 0, - vk::PolygonMode::eFill, - vk::CullModeFlagBits::eBack, - vk::FrontFace::eClockwise, - {blend_attachment_state}, - depth_stencil_state, - pipeline_layout, - render_pass); + pipeline = vkb::common::create_graphics_pipeline(get_device().get_handle(), pipeline_cache, shader_stages, vertex_input_state, + vk::PrimitiveTopology::eTriangleList, 0, vk::PolygonMode::eFill, vk::CullModeFlagBits::eBack, + vk::FrontFace::eClockwise, {blend_attachment_state}, depth_stencil_state, pipeline_layout, render_pass); } void HPPPushDescriptors::create_uniform_buffers() { // Vertex shader scene uniform buffer block - uniform_buffers.scene = std::make_unique(get_device(), - sizeof(UboScene), - vk::BufferUsageFlagBits::eUniformBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.scene = + std::make_unique(get_device(), sizeof(UboScene), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); // Vertex shader cube model uniform buffer blocks for (auto &cube : cubes) { - cube.uniform_buffer = std::make_unique(get_device(), - sizeof(glm::mat4), - vk::BufferUsageFlagBits::eUniformBuffer, - VMA_MEMORY_USAGE_CPU_TO_GPU); + cube.uniform_buffer = + std::make_unique(get_device(), sizeof(glm::mat4), vk::BufferUsageFlagBits::eUniformBuffer, VMA_MEMORY_USAGE_CPU_TO_GPU); } update_uniform_buffers(); diff --git a/samples/extensions/logic_op_dynamic_state/logic_op_dynamic_state.cpp b/samples/extensions/logic_op_dynamic_state/logic_op_dynamic_state.cpp index 8cd29bb1dc..da95ffef6c 100644 --- a/samples/extensions/logic_op_dynamic_state/logic_op_dynamic_state.cpp +++ b/samples/extensions/logic_op_dynamic_state/logic_op_dynamic_state.cpp @@ -24,8 +24,7 @@ #include "gltf_loader.h" /* Initialize the static variable containing a vector of logic operations' labels for GUI */ -std::vector LogicOpDynamicState::GUI_settings::logic_op_names = - LogicOpDynamicState::GUI_settings::init_logic_op_names(); +std::vector LogicOpDynamicState::GUI_settings::logic_op_names = LogicOpDynamicState::GUI_settings::init_logic_op_names(); LogicOpDynamicState::LogicOpDynamicState() { @@ -151,13 +150,7 @@ void LogicOpDynamicState::build_command_buffers() vkCmdSetScissor(draw_cmd_buffer, 0, 1, &scissor); /* Binding background pipeline and descriptor sets */ - vkCmdBindDescriptorSets(draw_cmd_buffer, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layouts.background, - 0, - 1, - &descriptor_sets.background, - 0, + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.background, 0, 1, &descriptor_sets.background, 0, VK_NULL_HANDLE); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.background); @@ -165,13 +158,7 @@ void LogicOpDynamicState::build_command_buffers() draw_model(background_model, draw_cmd_buffer); /* Binding baseline pipeline and descriptor sets */ - vkCmdBindDescriptorSets(draw_cmd_buffer, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layouts.baseline, - 0, - 1, - &descriptor_sets.baseline, - 0, + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.baseline, 0, 1, &descriptor_sets.baseline, 0, VK_NULL_HANDLE); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.baseline); @@ -242,25 +229,16 @@ void LogicOpDynamicState::create_pipeline() { /* Setup for first pipeline */ VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); rasterization_state.depthBiasConstantFactor = 1.0f; rasterization_state.depthBiasSlopeFactor = 1.0f; - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, - VK_TRUE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_TRUE); blend_attachment_state.colorBlendOp = VK_BLEND_OP_ADD; blend_attachment_state.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; @@ -269,24 +247,18 @@ void LogicOpDynamicState::create_pipeline() blend_attachment_state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; blend_attachment_state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); /* Enable logic operations */ color_blend_state.logicOpEnable = VK_TRUE; /* Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept */ VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); std::vector dynamic_state_enables = { VK_DYNAMIC_STATE_VIEWPORT, @@ -296,10 +268,7 @@ void LogicOpDynamicState::create_pipeline() VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE_EXT, }; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); /* Binding description */ std::vector vertex_input_bindings = { @@ -416,10 +385,7 @@ void LogicOpDynamicState::create_descriptor_pool() }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, VK_NULL_HANDLE, &descriptor_pool)); } @@ -432,14 +398,8 @@ void LogicOpDynamicState::setup_descriptor_set_layout() { /* First descriptor set */ std::vector set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 1), }; VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = @@ -447,10 +407,7 @@ void LogicOpDynamicState::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, VK_NULL_HANDLE, &descriptor_set_layouts.baseline)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.baseline, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.baseline, 1); /* Pass scene node information via push constants */ VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT, sizeof(push_const_block), 0); @@ -461,14 +418,8 @@ void LogicOpDynamicState::setup_descriptor_set_layout() /* Second descriptor set */ set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; descriptor_layout_create_info.pBindings = set_layout_bindings.data(); @@ -491,11 +442,7 @@ void LogicOpDynamicState::setup_descriptor_set_layout() void LogicOpDynamicState::create_descriptor_sets() { /* First descriptor set */ - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.baseline, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.baseline, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.baseline)); @@ -503,45 +450,23 @@ void LogicOpDynamicState::create_descriptor_sets() VkDescriptorBufferInfo matrix_baseline_buffer_descriptor = create_descriptor(*uniform_buffers.baseline); std::vector write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - descriptor_sets.baseline, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &matrix_common_buffer_descriptor), - vkb::initializers::write_descriptor_set( - descriptor_sets.baseline, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 1, - &matrix_baseline_buffer_descriptor)}; - - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkb::initializers::write_descriptor_set(descriptor_sets.baseline, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_common_buffer_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets.baseline, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &matrix_baseline_buffer_descriptor)}; + + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); /* Second descriptor set */ - alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.background, - 1); + alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.background, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.background)); VkDescriptorImageInfo background_image_descriptor = create_descriptor(textures.envmap); write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - descriptor_sets.background, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &matrix_common_buffer_descriptor), - vkb::initializers::write_descriptor_set( - descriptor_sets.background, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - 1, - &background_image_descriptor)}; - - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkb::initializers::write_descriptor_set(descriptor_sets.background, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_common_buffer_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets.background, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &background_image_descriptor)}; + + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); } /** @@ -595,35 +520,20 @@ void LogicOpDynamicState::model_data_creation() cube.index_count = index_count; /* Array with vertices indexes for corresponding triangles */ - std::array indices{0, 4, 3, 7, - UINT32_MAX, - 1, 0, 2, 3, - UINT32_MAX, - 2, 6, 1, 5, - UINT32_MAX, - 1, 5, 0, 4, - UINT32_MAX, - 4, 5, 7, 6, - UINT32_MAX, - 2, 3, 6, 7}; + std::array indices{0, 4, 3, 7, UINT32_MAX, 1, 0, 2, 3, UINT32_MAX, 2, 6, 1, 5, UINT32_MAX, + 1, 5, 0, 4, UINT32_MAX, 4, 5, 7, 6, UINT32_MAX, 2, 3, 6, 7}; vkb::core::BufferC vertex_pos_staging = vkb::core::BufferC::create_staging_buffer(get_device(), vertices_pos); vkb::core::BufferC vertex_norm_staging = vkb::core::BufferC::create_staging_buffer(get_device(), vertices_norm); vkb::core::BufferC index_staging = vkb::core::BufferC::create_staging_buffer(get_device(), indices); - cube.vertices_pos = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + cube.vertices_pos = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); - cube.vertices_norm = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + cube.vertices_norm = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); - cube.indices = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + cube.indices = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); /* Copy from staging buffers */ @@ -632,27 +542,12 @@ void LogicOpDynamicState::model_data_creation() VkBufferCopy copy_region = {}; copy_region.size = vertex_buffer_size; - vkCmdCopyBuffer( - copy_command, - vertex_pos_staging.get_handle(), - cube.vertices_pos->get_handle(), - 1, - ©_region); - - vkCmdCopyBuffer( - copy_command, - vertex_norm_staging.get_handle(), - cube.vertices_norm->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, vertex_pos_staging.get_handle(), cube.vertices_pos->get_handle(), 1, ©_region); + + vkCmdCopyBuffer(copy_command, vertex_norm_staging.get_handle(), cube.vertices_norm->get_handle(), 1, ©_region); copy_region.size = index_buffer_size; - vkCmdCopyBuffer( - copy_command, - index_staging.get_handle(), - cube.indices->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, index_staging.get_handle(), cube.indices->get_handle(), 1, ©_region); get_device().flush_command_buffer(copy_command, queue, true); } diff --git a/samples/extensions/memory_budget/memory_budget.cpp b/samples/extensions/memory_budget/memory_budget.cpp index fb200ee02b..d52a08d40f 100644 --- a/samples/extensions/memory_budget/memory_budget.cpp +++ b/samples/extensions/memory_budget/memory_budget.cpp @@ -221,48 +221,32 @@ void MemoryBudget::load_assets() void MemoryBudget::setup_descriptor_pool() { // Example uses one ubo - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2), - }; + std::vector pool_sizes = { + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2), + }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - vkb::to_u32(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(vkb::to_u32(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void MemoryBudget::setup_descriptor_set_layout() { - std::vector set_layout_bindings = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - // Binding 1 : Fragment shader combined sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), - }; + std::vector set_layout_bindings = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Fragment shader combined sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), + }; VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - vkb::to_u32(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), vkb::to_u32(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } @@ -279,8 +263,10 @@ void MemoryBudget::setup_descriptor_set() VkDescriptorImageInfo image_descriptor = create_descriptor(textures.rocks); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_set_alloc_info, &descriptor_sets.instanced_rocks)); write_descriptor_sets = { - vkb::initializers::write_descriptor_set(descriptor_sets.instanced_rocks, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set(descriptor_sets.instanced_rocks, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &image_descriptor) // Binding 1 : Color map + vkb::initializers::write_descriptor_set(descriptor_sets.instanced_rocks, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, + &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_sets.instanced_rocks, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, + &image_descriptor) // Binding 1 : Color map }; vkUpdateDescriptorSets(get_device().get_handle(), vkb::to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); @@ -289,8 +275,10 @@ void MemoryBudget::setup_descriptor_set() image_descriptor = create_descriptor(textures.planet); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_set_alloc_info, &descriptor_sets.planet)); write_descriptor_sets = { - vkb::initializers::write_descriptor_set(descriptor_sets.planet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set(descriptor_sets.planet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &image_descriptor) // Binding 1 : Color map + vkb::initializers::write_descriptor_set(descriptor_sets.planet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, + &buffer_descriptor), // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_sets.planet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, + &image_descriptor) // Binding 1 : Color map }; vkUpdateDescriptorSets(get_device().get_handle(), vkb::to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } @@ -298,61 +286,32 @@ void MemoryBudget::setup_descriptor_set() void MemoryBudget::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - vkb::to_u32(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), vkb::to_u32(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages{}; - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pInputAssemblyState = &input_assembly_state; pipeline_create_info.pRasterizationState = &rasterization_state; @@ -371,11 +330,10 @@ void MemoryBudget::prepare_pipelines() // Vertex input bindings // The instancing pipeline uses a vertex input state with two bindings - binding_descriptions = { - // Binding point 0: Mesh vertex layout description at per-vertex rate - vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), - // Binding point 1: Instanced data at per-instance rate - vkb::initializers::vertex_input_binding_description(1, sizeof(InstanceData), VK_VERTEX_INPUT_RATE_INSTANCE)}; + binding_descriptions = {// Binding point 0: Mesh vertex layout description at per-vertex rate + vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX), + // Binding point 1: Instanced data at per-instance rate + vkb::initializers::vertex_input_binding_description(1, sizeof(InstanceData), VK_VERTEX_INPUT_RATE_INSTANCE)}; // Vertex attribute bindings // Note that the shader declaration for per-vertex and per-instance attributes is the same, the different input rates are only stored in the bindings: @@ -394,7 +352,7 @@ void MemoryBudget::prepare_pipelines() vkb::initializers::vertex_input_attribute_description(1, 3, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 3: Position vkb::initializers::vertex_input_attribute_description(1, 4, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3), // Location 4: Rotation vkb::initializers::vertex_input_attribute_description(1, 5, VK_FORMAT_R32_SFLOAT, sizeof(float) * 6), // Location 5: Scale - vkb::initializers::vertex_input_attribute_description(1, 6, VK_FORMAT_R32_SINT, sizeof(float) * 7), // Location 6: Texture array layer index + vkb::initializers::vertex_input_attribute_description(1, 6, VK_FORMAT_R32_SINT, sizeof(float) * 7), // Location 6: Texture array layer index }; input_state.pVertexBindingDescriptions = binding_descriptions.data(); input_state.pVertexAttributeDescriptions = attribute_descriptions.data(); @@ -450,16 +408,19 @@ void MemoryBudget::prepare_instance_data() rho = sqrt((pow(ring0[1], 2.0f) - pow(ring0[0], 2.0f)) * uniform_dist(rnd_generator) + pow(ring0[0], 2.0f)); theta = 2.0f * glm::pi() * uniform_dist(rnd_generator); instance_data[i].pos = glm::vec3(rho * cos(theta), uniform_dist(rnd_generator) * 0.5f - 0.25f, rho * sin(theta)); - instance_data[i].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator)); + instance_data[i].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), + glm::pi() * uniform_dist(rnd_generator)); instance_data[i].scale = 1.5f + uniform_dist(rnd_generator) - uniform_dist(rnd_generator); instance_data[i].texIndex = rnd_texture_index(rnd_generator); instance_data[i].scale *= 0.75f; // Outer ring - rho = sqrt((pow(ring1[1], 2.0f) - pow(ring1[0], 2.0f)) * uniform_dist(rnd_generator) + pow(ring1[0], 2.0f)); - theta = 2.0f * glm::pi() * uniform_dist(rnd_generator); - instance_data[static_cast(i + MESH_DENSITY_HALF)].pos = glm::vec3(rho * cos(theta), uniform_dist(rnd_generator) * 0.5f - 0.25f, rho * sin(theta)); - instance_data[static_cast(i + MESH_DENSITY_HALF)].rot = glm::vec3(glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator)); + rho = sqrt((pow(ring1[1], 2.0f) - pow(ring1[0], 2.0f)) * uniform_dist(rnd_generator) + pow(ring1[0], 2.0f)); + theta = 2.0f * glm::pi() * uniform_dist(rnd_generator); + instance_data[static_cast(i + MESH_DENSITY_HALF)].pos = + glm::vec3(rho * cos(theta), uniform_dist(rnd_generator) * 0.5f - 0.25f, rho * sin(theta)); + instance_data[static_cast(i + MESH_DENSITY_HALF)].rot = glm::vec3( + glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator), glm::pi() * uniform_dist(rnd_generator)); instance_data[static_cast(i + MESH_DENSITY_HALF)].scale = 1.5f + uniform_dist(rnd_generator) - uniform_dist(rnd_generator); instance_data[static_cast(i + MESH_DENSITY_HALF)].texIndex = rnd_texture_index(rnd_generator); instance_data[static_cast(i + MESH_DENSITY_HALF)].scale *= 0.75f; @@ -474,19 +435,15 @@ void MemoryBudget::prepare_instance_data() vkb::core::BufferC staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), instance_data); - instance_buffer.buffer = std::make_unique(get_device(), instance_buffer.size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + instance_buffer.buffer = std::make_unique( + get_device(), instance_buffer.size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Copy to staging buffer VkCommandBuffer copy_command = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); VkBufferCopy copy_region = {}; copy_region.size = instance_buffer.size; - vkCmdCopyBuffer( - copy_command, - staging_buffer.get_handle(), - instance_buffer.buffer->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, staging_buffer.get_handle(), instance_buffer.buffer->get_handle(), 1, ©_region); get_device().flush_command_buffer(copy_command, queue, true); @@ -497,10 +454,7 @@ void MemoryBudget::prepare_instance_data() void MemoryBudget::prepare_uniform_buffers() { - uniform_buffers.scene = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.scene = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffer(0.0f); } diff --git a/samples/extensions/mesh_shader_culling/mesh_shader_culling.cpp b/samples/extensions/mesh_shader_culling/mesh_shader_culling.cpp index d2a22713cb..ff32169c6f 100644 --- a/samples/extensions/mesh_shader_culling/mesh_shader_culling.cpp +++ b/samples/extensions/mesh_shader_culling/mesh_shader_culling.cpp @@ -130,15 +130,12 @@ void MeshShaderCulling::build_command_buffers() void MeshShaderCulling::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1)}; uint32_t number_of_descriptor_sets = 1; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), - pool_sizes.data(), - number_of_descriptor_sets); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), number_of_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -146,25 +143,21 @@ void MeshShaderCulling::setup_descriptor_pool() void MeshShaderCulling::setup_descriptor_set_layout() { std::vector set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_TASK_BIT_EXT, - 0)}; + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TASK_BIT_EXT, 0)}; VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void MeshShaderCulling::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); // Task shader descriptor set VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -172,10 +165,7 @@ void MeshShaderCulling::setup_descriptor_sets() VkDescriptorBufferInfo uniform_buffer_descriptor = create_descriptor(*uniform_buffer); std::vector write_descriptor_sets = { - vkb::initializers::write_descriptor_set(descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &uniform_buffer_descriptor)}; + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniform_buffer_descriptor)}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } @@ -187,25 +177,18 @@ void MeshShaderCulling::prepare_pipelines() // Rasterization state VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); // Color blend state - VkPipelineColorBlendAttachmentState blend_attachment = - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment); // Multisample state - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); // Viewport state - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); // Depth stencil state VkPipelineDepthStencilStateCreateInfo depth_stencil_state = @@ -215,9 +198,7 @@ void MeshShaderCulling::prepare_pipelines() std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Shader state std::vector shader_stages{}; @@ -242,10 +223,7 @@ void MeshShaderCulling::prepare_pipelines() void MeshShaderCulling::prepare_uniform_buffers() { - uniform_buffer = std::make_unique(get_device(), - sizeof(ubo_cull), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer = std::make_unique(get_device(), sizeof(ubo_cull), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -364,9 +342,7 @@ void MeshShaderCulling::setup_query_result_buffer() VkMemoryRequirements memory_requirements; VkMemoryAllocateInfo memory_allocation = vkb::initializers::memory_allocate_info(); VkBufferCreateInfo buffer_create_info = - vkb::initializers::buffer_create_info( - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - buffer_size); + vkb::initializers::buffer_create_info(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, buffer_size); // Results are saved in a host visible buffer for easy access by the application VK_CHECK(vkCreateBuffer(get_device().get_handle(), &buffer_create_info, nullptr, &query_result.buffer)); @@ -383,10 +359,9 @@ void MeshShaderCulling::setup_query_result_buffer() VkQueryPoolCreateInfo query_pool_info = {}; query_pool_info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; query_pool_info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; - query_pool_info.pipelineStatistics = - VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | - VK_QUERY_PIPELINE_STATISTIC_TASK_SHADER_INVOCATIONS_BIT_EXT | - VK_QUERY_PIPELINE_STATISTIC_MESH_SHADER_INVOCATIONS_BIT_EXT; + query_pool_info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | + VK_QUERY_PIPELINE_STATISTIC_TASK_SHADER_INVOCATIONS_BIT_EXT | + VK_QUERY_PIPELINE_STATISTIC_MESH_SHADER_INVOCATIONS_BIT_EXT; query_pool_info.queryCount = 3; VK_CHECK(vkCreateQueryPool(get_device().get_handle(), &query_pool_info, nullptr, &query_pool)); } @@ -396,13 +371,5 @@ void MeshShaderCulling::setup_query_result_buffer() void MeshShaderCulling::get_query_results() { // We use vkGetQueryResults to copy the results into a host visible buffer - vkGetQueryPoolResults( - get_device().get_handle(), - query_pool, - 0, - 1, - sizeof(pipeline_stats), - pipeline_stats, - sizeof(uint64_t), - VK_QUERY_RESULT_64_BIT); + vkGetQueryPoolResults(get_device().get_handle(), query_pool, 0, 1, sizeof(pipeline_stats), pipeline_stats, sizeof(uint64_t), VK_QUERY_RESULT_64_BIT); } diff --git a/samples/extensions/mesh_shading/mesh_shading.cpp b/samples/extensions/mesh_shading/mesh_shading.cpp index 011341e646..c0fd3d2d53 100644 --- a/samples/extensions/mesh_shading/mesh_shading.cpp +++ b/samples/extensions/mesh_shading/mesh_shading.cpp @@ -22,8 +22,7 @@ #include "mesh_shading.h" -MeshShading::MeshShading() : - pipeline(VK_NULL_HANDLE), pipeline_layout(VK_NULL_HANDLE), descriptor_set(VK_NULL_HANDLE), descriptor_set_layout(VK_NULL_HANDLE) +MeshShading::MeshShading() : pipeline(VK_NULL_HANDLE), pipeline_layout(VK_NULL_HANDLE), descriptor_set(VK_NULL_HANDLE), descriptor_set_layout(VK_NULL_HANDLE) { title = "Mesh shading"; @@ -127,78 +126,45 @@ void MeshShading::draw() void MeshShading::prepare_pipelines() { - VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - 0, nullptr, - 2); + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(0, nullptr, 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); - VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - nullptr, - 0); + VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(nullptr, 0); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); // Create a blank pipeline layout. // We are not binding any resources to the pipeline in this first sample. - VkPipelineLayoutCreateInfo layout_info = vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo layout_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &layout_info, nullptr, &pipeline_layout)); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); // Our attachment will write to all color channels, but no blending is enabled. - VkPipelineColorBlendAttachmentState blend_attachment = vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo blend = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment); + VkPipelineColorBlendStateCreateInfo blend = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_TRUE, VK_COMPARE_OP_GREATER); // We will have one viewport and scissor box. - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); // No multisampling. - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); // Specify that these states will be dynamic, i.e. not part of pipeline state object. - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Load our SPIR-V shaders. std::array shader_stages{}; @@ -206,11 +172,7 @@ void MeshShading::prepare_pipelines() shader_stages[0] = load_shader("mesh_shading", "ms.mesh.spv", VK_SHADER_STAGE_MESH_BIT_EXT); shader_stages[1] = load_shader("mesh_shading", "ps.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = nullptr; pipeline_create_info.pInputAssemblyState = nullptr; diff --git a/samples/extensions/open_cl_common/open_cl_utils.cpp b/samples/extensions/open_cl_common/open_cl_utils.cpp index 59acc6b3c0..06a250ef35 100644 --- a/samples/extensions/open_cl_common/open_cl_utils.cpp +++ b/samples/extensions/open_cl_common/open_cl_utils.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2023, Arm Limited and Contributors +/* Copyright (c) 2021-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -40,20 +40,12 @@ cl_platform_id load_opencl() // Try to find the OpenCL library on one of the following paths static const char *libraryPaths[] = { // Generic - "/system/vendor/lib64/libOpenCL.so", - "/system/lib64/libOpenCL.so", - "/system/vendor/lib/libOpenCL.so", - "/system/lib/libOpenCL.so", + "/system/vendor/lib64/libOpenCL.so", "/system/lib64/libOpenCL.so", "/system/vendor/lib/libOpenCL.so", "/system/lib/libOpenCL.so", // ARM Mali - "/system/vendor/lib64/egl/libGLES_mali.so", - "/system/lib64/egl/libGLES_mali.so", - "/system/vendor/lib/egl/libGLES_mali.so", + "/system/vendor/lib64/egl/libGLES_mali.so", "/system/lib64/egl/libGLES_mali.so", "/system/vendor/lib/egl/libGLES_mali.so", "/system/lib/egl/libGLES_mali.so", // PowerVR - "/system/vendor/lib64/libPVROCL.so", - "/system/lib64/libPVROCL.so", - "/system/vendor/lib/libPVROCL.so", - "/system/lib/libPVROCL.so"}; + "/system/vendor/lib64/libPVROCL.so", "/system/lib64/libPVROCL.so", "/system/vendor/lib/libPVROCL.so", "/system/lib/libPVROCL.so"}; for (auto libraryPath : libraryPaths) { handle = dlopen(libraryPath, RTLD_LAZY); @@ -64,19 +56,18 @@ cl_platform_id load_opencl() } #elif defined(__linux__) // Try to find the OpenCL library on one of the following paths - static const char *libraryPaths[] = { - "libOpenCL.so", - "/usr/lib/libOpenCL.so", - "/usr/local/lib/libOpenCL.so", - "/usr/local/lib/libpocl.so", - "/usr/lib64/libOpenCL.so", - "/usr/lib32/libOpenCL.so", - "libOpenCL.so.1", - "/usr/lib/libOpenCL.so.1", - "/usr/local/lib/libOpenCL.so.1", - "/usr/local/lib/libpocl.so.1", - "/usr/lib64/libOpenCL.so.1", - "/usr/lib32/libOpenCL.so.1"}; + static const char *libraryPaths[] = {"libOpenCL.so", + "/usr/lib/libOpenCL.so", + "/usr/local/lib/libOpenCL.so", + "/usr/local/lib/libpocl.so", + "/usr/lib64/libOpenCL.so", + "/usr/lib32/libOpenCL.so", + "libOpenCL.so.1", + "/usr/lib/libOpenCL.so.1", + "/usr/local/lib/libOpenCL.so.1", + "/usr/local/lib/libpocl.so.1", + "/usr/lib64/libOpenCL.so.1", + "/usr/lib32/libOpenCL.so.1"}; for (auto libraryPath : libraryPaths) { handle = dlopen(libraryPath, RTLD_LAZY); @@ -105,8 +96,8 @@ cl_platform_id load_opencl() cl_uint num_platforms; clGetPlatformIDs_ptr(1, &platform_id, &num_platforms); -#define OPENCL_EXPORTED_EXTENSION_FUNCTION(func_name) func_name##_ptr = \ - reinterpret_cast(clGetExtensionFunctionAddressForPlatform_ptr(platform_id, #func_name)) +#define OPENCL_EXPORTED_EXTENSION_FUNCTION(func_name) \ + func_name##_ptr = reinterpret_cast(clGetExtensionFunctionAddressForPlatform_ptr(platform_id, #func_name)) #include "open_cl_functions.inl" return platform_id; diff --git a/samples/extensions/open_cl_interop/open_cl_interop.cpp b/samples/extensions/open_cl_interop/open_cl_interop.cpp index efe8f966d6..2a1bc42ed2 100644 --- a/samples/extensions/open_cl_interop/open_cl_interop.cpp +++ b/samples/extensions/open_cl_interop/open_cl_interop.cpp @@ -29,8 +29,8 @@ #ifdef _WIN32 // On Windows, we need to enable some security settings to allow api interop -// The spec states: For handles of the following types: VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT The implementation must ensure the access rights allow read and write access to the memory. -// This class sets up the structures required for tis +// The spec states: For handles of the following types: VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT The implementation must ensure the access rights allow +// read and write access to the memory. This class sets up the structures required for tis class WinSecurityAttributes { private: @@ -207,7 +207,8 @@ void OpenCLInterop::render(float delta_time) CL_CHECK(clSetKernelArg(opencl_objects.kernel, 0, sizeof(cl_mem), &opencl_objects.image)); CL_CHECK(clSetKernelArg(opencl_objects.kernel, 1, sizeof(float), &total_time_passed)); - CL_CHECK(clEnqueueNDRangeKernel(opencl_objects.command_queue, opencl_objects.kernel, global_size.size(), nullptr, global_size.data(), local_size.data(), 0, nullptr, nullptr)); + CL_CHECK(clEnqueueNDRangeKernel(opencl_objects.command_queue, opencl_objects.kernel, global_size.size(), nullptr, global_size.data(), local_size.data(), 0, + nullptr, nullptr)); // Release the image (resource) to Vulkan CL_CHECK(clEnqueueReleaseExternalMemObjectsKHR(opencl_objects.command_queue, 1, &opencl_objects.image, 0, nullptr, nullptr)); @@ -278,12 +279,10 @@ void OpenCLInterop::build_command_buffers() void OpenCLInterop::generate_quad() { - std::vector vertices = - { - {{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, - {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; + std::vector vertices = {{{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, + {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; std::vector indices = {0, 1, 2, 2, 3, 0}; index_count = static_cast(indices.size()); @@ -294,15 +293,11 @@ void OpenCLInterop::generate_quad() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory // Vertex buffer - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); @@ -310,14 +305,11 @@ void OpenCLInterop::generate_quad() void OpenCLInterop::setup_descriptor_pool() { - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + VkDescriptorPoolCreateInfo descriptor_pool_create_info = + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -330,7 +322,8 @@ void OpenCLInterop::setup_descriptor_set_layout() // Binding 1 : Fragment shader image sampler vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), vkb::to_u32(set_layout_bindings.size())); + VkDescriptorSetLayoutCreateInfo descriptor_layout = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), vkb::to_u32(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); @@ -361,52 +354,27 @@ void OpenCLInterop::setup_descriptor_set() void OpenCLInterop::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using Reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - vkb::to_u32(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), vkb::to_u32(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages{}; @@ -416,8 +384,7 @@ void OpenCLInterop::prepare_pipelines() // Vertex bindings and attributes const std::vector vertex_input_bindings = { - vkb::initializers::vertex_input_binding_description(0, sizeof(VertexStructure), - VK_VERTEX_INPUT_RATE_VERTEX), + vkb::initializers::vertex_input_binding_description(0, sizeof(VertexStructure), VK_VERTEX_INPUT_RATE_VERTEX), }; const std::vector vertex_input_attributes = { vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VertexStructure, pos)), @@ -449,10 +416,7 @@ void OpenCLInterop::prepare_pipelines() void OpenCLInterop::prepare_uniform_buffers() { // Vertex shader uniform buffer block - uniform_buffer_vs = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer_vs = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -544,7 +508,7 @@ void OpenCLInterop::prepare_shared_image() image_create_info.samples = VK_SAMPLE_COUNT_1_BIT; image_create_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_create_info.extent = {shared_image.width, shared_image.height, 1}; - image_create_info.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; + image_create_info.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; VkExternalMemoryImageCreateInfo external_memory_image_info{}; external_memory_image_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO; @@ -613,14 +577,8 @@ void OpenCLInterop::prepare_shared_image() image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - vkCmdPipelineBarrier( - copy_command, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - 0, - 0, nullptr, - 0, nullptr, - 1, &image_memory_barrier); + vkCmdPipelineBarrier(copy_command, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, + &image_memory_barrier); get_device().flush_command_buffer(copy_command, queue, true); @@ -655,13 +613,8 @@ void OpenCLInterop::prepare_shared_image() cl_img_desc.buffer = nullptr; int cl_result; - opencl_objects.image = clCreateImageWithProperties(opencl_objects.context, - mem_properties.data(), - CL_MEM_READ_WRITE, - &cl_img_fmt, - &cl_img_desc, - NULL, - &cl_result); + opencl_objects.image = + clCreateImageWithProperties(opencl_objects.context, mem_properties.data(), CL_MEM_READ_WRITE, &cl_img_fmt, &cl_img_desc, NULL, &cl_result); CL_CHECK(cl_result); } @@ -758,12 +711,10 @@ void OpenCLInterop::prepare_opencl_resources() vkGetPhysicalDeviceProperties2KHR(get_device().get_gpu().get_handle(), &physical_device_properties_2); // We also need to make sure the OpenCL platform/device supports all the extensions required in this sample - std::vector required_extensions{ - // Platform independent OpenCL extensions for interop and for getting the device - "cl_khr_external_memory", - "cl_khr_external_semaphore", - // Extension required to read the uuid of a device (see below for more information on why this is required) - "cl_khr_device_uuid"}; + std::vector required_extensions{// Platform independent OpenCL extensions for interop and for getting the device + "cl_khr_external_memory", "cl_khr_external_semaphore", + // Extension required to read the uuid of a device (see below for more information on why this is required) + "cl_khr_device_uuid"}; // Platform specific OpenCL extensions for interop #if defined(_WIN32) required_extensions.push_back("cl_khr_external_memory_win32"); diff --git a/samples/extensions/open_cl_interop_arm/open_cl_interop_arm.cpp b/samples/extensions/open_cl_interop_arm/open_cl_interop_arm.cpp index d5ce402b4a..0ffaae1b91 100644 --- a/samples/extensions/open_cl_interop_arm/open_cl_interop_arm.cpp +++ b/samples/extensions/open_cl_interop_arm/open_cl_interop_arm.cpp @@ -198,12 +198,10 @@ void OpenCLInteropArm::build_command_buffers() void OpenCLInteropArm::generate_quad() { - std::vector vertices = - { - {{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, - {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; + std::vector vertices = {{{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, + {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}}; std::vector indices = {0, 1, 2, 2, 3, 0}; index_count = static_cast(indices.size()); @@ -214,17 +212,11 @@ void OpenCLInteropArm::generate_quad() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory // Vertex buffer - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); @@ -232,14 +224,11 @@ void OpenCLInteropArm::generate_quad() void OpenCLInteropArm::setup_descriptor_pool() { - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + VkDescriptorPoolCreateInfo descriptor_pool_create_info = + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -248,40 +237,24 @@ void OpenCLInteropArm::setup_descriptor_set_layout() { std::vector set_layout_bindings{ // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), // Binding 1 : Fragment shader image sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - vkb::to_u32(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), vkb::to_u32(set_layout_bindings.size())); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, - &descriptor_set_layout)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); - VK_CHECK( - vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, - &pipeline_layout)); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void OpenCLInteropArm::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -293,76 +266,45 @@ void OpenCLInteropArm::setup_descriptor_set() image_descriptor.sampler = shared_texture.sampler; image_descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - std::vector write_descriptor_sets = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &buffer_descriptor), - // Binding 1 : Fragment shader texture sampler - // Fragment shader: layout (binding = 1) uniform sampler2D samplerColor; - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // The descriptor set will use a combined image sampler (sampler and image could be split) - 1, // Shader binding point 1 - &image_descriptor) // Pointer to the descriptor image for our texture - }; - - vkUpdateDescriptorSets(get_device().get_handle(), vkb::to_u32(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, nullptr); + std::vector write_descriptor_sets = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), + // Binding 1 : Fragment shader texture sampler + // Fragment shader: layout (binding = 1) uniform sampler2D samplerColor; + vkb::initializers::write_descriptor_set( + descriptor_set, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // The descriptor set will use a combined image sampler (sampler and image could be split) + 1, // Shader binding point 1 + &image_descriptor) // Pointer to the descriptor image for our texture + }; + + vkUpdateDescriptorSets(get_device().get_handle(), vkb::to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, nullptr); } void OpenCLInteropArm::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - vkb::to_u32(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), vkb::to_u32(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages{}; @@ -372,30 +314,20 @@ void OpenCLInteropArm::prepare_pipelines() // Vertex bindings and attributes const std::vector vertex_input_bindings = { - vkb::initializers::vertex_input_binding_description(0, sizeof(VertexStructure), - VK_VERTEX_INPUT_RATE_VERTEX), + vkb::initializers::vertex_input_binding_description(0, sizeof(VertexStructure), VK_VERTEX_INPUT_RATE_VERTEX), }; const std::vector vertex_input_attributes = { - vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, - offsetof(VertexStructure, pos)), - vkb::initializers::vertex_input_attribute_description(0, 1, VK_FORMAT_R32G32_SFLOAT, - offsetof(VertexStructure, uv)), - vkb::initializers::vertex_input_attribute_description(0, 2, VK_FORMAT_R32G32B32_SFLOAT, - offsetof(VertexStructure, - normal)), + vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VertexStructure, pos)), + vkb::initializers::vertex_input_attribute_description(0, 1, VK_FORMAT_R32G32_SFLOAT, offsetof(VertexStructure, uv)), + vkb::initializers::vertex_input_attribute_description(0, 2, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VertexStructure, normal)), }; VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); vertex_input_state.vertexBindingDescriptionCount = vkb::to_u32(vertex_input_bindings.size()); vertex_input_state.pVertexBindingDescriptions = vertex_input_bindings.data(); - vertex_input_state.vertexAttributeDescriptionCount = vkb::to_u32( - vertex_input_attributes.size()); - vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); + vertex_input_state.vertexAttributeDescriptionCount = vkb::to_u32(vertex_input_attributes.size()); + vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -408,17 +340,13 @@ void OpenCLInteropArm::prepare_pipelines() pipeline_create_info.stageCount = vkb::to_u32(shader_stages.size()); pipeline_create_info.pStages = shader_stages.data(); - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, - &pipeline_create_info, nullptr, &pipeline)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, &pipeline)); } void OpenCLInteropArm::prepare_uniform_buffers() { // Vertex shader uniform buffer block - uniform_buffer_vs = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer_vs = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -454,8 +382,7 @@ void OpenCLInteropArm::prepare_shared_resources() // When creating a VkImage object we need to tell explicitly that it will be backed by external memory // In this case it's Android Hardware Buffer, so we specify the handle type accordingly VkExternalMemoryImageCreateInfo external_memory_image_create_info; - external_memory_image_create_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, - external_memory_image_create_info.pNext = nullptr, + external_memory_image_create_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, external_memory_image_create_info.pNext = nullptr, external_memory_image_create_info.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID; VkImageCreateInfo image_create_info = vkb::initializers::image_create_info(); @@ -539,14 +466,8 @@ void OpenCLInteropArm::prepare_shared_resources() image_memory_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_memory_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - vkCmdPipelineBarrier( - copy_command, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - 0, - 0, nullptr, - 0, nullptr, - 1, &image_memory_barrier); + vkCmdPipelineBarrier(copy_command, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, + &image_memory_barrier); get_device().flush_command_buffer(copy_command, queue, true); @@ -554,17 +475,11 @@ void OpenCLInteropArm::prepare_shared_resources() // In the list of properties CL_IMPORT_TYPE_ARM is set to Android Hardware Buffer // The list is terminated with 0 - const cl_import_properties_arm import_properties[3] = { - CL_IMPORT_TYPE_ARM, CL_IMPORT_TYPE_ANDROID_HARDWARE_BUFFER_ARM, - 0}; + const cl_import_properties_arm import_properties[3] = {CL_IMPORT_TYPE_ARM, CL_IMPORT_TYPE_ANDROID_HARDWARE_BUFFER_ARM, 0}; cl_int result = CL_SUCCESS; - cl_data->image = clImportMemoryARM(cl_data->context, - CL_MEM_READ_WRITE, - import_properties, - shared_texture.hardware_buffer, - CL_IMPORT_MEMORY_WHOLE_ALLOCATION_ARM, - &result); + cl_data->image = clImportMemoryARM(cl_data->context, CL_MEM_READ_WRITE, import_properties, shared_texture.hardware_buffer, + CL_IMPORT_MEMORY_WHOLE_ALLOCATION_ARM, &result); if (result != CL_SUCCESS) { @@ -594,9 +509,7 @@ void OpenCLInteropArm::prepare_open_cl_resources() } auto available_extensions = get_available_open_cl_extensions(platform_id); - std::vector required_extensions{ - "cl_arm_import_memory", - "cl_arm_import_memory_android_hardware_buffer"}; + std::vector required_extensions{"cl_arm_import_memory", "cl_arm_import_memory_android_hardware_buffer"}; for (auto extension : required_extensions) { @@ -644,13 +557,8 @@ void OpenCLInteropArm::run_texture_generation() std::array global_size = {shared_texture.width, shared_texture.height}; std::array local_size = {16, 16}; - cl_int result = clEnqueueNDRangeKernel(cl_data->command_queue, - cl_data->kernel, - global_size.size(), - NULL, - global_size.data(), - local_size.data(), - 0, NULL, NULL); + cl_int result = + clEnqueueNDRangeKernel(cl_data->command_queue, cl_data->kernel, global_size.size(), NULL, global_size.data(), local_size.data(), 0, NULL, NULL); if (result != CL_SUCCESS) { diff --git a/samples/extensions/open_gl_interop/offscreen_context.cpp b/samples/extensions/open_gl_interop/offscreen_context.cpp index 2f9b8133b2..54ef822848 100644 --- a/samples/extensions/open_gl_interop/offscreen_context.cpp +++ b/samples/extensions/open_gl_interop/offscreen_context.cpp @@ -1,5 +1,5 @@ -/* Copyright (c) 2020-2024, Arm Limited - * Copyright (c) 2020-2024, Bradley Austin Davis +/* Copyright (c) 2020-2026, Arm Limited + * Copyright (c) 2020-2026, Bradley Austin Davis * * SPDX-License-Identifier: Apache-2.0 * @@ -102,14 +102,11 @@ GLuint OffscreenContext::build_program(const char *vertex_shader_source, const c #ifdef VK_USE_PLATFORM_ANDROID_KHR void OffscreenContext::init_context() { - EGLint egl_maj_vers{0}, - egl_min_vers{0}; + EGLint egl_maj_vers{0}, egl_min_vers{0}; data.display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(data.display, &egl_maj_vers, &egl_min_vers); - constexpr EGLint conf_attr[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR, - EGL_NONE}; + constexpr EGLint conf_attr[] = {EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR, EGL_NONE}; EGLint num_configs; eglChooseConfig(data.display, conf_attr, &data.config, 1, &num_configs); diff --git a/samples/extensions/open_gl_interop/open_gl_interop.cpp b/samples/extensions/open_gl_interop/open_gl_interop.cpp index e23e237f65..84241b87f9 100644 --- a/samples/extensions/open_gl_interop/open_gl_interop.cpp +++ b/samples/extensions/open_gl_interop/open_gl_interop.cpp @@ -131,17 +131,12 @@ void OpenGLInterop::prepare_shared_resources() auto physicalDeviceHandle = get_device().get_gpu().get_handle(); { - VkExternalSemaphoreHandleTypeFlagBits flags[] = { - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT}; - - VkPhysicalDeviceExternalSemaphoreInfo zzzz{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO, nullptr}; - VkExternalSemaphoreProperties aaaa{VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES, - nullptr}; + VkExternalSemaphoreHandleTypeFlagBits flags[] = {VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT, + VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT, + VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT, VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT}; + + VkPhysicalDeviceExternalSemaphoreInfo zzzz{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO, nullptr}; + VkExternalSemaphoreProperties aaaa{VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES, nullptr}; bool found = false; VkExternalSemaphoreHandleTypeFlagBits compatable_semaphore_type; @@ -162,28 +157,21 @@ void OpenGLInterop::prepare_shared_resources() throw; } - VkExportSemaphoreCreateInfo exportSemaphoreCreateInfo{ - VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO, nullptr, - static_cast(compatable_semaphore_type)}; - VkSemaphoreCreateInfo semaphoreCreateInfo{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, - &exportSemaphoreCreateInfo}; - VK_CHECK(vkCreateSemaphore(deviceHandle, &semaphoreCreateInfo, nullptr, - &sharedSemaphores.gl_complete)); - VK_CHECK(vkCreateSemaphore(deviceHandle, &semaphoreCreateInfo, nullptr, - &sharedSemaphores.gl_ready)); + VkExportSemaphoreCreateInfo exportSemaphoreCreateInfo{VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO, nullptr, + static_cast(compatable_semaphore_type)}; + VkSemaphoreCreateInfo semaphoreCreateInfo{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &exportSemaphoreCreateInfo}; + VK_CHECK(vkCreateSemaphore(deviceHandle, &semaphoreCreateInfo, nullptr, &sharedSemaphores.gl_complete)); + VK_CHECK(vkCreateSemaphore(deviceHandle, &semaphoreCreateInfo, nullptr, &sharedSemaphores.gl_ready)); #ifdef WIN32 - VkSemaphoreGetWin32HandleInfoKHR semaphoreGetHandleInfo{ - VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR, nullptr, - VK_NULL_HANDLE, compatable_semaphore_type}; + VkSemaphoreGetWin32HandleInfoKHR semaphoreGetHandleInfo{VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR, nullptr, VK_NULL_HANDLE, + compatable_semaphore_type}; semaphoreGetHandleInfo.semaphore = sharedSemaphores.gl_ready; VK_CHECK(vkGetSemaphoreWin32HandleKHR(deviceHandle, &semaphoreGetHandleInfo, &shareHandles.gl_ready)); semaphoreGetHandleInfo.semaphore = sharedSemaphores.gl_complete; VK_CHECK(vkGetSemaphoreWin32HandleKHR(deviceHandle, &semaphoreGetHandleInfo, &shareHandles.gl_complete)); #else - VkSemaphoreGetFdInfoKHR semaphoreGetFdInfo{ - VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR, nullptr, - VK_NULL_HANDLE, compatable_semaphore_type}; + VkSemaphoreGetFdInfoKHR semaphoreGetFdInfo{VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR, nullptr, VK_NULL_HANDLE, compatable_semaphore_type}; semaphoreGetFdInfo.semaphore = sharedSemaphores.gl_ready; VK_CHECK(vkGetSemaphoreFdKHR(deviceHandle, &semaphoreGetFdInfo, &shareHandles.gl_ready)); semaphoreGetFdInfo.semaphore = sharedSemaphores.gl_complete; @@ -233,18 +221,16 @@ void OpenGLInterop::prepare_shared_resources() VkMemoryAllocateInfo memAllocInfo{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &export_memory_allocate_Info}; memAllocInfo.allocationSize = sharedTexture.allocationSize = memReqs.size; - memAllocInfo.memoryTypeIndex = get_device().get_gpu().get_memory_type(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + memAllocInfo.memoryTypeIndex = get_device().get_gpu().get_memory_type(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK(vkAllocateMemory(deviceHandle, &memAllocInfo, nullptr, &sharedTexture.memory)); VK_CHECK(vkBindImageMemory(deviceHandle, sharedTexture.image, sharedTexture.memory, 0)); #ifdef WIN32 - VkMemoryGetWin32HandleInfoKHR memoryFdInfo{VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR, nullptr, - sharedTexture.memory, + VkMemoryGetWin32HandleInfoKHR memoryFdInfo{VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR, nullptr, sharedTexture.memory, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT}; VK_CHECK(vkGetMemoryWin32HandleKHR(deviceHandle, &memoryFdInfo, &shareHandles.memory)); #else - VkMemoryGetFdInfoKHR memoryFdInfo{VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR, nullptr, - sharedTexture.memory, + VkMemoryGetFdInfoKHR memoryFdInfo{VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR, nullptr, sharedTexture.memory, VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT}; VK_CHECK(vkGetMemoryFdKHR(deviceHandle, &memoryFdInfo, &shareHandles.memory)); #endif @@ -270,12 +256,13 @@ void OpenGLInterop::prepare_shared_resources() viewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; viewCreateInfo.image = sharedTexture.image; viewCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; - viewCreateInfo.subresourceRange = VkImageSubresourceRange{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, - 0, 1}; + viewCreateInfo.subresourceRange = VkImageSubresourceRange{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; vkCreateImageView(deviceHandle, &viewCreateInfo, nullptr, &sharedTexture.view); with_command_buffer( - [&](VkCommandBuffer image_command_buffer) { vkb::image_layout_transition(image_command_buffer, sharedTexture.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); }, + [&](VkCommandBuffer image_command_buffer) { + vkb::image_layout_transition(image_command_buffer, sharedTexture.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + }, sharedSemaphores.gl_ready); } } @@ -283,13 +270,12 @@ void OpenGLInterop::prepare_shared_resources() void OpenGLInterop::generate_quad() { // Setup vertices for a single uv-mapped quad made from two triangles - std::vector vertices = - { - {{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, - {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, - {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, - }; + std::vector vertices = { + {{1.0f, 1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, 1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f, 1.0f}}, + {{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, + {{1.0f, -1.0f, 0.0f}, {1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}, + }; // Setup indices std::vector indices = {0, 1, 2, 2, 3, 0}; @@ -301,17 +287,11 @@ void OpenGLInterop::generate_quad() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory // Vertex buffer - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); @@ -327,61 +307,37 @@ void OpenGLInterop::request_instance_extensions(std::unordered_map pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); - - VK_CHECK( - vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, - &descriptor_pool)); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); + + VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void OpenGLInterop::setup_descriptor_set_layout() { std::vector set_layout_bindings{ // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), // Binding 1 : Fragment shader image sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - vkb::to_u32(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), vkb::to_u32(set_layout_bindings.size())); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, - &descriptor_set_layout)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); - VK_CHECK( - vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, - &pipeline_layout)); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void OpenGLInterop::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -389,80 +345,51 @@ void OpenGLInterop::setup_descriptor_set() // Setup a descriptor image info for the current texture to be used as a combined image sampler VkDescriptorImageInfo image_descriptor; - image_descriptor.imageView = sharedTexture.view; // The image's view (images are never directly accessed by the shader, but rather through views defining subresources) - image_descriptor.sampler = sharedTexture.sampler; // The sampler (Telling the pipeline how to sample the texture, including repeat, border, etc.) - image_descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // The current layout of the image (Note: Should always fit the actual use, e.g. shader read) - - std::vector write_descriptor_sets = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &buffer_descriptor), - // Binding 1 : Fragment shader texture sampler - // Fragment shader: layout (binding = 1) uniform sampler2D samplerColor; - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // The descriptor set will use a combined image sampler (sampler and image could be split) - 1, // Shader binding point 1 - &image_descriptor) // Pointer to the descriptor image for our texture - }; - - vkUpdateDescriptorSets(get_device().get_handle(), vkb::to_u32(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, NULL); + image_descriptor.imageView = + sharedTexture.view; // The image's view (images are never directly accessed by the shader, but rather through views defining subresources) + image_descriptor.sampler = sharedTexture.sampler; // The sampler (Telling the pipeline how to sample the texture, including repeat, border, etc.) + image_descriptor.imageLayout = + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // The current layout of the image (Note: Should always fit the actual use, e.g. shader read) + + std::vector write_descriptor_sets = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), + // Binding 1 : Fragment shader texture sampler + // Fragment shader: layout (binding = 1) uniform sampler2D samplerColor; + vkb::initializers::write_descriptor_set( + descriptor_set, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // The descriptor set will use a combined image sampler (sampler and image could be split) + 1, // Shader binding point 1 + &image_descriptor) // Pointer to the descriptor image for our texture + }; + + vkUpdateDescriptorSets(get_device().get_handle(), vkb::to_u32(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); } void OpenGLInterop::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - vkb::to_u32(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), vkb::to_u32(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages; @@ -472,30 +399,20 @@ void OpenGLInterop::prepare_pipelines() // Vertex bindings and attributes const std::vector vertex_input_bindings = { - vkb::initializers::vertex_input_binding_description(0, sizeof(VertexStructure), - VK_VERTEX_INPUT_RATE_VERTEX), + vkb::initializers::vertex_input_binding_description(0, sizeof(VertexStructure), VK_VERTEX_INPUT_RATE_VERTEX), }; const std::vector vertex_input_attributes = { - vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, - offsetof(VertexStructure, pos)), - vkb::initializers::vertex_input_attribute_description(0, 1, VK_FORMAT_R32G32_SFLOAT, - offsetof(VertexStructure, uv)), - vkb::initializers::vertex_input_attribute_description(0, 2, VK_FORMAT_R32G32B32_SFLOAT, - offsetof(VertexStructure, - normal)), + vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VertexStructure, pos)), + vkb::initializers::vertex_input_attribute_description(0, 1, VK_FORMAT_R32G32_SFLOAT, offsetof(VertexStructure, uv)), + vkb::initializers::vertex_input_attribute_description(0, 2, VK_FORMAT_R32G32B32_SFLOAT, offsetof(VertexStructure, normal)), }; VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); vertex_input_state.vertexBindingDescriptionCount = vkb::to_u32(vertex_input_bindings.size()); vertex_input_state.pVertexBindingDescriptions = vertex_input_bindings.data(); - vertex_input_state.vertexAttributeDescriptionCount = vkb::to_u32( - vertex_input_attributes.size()); - vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); + vertex_input_state.vertexAttributeDescriptionCount = vkb::to_u32(vertex_input_attributes.size()); + vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -508,18 +425,14 @@ void OpenGLInterop::prepare_pipelines() pipeline_create_info.stageCount = vkb::to_u32(shader_stages.size()); pipeline_create_info.pStages = shader_stages.data(); - VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, - &pipeline_create_info, nullptr, &pipeline)); + VK_CHECK(vkCreateGraphicsPipelines(get_device().get_handle(), pipeline_cache, 1, &pipeline_create_info, nullptr, &pipeline)); } // Prepare and initialize uniform buffer containing shader uniforms void OpenGLInterop::prepare_uniform_buffers() { // Vertex shader uniform buffer block - uniform_buffer_vs = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer_vs = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -527,8 +440,7 @@ void OpenGLInterop::prepare_uniform_buffers() void OpenGLInterop::update_uniform_buffers() { // Vertex shader - ubo_vs.projection = glm::perspective(glm::radians(60.0f), static_cast(width) / static_cast(height), - 0.001f, 256.0f); + ubo_vs.projection = glm::perspective(glm::radians(60.0f), static_cast(width) / static_cast(height), 0.001f, 256.0f); glm::mat4 view_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, zoom)); ubo_vs.model = view_matrix * glm::translate(glm::mat4(1.0f), camera_pos); @@ -584,8 +496,7 @@ bool OpenGLInterop::prepare(const vkb::ApplicationOptions &options) // Use the imported memory as backing for the OpenGL texture. The internalFormat, dimensions // and mip count should match the ones used by Vulkan to create the image and determine it's memory // allocation. - glTextureStorageMem2DEXT(gl_data->color, 1, GL_RGBA8, SHARED_TEXTURE_DIMENSION, - SHARED_TEXTURE_DIMENSION, gl_data->mem, 0); + glTextureStorageMem2DEXT(gl_data->color, 1, GL_RGBA8, SHARED_TEXTURE_DIMENSION, SHARED_TEXTURE_DIMENSION, gl_data->mem, 0); glBindTexture(GL_TEXTURE_2D, 0); // The remaining initialization code is all standard OpenGL @@ -597,8 +508,7 @@ bool OpenGLInterop::prepare(const vkb::ApplicationOptions &options) glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, gl_data->color, 0); glUseProgram(gl_data->program); - glProgramUniform3f(gl_data->program, 0, static_cast(SHARED_TEXTURE_DIMENSION), - static_cast(SHARED_TEXTURE_DIMENSION), 0.0f); + glProgramUniform3f(gl_data->program, 0, static_cast(SHARED_TEXTURE_DIMENSION), static_cast(SHARED_TEXTURE_DIMENSION), 0.0f); glViewport(0, 0, SHARED_TEXTURE_DIMENSION, SHARED_TEXTURE_DIMENSION); @@ -677,8 +587,7 @@ void OpenGLInterop::view_changed() void OpenGLInterop::on_update_ui_overlay(vkb::Drawer &drawer) { if (drawer.header("Settings")) - { - } + {} } void OpenGLInterop::build_command_buffers() @@ -705,26 +614,23 @@ void OpenGLInterop::build_command_buffers() VK_CHECK(vkBeginCommandBuffer(draw_cmd_buffers[i], &command_buffer_begin_info)); - vkb::image_layout_transition(draw_cmd_buffers[i], sharedTexture.image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + vkb::image_layout_transition(draw_cmd_buffers[i], sharedTexture.image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - vkCmdBeginRenderPass(draw_cmd_buffers[i], &render_pass_begin_info, - VK_SUBPASS_CONTENTS_INLINE); + vkCmdBeginRenderPass(draw_cmd_buffers[i], &render_pass_begin_info, VK_SUBPASS_CONTENTS_INLINE); - VkViewport viewport = vkb::initializers::viewport(static_cast(width), static_cast(height), 0.0f, - 1.0f); + VkViewport viewport = vkb::initializers::viewport(static_cast(width), static_cast(height), 0.0f, 1.0f); vkCmdSetViewport(draw_cmd_buffers[i], 0, 1, &viewport); VkRect2D scissor = vkb::initializers::rect2D(width, height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layout, 0, 1, &descriptor_set, 0, NULL); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_set, 0, NULL); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(draw_cmd_buffers[i], 0, 1, vertex_buffer->get(), offsets); - vkCmdBindIndexBuffer(draw_cmd_buffers[i], index_buffer->get_handle(), 0, - VK_INDEX_TYPE_UINT32); + vkCmdBindIndexBuffer(draw_cmd_buffers[i], index_buffer->get_handle(), 0, VK_INDEX_TYPE_UINT32); vkCmdDrawIndexed(draw_cmd_buffers[i], index_count, 1, 0, 0, 0); @@ -732,7 +638,8 @@ void OpenGLInterop::build_command_buffers() vkCmdEndRenderPass(draw_cmd_buffers[i]); - vkb::image_layout_transition(draw_cmd_buffers[i], sharedTexture.image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); + vkb::image_layout_transition(draw_cmd_buffers[i], sharedTexture.image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); VK_CHECK(vkEndCommandBuffer(draw_cmd_buffers[i])); } diff --git a/samples/extensions/open_gl_interop/third_party/glad/include/KHR/khrplatform.h b/samples/extensions/open_gl_interop/third_party/glad/include/KHR/khrplatform.h index dc82c3a94a..7424418e74 100644 --- a/samples/extensions/open_gl_interop/third_party/glad/include/KHR/khrplatform.h +++ b/samples/extensions/open_gl_interop/third_party/glad/include/KHR/khrplatform.h @@ -101,7 +101,7 @@ */ #if defined(KHRONOS_STATIC) /* If the preprocessor constant KHRONOS_STATIC is defined, make the - * header compatible with static linking. */ + * header compatible with static linking. */ # define KHRONOS_APICALL #elif defined(_WIN32) # define KHRONOS_APICALL __declspec(dllimport) diff --git a/samples/extensions/open_gl_interop/third_party/glad/include/glad/glad.h b/samples/extensions/open_gl_interop/third_party/glad/include/glad/glad.h index 4bc94f33ee..356702ac2f 100644 --- a/samples/extensions/open_gl_interop/third_party/glad/include/glad/glad.h +++ b/samples/extensions/open_gl_interop/third_party/glad/include/glad/glad.h @@ -20,7 +20,8 @@ Reproducible: False Commandline: - --profile="core" --api="gl=4.5,gles2=3.2" --generator="c" --spec="gl" --extensions="GL_EXT_memory_object,GL_EXT_memory_object_fd,GL_EXT_memory_object_win32,GL_EXT_semaphore,GL_EXT_semaphore_fd,GL_EXT_semaphore_win32,GL_KHR_debug" + --profile="core" --api="gl=4.5,gles2=3.2" --generator="c" --spec="gl" + --extensions="GL_EXT_memory_object,GL_EXT_memory_object_fd,GL_EXT_memory_object_win32,GL_EXT_semaphore,GL_EXT_semaphore_fd,GL_EXT_semaphore_win32,GL_KHR_debug" Online: https://glad.dav1d.de/#profile=core&language=c&specification=gl&loader=on&api=gl%3D4.5&api=gles2%3D3.2&extensions=GL_EXT_memory_object&extensions=GL_EXT_memory_object_fd&extensions=GL_EXT_memory_object_win32&extensions=GL_EXT_semaphore&extensions=GL_EXT_semaphore_fd&extensions=GL_EXT_semaphore_win32&extensions=GL_KHR_debug */ @@ -122,8 +123,8 @@ extern "C" typedef khronos_float_t GLclampf; typedef double GLdouble; typedef double GLclampd; - typedef void * GLeglClientBufferEXT; - typedef void * GLeglImageOES; + typedef void *GLeglClientBufferEXT; + typedef void *GLeglImageOES; typedef char GLchar; typedef char GLcharARB; #ifdef __APPLE__ @@ -146,8 +147,10 @@ typedef unsigned int GLhandleARB; struct _cl_context; struct _cl_event; typedef void(APIENTRY *GLDEBUGPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); - typedef void(APIENTRY *GLDEBUGPROCARB)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); - typedef void(APIENTRY *GLDEBUGPROCKHR)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); + typedef void(APIENTRY *GLDEBUGPROCARB)( + GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); + typedef void(APIENTRY *GLDEBUGPROCKHR)( + GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); typedef void(APIENTRY *GLDEBUGPROCAMD)(GLuint id, GLenum category, GLenum severity, GLsizei length, const GLchar *message, void *userParam); typedef unsigned short GLhalfNV; typedef GLintptr GLvdpauSurfaceNV; @@ -1603,10 +1606,12 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint *params); GLAPI PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; # define glTexParameteriv glad_glTexParameteriv - typedef void(APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); + typedef void(APIENTRYP PFNGLTEXIMAGE1DPROC)( + GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXIMAGE1DPROC glad_glTexImage1D; # define glTexImage1D glad_glTexImage1D - typedef void(APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); + typedef void(APIENTRYP PFNGLTEXIMAGE2DPROC)( + GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXIMAGE2DPROC glad_glTexImage2D; # define glTexImage2D glad_glTexImage2D typedef void(APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum buf); @@ -1730,19 +1735,22 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); GLAPI PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; # define glCopyTexImage1D glad_glCopyTexImage1D - typedef void(APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); + typedef void(APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)( + GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); GLAPI PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; # define glCopyTexImage2D glad_glCopyTexImage2D typedef void(APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); GLAPI PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; # define glCopyTexSubImage1D glad_glCopyTexSubImage1D - typedef void(APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); + typedef void(APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; # define glCopyTexSubImage2D glad_glCopyTexSubImage2D typedef void(APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; # define glTexSubImage1D glad_glTexSubImage1D - typedef void(APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); + typedef void(APIENTRYP PFNGLTEXSUBIMAGE2DPROC)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; # define glTexSubImage2D glad_glTexSubImage2D typedef void(APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); @@ -1764,13 +1772,33 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); GLAPI PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; # define glDrawRangeElements glad_glDrawRangeElements - typedef void(APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); + typedef void(APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border, + GLenum format, + GLenum type, + const void *pixels); GLAPI PFNGLTEXIMAGE3DPROC glad_glTexImage3D; # define glTexImage3D glad_glTexImage3D - typedef void(APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); + typedef void(APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + const void *pixels); GLAPI PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; # define glTexSubImage3D glad_glTexSubImage3D - typedef void(APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); + typedef void(APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; # define glCopyTexSubImage3D glad_glCopyTexSubImage3D #endif @@ -1783,22 +1811,37 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); GLAPI PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; # define glSampleCoverage glad_glSampleCoverage - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)( + GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; # define glCompressedTexImage3D glad_glCompressedTexImage3D - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)( + GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; # define glCompressedTexImage2D glad_glCompressedTexImage2D - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)( + GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; # define glCompressedTexImage1D glad_glCompressedTexImage1D - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLsizei imageSize, + const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; # define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)( + GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; # define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)( + GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; # define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D typedef void(APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void *img); @@ -2238,7 +2281,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC)(GLuint program, GLsizei count, const GLchar *const *varyings, GLenum bufferMode); GLAPI PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; # define glTransformFeedbackVaryings glad_glTransformFeedbackVaryings - typedef void(APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); + typedef void(APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)( + GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); GLAPI PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; # define glGetTransformFeedbackVarying glad_glGetTransformFeedbackVarying typedef void(APIENTRYP PFNGLCLAMPCOLORPROC)(GLenum target, GLenum clamp); @@ -2430,7 +2474,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLGENERATEMIPMAPPROC)(GLenum target); GLAPI PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; # define glGenerateMipmap glad_glGenerateMipmap - typedef void(APIENTRYP PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); + typedef void(APIENTRYP PFNGLBLITFRAMEBUFFERPROC)( + GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); GLAPI PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; # define glBlitFramebuffer glad_glBlitFramebuffer typedef void(APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); @@ -2491,7 +2536,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); GLAPI PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; # define glGetActiveUniformBlockiv glad_glGetActiveUniformBlockiv - typedef void(APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); + typedef void(APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)( + GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); GLAPI PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; # define glGetActiveUniformBlockName glad_glGetActiveUniformBlockName typedef void(APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); @@ -2504,13 +2550,16 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); GLAPI PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; # define glDrawElementsBaseVertex glad_glDrawElementsBaseVertex - typedef void(APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); + typedef void(APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)( + GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); GLAPI PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; # define glDrawRangeElementsBaseVertex glad_glDrawRangeElementsBaseVertex - typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); + typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)( + GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; # define glDrawElementsInstancedBaseVertex glad_glDrawElementsInstancedBaseVertex - typedef void(APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const *indices, GLsizei drawcount, const GLint *basevertex); + typedef void(APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)( + GLenum mode, const GLsizei *count, GLenum type, const void *const *indices, GLsizei drawcount, const GLint *basevertex); GLAPI PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; # define glMultiDrawElementsBaseVertex glad_glMultiDrawElementsBaseVertex typedef void(APIENTRYP PFNGLPROVOKINGVERTEXPROC)(GLenum mode); @@ -2546,10 +2595,12 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level); GLAPI PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; # define glFramebufferTexture glad_glFramebufferTexture - typedef void(APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); + typedef void(APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC)( + GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; # define glTexImage2DMultisample glad_glTexImage2DMultisample - typedef void(APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); + typedef void(APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC)( + GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; # define glTexImage3DMultisample glad_glTexImage3DMultisample typedef void(APIENTRYP PFNGLGETMULTISAMPLEFVPROC)(GLenum pname, GLuint index, GLfloat *val); @@ -2824,7 +2875,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)(GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); GLAPI PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glad_glGetActiveSubroutineUniformiv; # define glGetActiveSubroutineUniformiv glad_glGetActiveSubroutineUniformiv - typedef void(APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); + typedef void(APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)( + GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); GLAPI PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glad_glGetActiveSubroutineUniformName; # define glGetActiveSubroutineUniformName glad_glGetActiveSubroutineUniformName typedef void(APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); @@ -3153,10 +3205,12 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); GLAPI PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC glad_glDrawArraysInstancedBaseInstance; # define glDrawArraysInstancedBaseInstance glad_glDrawArraysInstancedBaseInstance - typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); + typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)( + GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC glad_glDrawElementsInstancedBaseInstance; # define glDrawElementsInstancedBaseInstance glad_glDrawElementsInstancedBaseInstance - typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); + typedef void(APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)( + GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC glad_glDrawElementsInstancedBaseVertexBaseInstance; # define glDrawElementsInstancedBaseVertexBaseInstance glad_glDrawElementsInstancedBaseVertexBaseInstance typedef void(APIENTRYP PFNGLGETINTERNALFORMATIVPROC)(GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint *params); @@ -3193,7 +3247,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLCLEARBUFFERDATAPROC)(GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARBUFFERDATAPROC glad_glClearBufferData; # define glClearBufferData glad_glClearBufferData - typedef void(APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC)(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); + typedef void(APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC)( + GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARBUFFERSUBDATAPROC glad_glClearBufferSubData; # define glClearBufferSubData glad_glClearBufferSubData typedef void(APIENTRYP PFNGLDISPATCHCOMPUTEPROC)(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); @@ -3202,7 +3257,21 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC)(GLintptr indirect); GLAPI PFNGLDISPATCHCOMPUTEINDIRECTPROC glad_glDispatchComputeIndirect; # define glDispatchComputeIndirect glad_glDispatchComputeIndirect - typedef void(APIENTRYP PFNGLCOPYIMAGESUBDATAPROC)(GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); + typedef void(APIENTRYP PFNGLCOPYIMAGESUBDATAPROC)(GLuint srcName, + GLenum srcTarget, + GLint srcLevel, + GLint srcX, + GLint srcY, + GLint srcZ, + GLuint dstName, + GLenum dstTarget, + GLint dstLevel, + GLint dstX, + GLint dstY, + GLint dstZ, + GLsizei srcWidth, + GLsizei srcHeight, + GLsizei srcDepth); GLAPI PFNGLCOPYIMAGESUBDATAPROC glad_glCopyImageSubData; # define glCopyImageSubData glad_glCopyImageSubData typedef void(APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); @@ -3214,7 +3283,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLGETINTERNALFORMATI64VPROC)(GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint64 *params); GLAPI PFNGLGETINTERNALFORMATI64VPROC glad_glGetInternalformati64v; # define glGetInternalformati64v glad_glGetInternalformati64v - typedef void(APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); + typedef void(APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC)( + GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); GLAPI PFNGLINVALIDATETEXSUBIMAGEPROC glad_glInvalidateTexSubImage; # define glInvalidateTexSubImage glad_glInvalidateTexSubImage typedef void(APIENTRYP PFNGLINVALIDATETEXIMAGEPROC)(GLuint texture, GLint level); @@ -3229,7 +3299,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC)(GLenum target, GLsizei numAttachments, const GLenum *attachments); GLAPI PFNGLINVALIDATEFRAMEBUFFERPROC glad_glInvalidateFramebuffer; # define glInvalidateFramebuffer glad_glInvalidateFramebuffer - typedef void(APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC)(GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); + typedef void(APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC)( + GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLINVALIDATESUBFRAMEBUFFERPROC glad_glInvalidateSubFramebuffer; # define glInvalidateSubFramebuffer glad_glInvalidateSubFramebuffer typedef void(APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC)(GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); @@ -3244,10 +3315,12 @@ typedef unsigned int GLhandleARB; typedef GLuint(APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC)(GLuint program, GLenum programInterface, const GLchar *name); GLAPI PFNGLGETPROGRAMRESOURCEINDEXPROC glad_glGetProgramResourceIndex; # define glGetProgramResourceIndex glad_glGetProgramResourceIndex - typedef void(APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC)(GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); + typedef void(APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC)( + GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); GLAPI PFNGLGETPROGRAMRESOURCENAMEPROC glad_glGetProgramResourceName; # define glGetProgramResourceName glad_glGetProgramResourceName - typedef void(APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC)(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLint *params); + typedef void(APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC)( + GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLint *params); GLAPI PFNGLGETPROGRAMRESOURCEIVPROC glad_glGetProgramResourceiv; # define glGetProgramResourceiv glad_glGetProgramResourceiv typedef GLint(APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC)(GLuint program, GLenum programInterface, const GLchar *name); @@ -3262,13 +3335,16 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLTEXBUFFERRANGEPROC)(GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); GLAPI PFNGLTEXBUFFERRANGEPROC glad_glTexBufferRange; # define glTexBufferRange glad_glTexBufferRange - typedef void(APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); + typedef void(APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC)( + GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI PFNGLTEXSTORAGE2DMULTISAMPLEPROC glad_glTexStorage2DMultisample; # define glTexStorage2DMultisample glad_glTexStorage2DMultisample - typedef void(APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); + typedef void(APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC)( + GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI PFNGLTEXSTORAGE3DMULTISAMPLEPROC glad_glTexStorage3DMultisample; # define glTexStorage3DMultisample glad_glTexStorage3DMultisample - typedef void(APIENTRYP PFNGLTEXTUREVIEWPROC)(GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); + typedef void(APIENTRYP PFNGLTEXTUREVIEWPROC)( + GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); GLAPI PFNGLTEXTUREVIEWPROC glad_glTextureView; # define glTextureView glad_glTextureView typedef void(APIENTRYP PFNGLBINDVERTEXBUFFERPROC)(GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); @@ -3298,7 +3374,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC)(GLDEBUGPROC callback, const void *userParam); GLAPI PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback; # define glDebugMessageCallback glad_glDebugMessageCallback - typedef GLuint(APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC)(GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); + typedef GLuint(APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC)( + GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); GLAPI PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog; # define glGetDebugMessageLog glad_glGetDebugMessageLog typedef void(APIENTRYP PFNGLPUSHDEBUGGROUPPROC)(GLenum source, GLuint id, GLsizei length, const GLchar *message); @@ -3332,13 +3409,24 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLCLEARTEXIMAGEPROC)(GLuint texture, GLint level, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARTEXIMAGEPROC glad_glClearTexImage; # define glClearTexImage glad_glClearTexImage - typedef void(APIENTRYP PFNGLCLEARTEXSUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); + typedef void(APIENTRYP PFNGLCLEARTEXSUBIMAGEPROC)(GLuint texture, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + const void *data); GLAPI PFNGLCLEARTEXSUBIMAGEPROC glad_glClearTexSubImage; # define glClearTexSubImage glad_glClearTexSubImage typedef void(APIENTRYP PFNGLBINDBUFFERSBASEPROC)(GLenum target, GLuint first, GLsizei count, const GLuint *buffers); GLAPI PFNGLBINDBUFFERSBASEPROC glad_glBindBuffersBase; # define glBindBuffersBase glad_glBindBuffersBase - typedef void(APIENTRYP PFNGLBINDBUFFERSRANGEPROC)(GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); + typedef void(APIENTRYP PFNGLBINDBUFFERSRANGEPROC)( + GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); GLAPI PFNGLBINDBUFFERSRANGEPROC glad_glBindBuffersRange; # define glBindBuffersRange glad_glBindBuffersRange typedef void(APIENTRYP PFNGLBINDTEXTURESPROC)(GLuint first, GLsizei count, const GLuint *textures); @@ -3396,7 +3484,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLCLEARNAMEDBUFFERDATAPROC)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARNAMEDBUFFERDATAPROC glad_glClearNamedBufferData; # define glClearNamedBufferData glad_glClearNamedBufferData - typedef void(APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAPROC)(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); + typedef void(APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAPROC)( + GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); GLAPI PFNGLCLEARNAMEDBUFFERSUBDATAPROC glad_glClearNamedBufferSubData; # define glClearNamedBufferSubData glad_glClearNamedBufferSubData typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERPROC)(GLuint buffer, GLenum access); @@ -3450,7 +3539,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC)(GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); GLAPI PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC glad_glInvalidateNamedFramebufferData; # define glInvalidateNamedFramebufferData glad_glInvalidateNamedFramebufferData - typedef void(APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC)(GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); + typedef void(APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC)( + GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC glad_glInvalidateNamedFramebufferSubData; # define glInvalidateNamedFramebufferSubData glad_glInvalidateNamedFramebufferSubData typedef void(APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERIVPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); @@ -3465,7 +3555,18 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFIPROC)(GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); GLAPI PFNGLCLEARNAMEDFRAMEBUFFERFIPROC glad_glClearNamedFramebufferfi; # define glClearNamedFramebufferfi glad_glClearNamedFramebufferfi - typedef void(APIENTRYP PFNGLBLITNAMEDFRAMEBUFFERPROC)(GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); + typedef void(APIENTRYP PFNGLBLITNAMEDFRAMEBUFFERPROC)(GLuint readFramebuffer, + GLuint drawFramebuffer, + GLint srcX0, + GLint srcY0, + GLint srcX1, + GLint srcY1, + GLint dstX0, + GLint dstY0, + GLint dstX1, + GLint dstY1, + GLbitfield mask, + GLenum filter); GLAPI PFNGLBLITNAMEDFRAMEBUFFERPROC glad_glBlitNamedFramebuffer; # define glBlitNamedFramebuffer glad_glBlitNamedFramebuffer typedef GLenum(APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC)(GLuint framebuffer, GLenum target); @@ -3483,7 +3584,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEPROC)(GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLNAMEDRENDERBUFFERSTORAGEPROC glad_glNamedRenderbufferStorage; # define glNamedRenderbufferStorage glad_glNamedRenderbufferStorage - typedef void(APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); + typedef void(APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC)( + GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glNamedRenderbufferStorageMultisample; # define glNamedRenderbufferStorageMultisample glad_glNamedRenderbufferStorageMultisample typedef void(APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC)(GLuint renderbuffer, GLenum pname, GLint *params); @@ -3507,37 +3609,65 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLTEXTURESTORAGE3DPROC)(GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); GLAPI PFNGLTEXTURESTORAGE3DPROC glad_glTextureStorage3D; # define glTextureStorage3D glad_glTextureStorage3D - typedef void(APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC)(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); + typedef void(APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC)( + GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC glad_glTextureStorage2DMultisample; # define glTextureStorage2DMultisample glad_glTextureStorage2DMultisample - typedef void(APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC)(GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); + typedef void(APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC)( + GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC glad_glTextureStorage3DMultisample; # define glTextureStorage3DMultisample glad_glTextureStorage3DMultisample - typedef void(APIENTRYP PFNGLTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); + typedef void(APIENTRYP PFNGLTEXTURESUBIMAGE1DPROC)( + GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXTURESUBIMAGE1DPROC glad_glTextureSubImage1D; # define glTextureSubImage1D glad_glTextureSubImage1D - typedef void(APIENTRYP PFNGLTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); + typedef void(APIENTRYP PFNGLTEXTURESUBIMAGE2DPROC)( + GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXTURESUBIMAGE2DPROC glad_glTextureSubImage2D; # define glTextureSubImage2D glad_glTextureSubImage2D - typedef void(APIENTRYP PFNGLTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); + typedef void(APIENTRYP PFNGLTEXTURESUBIMAGE3DPROC)(GLuint texture, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + const void *pixels); GLAPI PFNGLTEXTURESUBIMAGE3DPROC glad_glTextureSubImage3D; # define glTextureSubImage3D glad_glTextureSubImage3D - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC)( + GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC glad_glCompressedTextureSubImage1D; # define glCompressedTextureSubImage1D glad_glCompressedTextureSubImage1D - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC)( + GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC glad_glCompressedTextureSubImage2D; # define glCompressedTextureSubImage2D glad_glCompressedTextureSubImage2D - typedef void(APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); + typedef void(APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC)(GLuint texture, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLsizei imageSize, + const void *data); GLAPI PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC glad_glCompressedTextureSubImage3D; # define glCompressedTextureSubImage3D glad_glCompressedTextureSubImage3D typedef void(APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DPROC)(GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); GLAPI PFNGLCOPYTEXTURESUBIMAGE1DPROC glad_glCopyTextureSubImage1D; # define glCopyTextureSubImage1D glad_glCopyTextureSubImage1D - typedef void(APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); + typedef void(APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DPROC)( + GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXTURESUBIMAGE2DPROC glad_glCopyTextureSubImage2D; # define glCopyTextureSubImage2D glad_glCopyTextureSubImage2D - typedef void(APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); + typedef void(APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DPROC)( + GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXTURESUBIMAGE3DPROC glad_glCopyTextureSubImage3D; # define glCopyTextureSubImage3D glad_glCopyTextureSubImage3D typedef void(APIENTRYP PFNGLTEXTUREPARAMETERFPROC)(GLuint texture, GLenum pname, GLfloat param); @@ -3603,13 +3733,15 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERPROC)(GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); GLAPI PFNGLVERTEXARRAYVERTEXBUFFERPROC glad_glVertexArrayVertexBuffer; # define glVertexArrayVertexBuffer glad_glVertexArrayVertexBuffer - typedef void(APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERSPROC)(GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); + typedef void(APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERSPROC)( + GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); GLAPI PFNGLVERTEXARRAYVERTEXBUFFERSPROC glad_glVertexArrayVertexBuffers; # define glVertexArrayVertexBuffers glad_glVertexArrayVertexBuffers typedef void(APIENTRYP PFNGLVERTEXARRAYATTRIBBINDINGPROC)(GLuint vaobj, GLuint attribindex, GLuint bindingindex); GLAPI PFNGLVERTEXARRAYATTRIBBINDINGPROC glad_glVertexArrayAttribBinding; # define glVertexArrayAttribBinding glad_glVertexArrayAttribBinding - typedef void(APIENTRYP PFNGLVERTEXARRAYATTRIBFORMATPROC)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); + typedef void(APIENTRYP PFNGLVERTEXARRAYATTRIBFORMATPROC)( + GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); GLAPI PFNGLVERTEXARRAYATTRIBFORMATPROC glad_glVertexArrayAttribFormat; # define glVertexArrayAttribFormat glad_glVertexArrayAttribFormat typedef void(APIENTRYP PFNGLVERTEXARRAYATTRIBIFORMATPROC)(GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); @@ -3654,10 +3786,22 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLMEMORYBARRIERBYREGIONPROC)(GLbitfield barriers); GLAPI PFNGLMEMORYBARRIERBYREGIONPROC glad_glMemoryBarrierByRegion; # define glMemoryBarrierByRegion glad_glMemoryBarrierByRegion - typedef void(APIENTRYP PFNGLGETTEXTURESUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); + typedef void(APIENTRYP PFNGLGETTEXTURESUBIMAGEPROC)(GLuint texture, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + GLsizei bufSize, + void *pixels); GLAPI PFNGLGETTEXTURESUBIMAGEPROC glad_glGetTextureSubImage; # define glGetTextureSubImage glad_glGetTextureSubImage - typedef void(APIENTRYP PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC)(GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); + typedef void(APIENTRYP PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC)( + GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); GLAPI PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC glad_glGetCompressedTextureSubImage; # define glGetCompressedTextureSubImage glad_glGetCompressedTextureSubImage typedef GLenum(APIENTRYP PFNGLGETGRAPHICSRESETSTATUSPROC)(void); @@ -3711,7 +3855,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLGETNCONVOLUTIONFILTERPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); GLAPI PFNGLGETNCONVOLUTIONFILTERPROC glad_glGetnConvolutionFilter; # define glGetnConvolutionFilter glad_glGetnConvolutionFilter - typedef void(APIENTRYP PFNGLGETNSEPARABLEFILTERPROC)(GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); + typedef void(APIENTRYP PFNGLGETNSEPARABLEFILTERPROC)( + GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); GLAPI PFNGLGETNSEPARABLEFILTERPROC glad_glGetnSeparableFilter; # define glGetnSeparableFilter glad_glGetnSeparableFilter typedef void(APIENTRYP PFNGLGETNHISTOGRAMPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); @@ -3742,7 +3887,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLBLENDBARRIERPROC)(void); GLAPI PFNGLBLENDBARRIERPROC glad_glBlendBarrier; # define glBlendBarrier glad_glBlendBarrier - typedef void(APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXPROC)(GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); + typedef void(APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXPROC)( + GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); GLAPI PFNGLPRIMITIVEBOUNDINGBOXPROC glad_glPrimitiveBoundingBox; # define glPrimitiveBoundingBox glad_glPrimitiveBoundingBox #endif @@ -3842,31 +3988,53 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLGETMEMORYOBJECTPARAMETERIVEXTPROC)(GLuint memoryObject, GLenum pname, GLint *params); GLAPI PFNGLGETMEMORYOBJECTPARAMETERIVEXTPROC glad_glGetMemoryObjectParameterivEXT; # define glGetMemoryObjectParameterivEXT glad_glGetMemoryObjectParameterivEXT - typedef void(APIENTRYP PFNGLTEXSTORAGEMEM2DEXTPROC)(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXSTORAGEMEM2DEXTPROC)( + GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); GLAPI PFNGLTEXSTORAGEMEM2DEXTPROC glad_glTexStorageMem2DEXT; # define glTexStorageMem2DEXT glad_glTexStorageMem2DEXT - typedef void(APIENTRYP PFNGLTEXSTORAGEMEM2DMULTISAMPLEEXTPROC)(GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXSTORAGEMEM2DMULTISAMPLEEXTPROC)( + GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); GLAPI PFNGLTEXSTORAGEMEM2DMULTISAMPLEEXTPROC glad_glTexStorageMem2DMultisampleEXT; # define glTexStorageMem2DMultisampleEXT glad_glTexStorageMem2DMultisampleEXT - typedef void(APIENTRYP PFNGLTEXSTORAGEMEM3DEXTPROC)(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXSTORAGEMEM3DEXTPROC)( + GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); GLAPI PFNGLTEXSTORAGEMEM3DEXTPROC glad_glTexStorageMem3DEXT; # define glTexStorageMem3DEXT glad_glTexStorageMem3DEXT - typedef void(APIENTRYP PFNGLTEXSTORAGEMEM3DMULTISAMPLEEXTPROC)(GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXSTORAGEMEM3DMULTISAMPLEEXTPROC)(GLenum target, + GLsizei samples, + GLenum internalFormat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLboolean fixedSampleLocations, + GLuint memory, + GLuint64 offset); GLAPI PFNGLTEXSTORAGEMEM3DMULTISAMPLEEXTPROC glad_glTexStorageMem3DMultisampleEXT; # define glTexStorageMem3DMultisampleEXT glad_glTexStorageMem3DMultisampleEXT typedef void(APIENTRYP PFNGLBUFFERSTORAGEMEMEXTPROC)(GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset); GLAPI PFNGLBUFFERSTORAGEMEMEXTPROC glad_glBufferStorageMemEXT; # define glBufferStorageMemEXT glad_glBufferStorageMemEXT - typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM2DEXTPROC)(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM2DEXTPROC)( + GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); GLAPI PFNGLTEXTURESTORAGEMEM2DEXTPROC glad_glTextureStorageMem2DEXT; # define glTextureStorageMem2DEXT glad_glTextureStorageMem2DEXT - typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM2DMULTISAMPLEEXTPROC)(GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM2DMULTISAMPLEEXTPROC)( + GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); GLAPI PFNGLTEXTURESTORAGEMEM2DMULTISAMPLEEXTPROC glad_glTextureStorageMem2DMultisampleEXT; # define glTextureStorageMem2DMultisampleEXT glad_glTextureStorageMem2DMultisampleEXT - typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM3DEXTPROC)(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM3DEXTPROC)( + GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); GLAPI PFNGLTEXTURESTORAGEMEM3DEXTPROC glad_glTextureStorageMem3DEXT; # define glTextureStorageMem3DEXT glad_glTextureStorageMem3DEXT - typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM3DMULTISAMPLEEXTPROC)(GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM3DMULTISAMPLEEXTPROC)(GLuint texture, + GLsizei samples, + GLenum internalFormat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLboolean fixedSampleLocations, + GLuint memory, + GLuint64 offset); GLAPI PFNGLTEXTURESTORAGEMEM3DMULTISAMPLEEXTPROC glad_glTextureStorageMem3DMultisampleEXT; # define glTextureStorageMem3DMultisampleEXT glad_glTextureStorageMem3DMultisampleEXT typedef void(APIENTRYP PFNGLNAMEDBUFFERSTORAGEMEMEXTPROC)(GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset); @@ -3875,7 +4043,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLTEXSTORAGEMEM1DEXTPROC)(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); GLAPI PFNGLTEXSTORAGEMEM1DEXTPROC glad_glTexStorageMem1DEXT; # define glTexStorageMem1DEXT glad_glTexStorageMem1DEXT - typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM1DEXTPROC)(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); + typedef void(APIENTRYP PFNGLTEXTURESTORAGEMEM1DEXTPROC)( + GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); GLAPI PFNGLTEXTURESTORAGEMEM1DEXTPROC glad_glTextureStorageMem1DEXT; # define glTextureStorageMem1DEXT glad_glTextureStorageMem1DEXT #endif @@ -3914,10 +4083,12 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLGETSEMAPHOREPARAMETERUI64VEXTPROC)(GLuint semaphore, GLenum pname, GLuint64 *params); GLAPI PFNGLGETSEMAPHOREPARAMETERUI64VEXTPROC glad_glGetSemaphoreParameterui64vEXT; # define glGetSemaphoreParameterui64vEXT glad_glGetSemaphoreParameterui64vEXT - typedef void(APIENTRYP PFNGLWAITSEMAPHOREEXTPROC)(GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts); + typedef void(APIENTRYP PFNGLWAITSEMAPHOREEXTPROC)( + GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts); GLAPI PFNGLWAITSEMAPHOREEXTPROC glad_glWaitSemaphoreEXT; # define glWaitSemaphoreEXT glad_glWaitSemaphoreEXT - typedef void(APIENTRYP PFNGLSIGNALSEMAPHOREEXTPROC)(GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts); + typedef void(APIENTRYP PFNGLSIGNALSEMAPHOREEXTPROC)( + GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts); GLAPI PFNGLSIGNALSEMAPHOREEXTPROC glad_glSignalSemaphoreEXT; # define glSignalSemaphoreEXT glad_glSignalSemaphoreEXT #endif @@ -3950,7 +4121,8 @@ typedef unsigned int GLhandleARB; typedef void(APIENTRYP PFNGLDEBUGMESSAGECALLBACKKHRPROC)(GLDEBUGPROCKHR callback, const void *userParam); GLAPI PFNGLDEBUGMESSAGECALLBACKKHRPROC glad_glDebugMessageCallbackKHR; # define glDebugMessageCallbackKHR glad_glDebugMessageCallbackKHR - typedef GLuint(APIENTRYP PFNGLGETDEBUGMESSAGELOGKHRPROC)(GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); + typedef GLuint(APIENTRYP PFNGLGETDEBUGMESSAGELOGKHRPROC)( + GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); GLAPI PFNGLGETDEBUGMESSAGELOGKHRPROC glad_glGetDebugMessageLogKHR; # define glGetDebugMessageLogKHR glad_glGetDebugMessageLogKHR typedef void(APIENTRYP PFNGLPUSHDEBUGGROUPKHRPROC)(GLenum source, GLuint id, GLsizei length, const GLchar *message); diff --git a/samples/extensions/patch_control_points/patch_control_points.cpp b/samples/extensions/patch_control_points/patch_control_points.cpp index b3e9b1a019..6646f9756d 100644 --- a/samples/extensions/patch_control_points/patch_control_points.cpp +++ b/samples/extensions/patch_control_points/patch_control_points.cpp @@ -117,18 +117,12 @@ void PatchControlPoints::render(float delta_time) */ void PatchControlPoints::prepare_uniform_buffers() { - uniform_buffers.common = std::make_unique(get_device(), - sizeof(ubo_common), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); - uniform_buffers.dynamic_tessellation = std::make_unique(get_device(), - sizeof(ubo_tess), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); - uniform_buffers.static_tessellation = std::make_unique(get_device(), - sizeof(ubo_tess), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.common = + std::make_unique(get_device(), sizeof(ubo_common), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.dynamic_tessellation = + std::make_unique(get_device(), sizeof(ubo_tess), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.static_tessellation = + std::make_unique(get_device(), sizeof(ubo_tess), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -166,17 +160,11 @@ void PatchControlPoints::create_pipelines() { /* Setup for pipelines */ VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, /* used in tessellation */ - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, /* used in tessellation */ + 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_FRONT_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_FRONT_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); /* Wireframe mode */ if (get_device().get_gpu().get_features().fillModeNonSolid) @@ -184,10 +172,8 @@ void PatchControlPoints::create_pipelines() rasterization_state.polygonMode = VK_POLYGON_MODE_LINE; } - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, - VK_TRUE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_TRUE); blend_attachment_state.colorBlendOp = VK_BLEND_OP_ADD; blend_attachment_state.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; @@ -196,34 +182,20 @@ void PatchControlPoints::create_pipelines() blend_attachment_state.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; blend_attachment_state.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); /* Note: Using Reversed depth-buffer for increased precision, so Greater depth values are kept */ - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, /* depthTestEnable */ - VK_TRUE, /* depthWriteEnable */ - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, /* depthTestEnable */ + VK_TRUE, /* depthWriteEnable */ + VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); /* Binding description */ std::vector vertex_input_bindings = { @@ -329,44 +301,22 @@ void PatchControlPoints::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(static_cast(width), static_cast(height), 0, 0); vkCmdSetScissor(draw_cmd_buffer, 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffer, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layouts.static_tessellation, - 0, - 1, - &descriptor_sets.static_tessellation, - 0, - nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.static_tessellation, 0, 1, + &descriptor_sets.static_tessellation, 0, nullptr); push_const_block.direction = directions[0]; - vkCmdPushConstants(draw_cmd_buffer, - pipeline_layouts.static_tessellation, - VK_SHADER_STAGE_VERTEX_BIT, - 0, - sizeof(push_const_block), - &push_const_block); + vkCmdPushConstants(draw_cmd_buffer, pipeline_layouts.static_tessellation, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(push_const_block), &push_const_block); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.static_tessellation); draw_model(model, draw_cmd_buffer); // dynamically tessellation - vkCmdBindDescriptorSets(draw_cmd_buffer, - VK_PIPELINE_BIND_POINT_GRAPHICS, - pipeline_layouts.dynamic_tessellation, - 0, - 1, - &descriptor_sets.dynamic_tessellation, - 0, - nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.dynamic_tessellation, 0, 1, + &descriptor_sets.dynamic_tessellation, 0, nullptr); push_const_block.direction = directions[1]; - vkCmdPushConstants(draw_cmd_buffer, - pipeline_layouts.dynamic_tessellation, - VK_SHADER_STAGE_VERTEX_BIT, - 0, - sizeof(push_const_block), - &push_const_block); + vkCmdPushConstants(draw_cmd_buffer, pipeline_layouts.dynamic_tessellation, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(push_const_block), &push_const_block); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.dynamic_tessellation); @@ -394,15 +344,9 @@ void PatchControlPoints::create_descriptor_pool() }; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); - - VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), - &descriptor_pool_create_info, - nullptr, - &descriptor_pool)); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); + + VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } /** @@ -415,66 +359,40 @@ void PatchControlPoints::setup_descriptor_set_layout() std::vector set_layout_bindings = { vkb::initializers::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_VERTEX_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, - 1), + VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, 1), }; VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = - vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), - &descriptor_layout_create_info, - nullptr, - &descriptor_set_layouts.static_tessellation)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.static_tessellation)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.static_tessellation, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.static_tessellation, 1); /* Pass scene node information via push constants */ - VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT, - sizeof(push_const_block), - 0); + VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT, sizeof(push_const_block), 0); pipeline_layout_create_info.pushConstantRangeCount = 1; pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; - VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), - &pipeline_layout_create_info, - nullptr, - &pipeline_layouts.static_tessellation)); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.static_tessellation)); /* Second descriptor set */ set_layout_bindings = { vkb::initializers::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_VERTEX_BIT, - 0), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, - 1), + VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, 1), }; descriptor_layout_create_info.pBindings = set_layout_bindings.data(); descriptor_layout_create_info.bindingCount = static_cast(set_layout_bindings.size()); - VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), - &descriptor_layout_create_info, - nullptr, - &descriptor_set_layouts.dynamic_tessellation)); + VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.dynamic_tessellation)); pipeline_layout_create_info.pSetLayouts = &descriptor_set_layouts.dynamic_tessellation; - VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), - &pipeline_layout_create_info, - nullptr, - &pipeline_layouts.dynamic_tessellation)); + VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layouts.dynamic_tessellation)); } /** @@ -484,62 +402,31 @@ void PatchControlPoints::setup_descriptor_set_layout() void PatchControlPoints::create_descriptor_sets() { /* First descriptor set */ - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.static_tessellation, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.static_tessellation, 1); - VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), - &alloc_info, - &descriptor_sets.static_tessellation)); + VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.static_tessellation)); VkDescriptorBufferInfo matrix_common_buffer_descriptor = create_descriptor(*uniform_buffers.common); VkDescriptorBufferInfo matrix_tess_buffer_descriptor = create_descriptor(*uniform_buffers.static_tessellation); std::vector write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - descriptor_sets.static_tessellation, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &matrix_common_buffer_descriptor), - vkb::initializers::write_descriptor_set( - descriptor_sets.static_tessellation, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 1, - &matrix_tess_buffer_descriptor)}; + vkb::initializers::write_descriptor_set(descriptor_sets.static_tessellation, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_common_buffer_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets.static_tessellation, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &matrix_tess_buffer_descriptor)}; - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); /* Second descriptor set */ - alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.dynamic_tessellation, - 1); + alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.dynamic_tessellation, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.dynamic_tessellation)); matrix_tess_buffer_descriptor = create_descriptor(*uniform_buffers.dynamic_tessellation); write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - descriptor_sets.dynamic_tessellation, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &matrix_common_buffer_descriptor), - vkb::initializers::write_descriptor_set( - descriptor_sets.dynamic_tessellation, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 1, - &matrix_tess_buffer_descriptor)}; - - vkUpdateDescriptorSets(get_device().get_handle(), - static_cast(write_descriptor_sets.size()), - write_descriptor_sets.data(), - 0, - VK_NULL_HANDLE); + vkb::initializers::write_descriptor_set(descriptor_sets.dynamic_tessellation, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_common_buffer_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets.dynamic_tessellation, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &matrix_tess_buffer_descriptor)}; + + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); } /** diff --git a/samples/extensions/portability/portability.cpp b/samples/extensions/portability/portability.cpp index abf1e3aecf..373f2d2057 100644 --- a/samples/extensions/portability/portability.cpp +++ b/samples/extensions/portability/portability.cpp @@ -24,13 +24,7 @@ #include "scene_graph/components/sub_mesh.h" -Portability::Portability() : - pipelines(), - pipeline_layouts(), - descriptor_sets(), - descriptor_set_layouts(), - offscreen(), - filter_pass() +Portability::Portability() : pipelines(), pipeline_layouts(), descriptor_sets(), descriptor_set_layouts(), offscreen(), filter_pass() { title = "Portability"; } @@ -130,8 +124,10 @@ void Portability::build_command_buffers() { vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skysphere); push_const_block.object_type = 0; - vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layouts.models, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), &push_const_block); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.models, 0, 1, &descriptor_sets.skysphere, 0, nullptr); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layouts.models, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(push_const_block), &push_const_block); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.models, 0, 1, &descriptor_sets.skysphere, 0, + nullptr); draw_model(models.skysphere, draw_cmd_buffers[i]); } @@ -154,7 +150,8 @@ void Portability::build_command_buffers() push_const_block.object_type = 1; push_const_block.offset = glm::vec4(mesh_offsets[j], 0.0f); push_const_block.color = glm::vec4(mesh_colors[j], 0.0f); - vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layouts.models, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), &push_const_block); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layouts.models, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(push_const_block), &push_const_block); draw_model(models.scene, draw_cmd_buffers[i]); } @@ -187,7 +184,8 @@ void Portability::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(filter_pass.width, filter_pass.height, 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.bloom_filter, 0, 1, &descriptor_sets.bloom_filter, 0, + nullptr); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.bloom[1]); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); @@ -224,7 +222,8 @@ void Portability::build_command_buffers() VkRect2D scissor = vkb::initializers::rect2D(static_cast(width), static_cast(height), 0, 0); vkCmdSetScissor(draw_cmd_buffers[i], 0, 1, &scissor); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layouts.composition, 0, 1, &descriptor_sets.composition, 0, + nullptr); vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.composition); vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); @@ -516,11 +515,10 @@ void Portability::load_assets() void Portability::setup_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; - uint32_t num_descriptor_sets = 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6)}; + uint32_t num_descriptor_sets = 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -539,13 +537,11 @@ void Portability::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.models)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts.models, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.models, 1); // Pass object offset and color via push constant - VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); + VkPushConstantRange push_constant_range = + vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); pipeline_layout_create_info.pushConstantRangeCount = 1; pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; @@ -557,7 +553,8 @@ void Portability::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.bloom_filter)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.bloom_filter, 1); @@ -569,7 +566,8 @@ void Portability::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), }; - descriptor_layout_create_info = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + descriptor_layout_create_info = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts.composition)); pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts.composition, 1); @@ -578,11 +576,7 @@ void Portability::setup_descriptor_set_layout() void Portability::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts.models, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts.models, 1); // Sphere model object descriptor set VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.sphere)); @@ -640,57 +634,28 @@ void Portability::setup_descriptor_sets() void Portability::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layouts.models, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layouts.models, render_pass, 0); std::vector blend_attachment_states = { vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), @@ -801,10 +766,8 @@ void Portability::prepare_pipelines() void Portability::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffers.matrices = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.matrices = + std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } diff --git a/samples/extensions/push_descriptors/push_descriptors.cpp b/samples/extensions/push_descriptors/push_descriptors.cpp index 4ca61681bc..239c4a33d4 100644 --- a/samples/extensions/push_descriptors/push_descriptors.cpp +++ b/samples/extensions/push_descriptors/push_descriptors.cpp @@ -189,26 +189,21 @@ void PushDescriptors::prepare_pipelines() VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); + VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); // Vertex bindings and attributes const std::vector vertex_input_bindings = { @@ -235,9 +230,8 @@ void PushDescriptors::prepare_pipelines() pipeline_create_info.pDepthStencilState = &depth_stencil_state; pipeline_create_info.pDynamicState = &dynamic_state; - const std::array shader_stages = { - load_shader("push_descriptors", "cube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), - load_shader("push_descriptors", "cube.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}; + const std::array shader_stages = {load_shader("push_descriptors", "cube.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), + load_shader("push_descriptors", "cube.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}; pipeline_create_info.stageCount = static_cast(shader_stages.size()); pipeline_create_info.pStages = shader_stages.data(); @@ -248,18 +242,14 @@ void PushDescriptors::prepare_pipelines() void PushDescriptors::prepare_uniform_buffers() { // Vertex shader scene uniform buffer block - uniform_buffers.scene = std::make_unique(get_device(), - sizeof(UboScene), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.scene = + std::make_unique(get_device(), sizeof(UboScene), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); // Vertex shader cube model uniform buffer blocks for (auto &cube : cubes) { - cube.uniform_buffer = std::make_unique(get_device(), - sizeof(glm::mat4), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + cube.uniform_buffer = + std::make_unique(get_device(), sizeof(glm::mat4), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } update_uniform_buffers(); diff --git a/samples/extensions/rasterization_order_attachment_access/rasterization_order_attachment_access.cpp b/samples/extensions/rasterization_order_attachment_access/rasterization_order_attachment_access.cpp index fcd1f700b0..102ee8c158 100644 --- a/samples/extensions/rasterization_order_attachment_access/rasterization_order_attachment_access.cpp +++ b/samples/extensions/rasterization_order_attachment_access/rasterization_order_attachment_access.cpp @@ -92,21 +92,17 @@ void RasterizationOrderAttachmentAccess::load_assets() // Creates uniform buffer for scene data and instance buffer with randomized sphere transforms/colors void RasterizationOrderAttachmentAccess::create_buffers() { - scene_uniform_buffer = std::make_unique( - get_device(), sizeof(SceneUniforms), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + scene_uniform_buffer = + std::make_unique(get_device(), sizeof(SceneUniforms), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); - instance_buffer = std::make_unique( - get_device(), sizeof(InstanceData) * kInstanceCount, - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + instance_buffer = std::make_unique(get_device(), sizeof(InstanceData) * kInstanceCount, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); // Initialize instance data with random colors instances.resize(kInstanceCount); srand(42); - const auto random_float = []() { - return static_cast(rand()) / static_cast(RAND_MAX); - }; + const auto random_float = []() { return static_cast(rand()) / static_cast(RAND_MAX); }; uint32_t idx = 0; for (uint32_t z = 0; z < kInstanceLayerCount; ++z) @@ -115,20 +111,12 @@ void RasterizationOrderAttachmentAccess::create_buffers() { for (uint32_t x = 0; x < kInstanceRowCount; ++x, ++idx) { - const glm::vec3 pos = { - static_cast(x) - (kInstanceRowCount - 1) * 0.5f, - static_cast(y) - (kInstanceColumnCount - 1) * 0.5f, - static_cast(z) - (kInstanceLayerCount - 1) * 0.5f}; - - instances[idx].model = glm::scale( - glm::translate(glm::mat4(1.0f), pos), - glm::vec3(0.03f)); - - instances[idx].color = glm::vec4( - random_float(), - random_float(), - random_float(), - random_float() * 0.8f + 0.2f); + const glm::vec3 pos = {static_cast(x) - (kInstanceRowCount - 1) * 0.5f, static_cast(y) - (kInstanceColumnCount - 1) * 0.5f, + static_cast(z) - (kInstanceLayerCount - 1) * 0.5f}; + + instances[idx].model = glm::scale(glm::translate(glm::mat4(1.0f), pos), glm::vec3(0.03f)); + + instances[idx].color = glm::vec4(random_float(), random_float(), random_float(), random_float() * 0.8f + 0.2f); } } } @@ -153,7 +141,8 @@ void RasterizationOrderAttachmentAccess::create_descriptors() vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, VK_SHADER_STAGE_FRAGMENT_BIT, 3), }; - const VkDescriptorSetLayoutCreateInfo layout_info = vkb::initializers::descriptor_set_layout_create_info(bindings.data(), static_cast(bindings.size())); + const VkDescriptorSetLayoutCreateInfo layout_info = + vkb::initializers::descriptor_set_layout_create_info(bindings.data(), static_cast(bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &descriptor_set_layout)); } @@ -175,7 +164,8 @@ void RasterizationOrderAttachmentAccess::create_descriptors() vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, set_count), vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, set_count), }; - VkDescriptorPoolCreateInfo pool_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), set_count); + VkDescriptorPoolCreateInfo pool_info = + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), set_count); VK_CHECK(vkCreateDescriptorPool(device, &pool_info, nullptr, &descriptor_pool)); // Allocate @@ -222,17 +212,21 @@ void RasterizationOrderAttachmentAccess::create_pipelines() const VkFormat color_format = get_render_context().get_swapchain().get_format(); // Common pipeline state - VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); - const VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - const VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); - const VkPipelineColorBlendAttachmentState blend_attachment = vkb::initializers::pipeline_color_blend_attachment_state(0xF, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment); - const VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - const VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - const VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + VkPipelineVertexInputStateCreateInfo vertex_input_state = vkb::initializers::pipeline_vertex_input_state_create_info(); + const VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + const VkPipelineRasterizationStateCreateInfo rasterization_state = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + const VkPipelineColorBlendAttachmentState blend_attachment = vkb::initializers::pipeline_color_blend_attachment_state(0xF, VK_FALSE); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment); + const VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + const VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + const VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); const std::vector dynamic_states = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - const VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_states.data(), static_cast(dynamic_states.size()), 0); + const VkPipelineDynamicStateCreateInfo dynamic_state = + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_states.data(), static_cast(dynamic_states.size()), 0); std::array shader_stages{}; @@ -260,7 +254,7 @@ void RasterizationOrderAttachmentAccess::create_pipelines() VK_CHECK(vkCreateGraphicsPipelines(device, pipeline_cache, 1, &pipeline_info, nullptr, &background_pipeline)); // Blend pipelines (sphere geometry with local read) - const VkVertexInputBindingDescription vertex_binding = vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX); + const VkVertexInputBindingDescription vertex_binding = vkb::initializers::vertex_input_binding_description(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX); const VkVertexInputAttributeDescription vertex_attribute = vkb::initializers::vertex_input_attribute_description(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0); vertex_input_state.vertexBindingDescriptionCount = 1; @@ -400,12 +394,9 @@ void RasterizationOrderAttachmentAccess::build_command_buffers() } // Transition: UNDEFINED -> RENDERING_LOCAL_READ_KHR (enables framebuffer fetch) - vkb::image_layout_transition( - draw_cmd_buffers[i], swapchain_buffers[i].image, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_RENDERING_LOCAL_READ_KHR, - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); + vkb::image_layout_transition(draw_cmd_buffers[i], swapchain_buffers[i].image, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_RENDERING_LOCAL_READ_KHR, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); // Set up color attachment for dynamic rendering with local read support VkRenderingAttachmentInfoKHR color_attachment = {}; @@ -457,9 +448,10 @@ void RasterizationOrderAttachmentAccess::build_command_buffers() VkDependencyInfoKHR dependency_info = {}; dependency_info.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO_KHR; - dependency_info.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; // BY_REGION makes the barrier tile-local, which is more efficient on tiled GPUs - dependency_info.memoryBarrierCount = 1; - dependency_info.pMemoryBarriers = &memory_barrier; + dependency_info.dependencyFlags = + VK_DEPENDENCY_BY_REGION_BIT; // BY_REGION makes the barrier tile-local, which is more efficient on tiled GPUs + dependency_info.memoryBarrierCount = 1; + dependency_info.pMemoryBarriers = &memory_barrier; vkCmdPipelineBarrier2KHR(draw_cmd_buffers[i], &dependency_info); // ROAA ON: Single instanced draw. Extension guarantees fragment ordering. @@ -497,22 +489,17 @@ void RasterizationOrderAttachmentAccess::build_command_buffers() } // Transition: RENDERING_LOCAL_READ_KHR -> COLOR_ATTACHMENT_OPTIMAL (required for UI rendering) - vkb::image_layout_transition( - draw_cmd_buffers[i], swapchain_buffers[i].image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_RENDERING_LOCAL_READ_KHR, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); + vkb::image_layout_transition(draw_cmd_buffers[i], swapchain_buffers[i].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_RENDERING_LOCAL_READ_KHR, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); draw_ui(draw_cmd_buffers[i], i); // Transition: COLOR_ATTACHMENT_OPTIMAL -> PRESENT_SRC_KHR - vkb::image_layout_transition( - draw_cmd_buffers[i], swapchain_buffers[i].image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, 0, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); + vkb::image_layout_transition(draw_cmd_buffers[i], swapchain_buffers[i].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, 0, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); } VK_CHECK(vkEndCommandBuffer(draw_cmd_buffers[i])); } @@ -549,14 +536,8 @@ void RasterizationOrderAttachmentAccess::retrieve_timestamp_results() // WAIT_BIT blocks until results are available. 64_BIT for full precision timestamps const VkDevice device = get_device().get_handle(); - vkGetQueryPoolResults( - device, - timestamp_query_pool, - 0, 2, - timestamp_results.size() * sizeof(uint64_t), - timestamp_results.data(), - sizeof(uint64_t), - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); + vkGetQueryPoolResults(device, timestamp_query_pool, 0, 2, timestamp_results.size() * sizeof(uint64_t), timestamp_results.data(), sizeof(uint64_t), + VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); // timestampPeriod is nanoseconds per tick, convert delta to milliseconds const VkPhysicalDeviceProperties &properties = get_device().get_gpu().get_properties(); diff --git a/samples/extensions/rasterization_order_attachment_access/rasterization_order_attachment_access.h b/samples/extensions/rasterization_order_attachment_access/rasterization_order_attachment_access.h index ffc1cee3c8..239f0f2354 100644 --- a/samples/extensions/rasterization_order_attachment_access/rasterization_order_attachment_access.h +++ b/samples/extensions/rasterization_order_attachment_access/rasterization_order_attachment_access.h @@ -142,12 +142,7 @@ class RasterizationOrderAttachmentAccess : public ApiVulkanSample // Maps color attachment 0 to input_attachment_index 0 in the fragment shader static constexpr uint32_t COLOR_ATTACHMENT_INPUT_INDEX = 0; static inline const VkRenderingInputAttachmentIndexInfo INPUT_ATTACHMENT_INDEX_INFO{ - VK_STRUCTURE_TYPE_RENDERING_INPUT_ATTACHMENT_INDEX_INFO_KHR, - nullptr, - 1, - &COLOR_ATTACHMENT_INPUT_INDEX, - nullptr, - nullptr}; + VK_STRUCTURE_TYPE_RENDERING_INPUT_ATTACHMENT_INDEX_INFO_KHR, nullptr, 1, &COLOR_ATTACHMENT_INPUT_INDEX, nullptr, nullptr}; // ============================================================================ // Performance measurement diff --git a/samples/extensions/ray_queries/ray_queries.cpp b/samples/extensions/ray_queries/ray_queries.cpp index a727a65732..9b3db5c564 100644 --- a/samples/extensions/ray_queries/ray_queries.cpp +++ b/samples/extensions/ray_queries/ray_queries.cpp @@ -207,10 +207,7 @@ uint64_t RayQueries::get_buffer_device_address(VkBuffer buffer) void RayQueries::create_top_level_acceleration_structure() { - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; VkAccelerationStructureInstanceKHR acceleration_structure_instance{}; acceleration_structure_instance.transform = transform_matrix; @@ -220,10 +217,9 @@ void RayQueries::create_top_level_acceleration_structure() acceleration_structure_instance.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR; acceleration_structure_instance.accelerationStructureReference = bottom_level_acceleration_structure->get_device_address(); - std::unique_ptr instances_buffer = std::make_unique(get_device(), - sizeof(VkAccelerationStructureInstanceKHR), - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr instances_buffer = std::make_unique( + get_device(), sizeof(VkAccelerationStructureInstanceKHR), + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); instances_buffer->update(&acceleration_structure_instance, sizeof(VkAccelerationStructureInstanceKHR)); // Top Level AS with single instance @@ -242,7 +238,8 @@ void RayQueries::create_bottom_level_acceleration_structure() // For the sake of simplicity we won't stage the vertex data to the GPU memory // Note that the buffer usage flags for buffers consumed by the bottom level acceleration structure require special flags - const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VkBufferUsageFlags buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(model.vertices.data(), vertex_buffer_size); @@ -251,32 +248,22 @@ void RayQueries::create_bottom_level_acceleration_structure() index_buffer->update(model.indices.data(), index_buffer_size); // Set up a single transformation matrix that can be used to transform the whole geometry for a single bottom level acceleration structure - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; - std::unique_ptr transform_matrix_buffer = std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; + std::unique_ptr transform_matrix_buffer = + std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); transform_matrix_buffer->update(&transform_matrix, sizeof(transform_matrix)); if (bottom_level_acceleration_structure == nullptr) { - bottom_level_acceleration_structure = std::make_unique( - get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); - bottom_level_acceleration_structure->add_triangle_geometry(*vertex_buffer, - *index_buffer, - *transform_matrix_buffer, - static_cast(model.indices.size()), - static_cast(model.vertices.size()) - 1, - sizeof(Vertex), - 0, - VK_FORMAT_R32G32B32_SFLOAT, - VK_INDEX_TYPE_UINT32, - VK_GEOMETRY_OPAQUE_BIT_KHR, - get_buffer_device_address(vertex_buffer->get_handle()), - get_buffer_device_address(index_buffer->get_handle())); + bottom_level_acceleration_structure = std::make_unique(get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); + bottom_level_acceleration_structure->add_triangle_geometry( + *vertex_buffer, *index_buffer, *transform_matrix_buffer, static_cast(model.indices.size()), + static_cast(model.vertices.size()) - 1, sizeof(Vertex), 0, VK_FORMAT_R32G32B32_SFLOAT, VK_INDEX_TYPE_UINT32, VK_GEOMETRY_OPAQUE_BIT_KHR, + get_buffer_device_address(vertex_buffer->get_handle()), get_buffer_device_address(index_buffer->get_handle())); } bottom_level_acceleration_structure->set_scrach_buffer_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment); - bottom_level_acceleration_structure->build(queue, VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR, VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); + bottom_level_acceleration_structure->build(queue, VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR, + VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); } void RayQueries::load_node(vkb::scene_graph::NodeC &node) @@ -348,24 +335,20 @@ void RayQueries::load_scene() void RayQueries::create_descriptor_pool() { - std::vector pool_sizes = { - {VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 1); + std::vector pool_sizes = {{VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}}; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 1); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); - std::vector set_layout_bindings = - { - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 1)}; + std::vector set_layout_bindings = { + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 1)}; - VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + VkDescriptorSetLayoutCreateInfo descriptor_layout = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } @@ -394,7 +377,8 @@ void RayQueries::create_descriptor_sets() VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*uniform_buffer); - VkWriteDescriptorSet uniform_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &buffer_descriptor); + VkWriteDescriptorSet uniform_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &buffer_descriptor); std::vector write_descriptor_sets = { acceleration_structure_write, @@ -405,29 +389,27 @@ void RayQueries::create_descriptor_sets() void RayQueries::prepare_pipelines() { - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineRasterizationStateCreateInfo rasterization_state = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS); - depth_stencil_state.depthBoundsTestEnable = VK_FALSE; - depth_stencil_state.minDepthBounds = 0.f; - depth_stencil_state.maxDepthBounds = 1.f; + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS); + depth_stencil_state.depthBoundsTestEnable = VK_FALSE; + depth_stencil_state.minDepthBounds = 0.f; + depth_stencil_state.maxDepthBounds = 1.f; VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); @@ -455,9 +437,8 @@ void RayQueries::prepare_pipelines() pipeline_create_info.pDepthStencilState = &depth_stencil_state; pipeline_create_info.pDynamicState = &dynamic_state; - const std::array shader_stages = { - load_shader("ray_queries", "ray_shadow.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), - load_shader("ray_queries", "ray_shadow.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}; + const std::array shader_stages = {load_shader("ray_queries", "ray_shadow.vert.spv", VK_SHADER_STAGE_VERTEX_BIT), + load_shader("ray_queries", "ray_shadow.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT)}; pipeline_create_info.stageCount = static_cast(shader_stages.size()); pipeline_create_info.pStages = shader_stages.data(); @@ -468,17 +449,14 @@ void RayQueries::prepare_pipelines() void RayQueries::create_uniforms() { // Note that in contrast to a typical pipeline, our vertex/index buffer requires the acceleration structure build flag - static constexpr VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + static constexpr VkBufferUsageFlags buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; const auto vertex_buffer_size = model.vertices.size() * sizeof(model.vertices[0]); const auto index_buffer_size = model.indices.size() * sizeof(model.indices[0]); - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - buffer_usage_flags | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - buffer_usage_flags | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, buffer_usage_flags | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); + index_buffer = std::make_unique(get_device(), index_buffer_size, buffer_usage_flags | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); if (vertex_buffer_size) { @@ -489,10 +467,9 @@ void RayQueries::create_uniforms() index_buffer->update(model.indices.data(), index_buffer_size); } - uniform_buffer = std::make_unique(get_device(), - sizeof(global_uniform), - VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer = std::make_unique( + get_device(), sizeof(global_uniform), + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -503,10 +480,11 @@ void RayQueries::update_uniform_buffers() global_uniform.proj = vkb::rendering::vulkan_style_projection(camera.matrices.perspective); global_uniform.view = camera.matrices.view; - const float PI = 3.14159f; - const float radius = 100.f; - const float speed = 2.f * PI / 10000.f; - const float time = static_cast(std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - start_time).count()); + const float PI = 3.14159f; + const float radius = 100.f; + const float speed = 2.f * PI / 10000.f; + const float time = + static_cast(std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - start_time).count()); const float angle = glm::mod(time * speed, PI); global_uniform.light_position = glm::vec3(0.0f, radius * sinf(angle), radius * cosf(angle)); diff --git a/samples/extensions/ray_tracing_basic/ray_tracing_basic.cpp b/samples/extensions/ray_tracing_basic/ray_tracing_basic.cpp index a031007382..f5c0943534 100644 --- a/samples/extensions/ray_tracing_basic/ray_tracing_basic.cpp +++ b/samples/extensions/ray_tracing_basic/ray_tracing_basic.cpp @@ -124,15 +124,8 @@ void RaytracingBasic::create_storage_image() VK_CHECK(vkCreateImageView(get_device().get_handle(), &color_image_view, nullptr, &storage_image.view)); VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkb::image_layout_transition(command_buffer, - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - {}, - {}, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_GENERAL, - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); + vkb::image_layout_transition(command_buffer, storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, {}, {}, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); get_device().flush_command_buffer(command_buffer, queue); } @@ -205,11 +198,8 @@ void RaytracingBasic::create_bottom_level_acceleration_structure() { float pos[3]; }; - std::vector vertices = { - {{1.0f, 1.0f, 0.0f}}, - {{-1.0f, 1.0f, 0.0f}}, - {{0.0f, -1.0f, 0.0f}}}; - std::vector indices = {0, 1, 2}; + std::vector vertices = {{{1.0f, 1.0f, 0.0f}}, {{-1.0f, 1.0f, 0.0f}}, {{0.0f, -1.0f, 0.0f}}}; + std::vector indices = {0, 1, 2}; auto vertex_buffer_size = vertices.size() * sizeof(Vertex); auto index_buffer_size = indices.size() * sizeof(uint32_t); @@ -218,7 +208,8 @@ void RaytracingBasic::create_bottom_level_acceleration_structure() // For the sake of simplicity we won't stage the vertex data to the GPU memory // Note that the buffer usage flags for buffers consumed by the bottom level acceleration structure require special flags - const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VkBufferUsageFlags buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); @@ -227,11 +218,9 @@ void RaytracingBasic::create_bottom_level_acceleration_structure() index_buffer->update(indices.data(), index_buffer_size); // Setup a single transformation matrix that can be used to transform the whole geometry for a single bottom level acceleration structure - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; - std::unique_ptr transform_matrix_buffer = std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; + std::unique_ptr transform_matrix_buffer = + std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); transform_matrix_buffer->update(&transform_matrix, sizeof(transform_matrix)); VkDeviceOrHostAddressConstKHR vertex_data_device_address{}; @@ -268,19 +257,13 @@ void RaytracingBasic::create_bottom_level_acceleration_structure() VkAccelerationStructureBuildSizesInfoKHR acceleration_structure_build_sizes_info{}; acceleration_structure_build_sizes_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR; - vkGetAccelerationStructureBuildSizesKHR( - get_device().get_handle(), - VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, - &acceleration_structure_build_geometry_info, - &primitive_count, - &acceleration_structure_build_sizes_info); + vkGetAccelerationStructureBuildSizesKHR(get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, + &acceleration_structure_build_geometry_info, &primitive_count, &acceleration_structure_build_sizes_info); // Create a buffer to hold the acceleration structure bottom_level_acceleration_structure.buffer = std::make_unique( - get_device(), - acceleration_structure_build_sizes_info.accelerationStructureSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + get_device(), acceleration_structure_build_sizes_info.accelerationStructureSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Create the acceleration structure VkAccelerationStructureCreateInfoKHR acceleration_structure_create_info{}; @@ -313,13 +296,10 @@ void RaytracingBasic::create_bottom_level_acceleration_structure() std::vector acceleration_build_structure_range_infos = {&acceleration_structure_build_range_info}; // Build the acceleration structure on the device via a one-time command buffer submission - // Some implementations may support acceleration structure building on the host (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds + // Some implementations may support acceleration structure building on the host + // (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkCmdBuildAccelerationStructuresKHR( - command_buffer, - 1, - &acceleration_build_geometry_info, - acceleration_build_structure_range_infos.data()); + vkCmdBuildAccelerationStructuresKHR(command_buffer, 1, &acceleration_build_geometry_info, acceleration_build_structure_range_infos.data()); get_device().flush_command_buffer(command_buffer, queue); delete_scratch_buffer(scratch_buffer); @@ -337,10 +317,7 @@ void RaytracingBasic::create_bottom_level_acceleration_structure() */ void RaytracingBasic::create_top_level_acceleration_structure() { - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; VkAccelerationStructureInstanceKHR acceleration_structure_instance{}; acceleration_structure_instance.transform = transform_matrix; @@ -350,10 +327,9 @@ void RaytracingBasic::create_top_level_acceleration_structure() acceleration_structure_instance.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR; acceleration_structure_instance.accelerationStructureReference = bottom_level_acceleration_structure.device_address; - std::unique_ptr instances_buffer = std::make_unique(get_device(), - sizeof(VkAccelerationStructureInstanceKHR), - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr instances_buffer = std::make_unique( + get_device(), sizeof(VkAccelerationStructureInstanceKHR), + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); instances_buffer->update(&acceleration_structure_instance, sizeof(VkAccelerationStructureInstanceKHR)); VkDeviceOrHostAddressConstKHR instance_data_device_address{}; @@ -380,18 +356,13 @@ void RaytracingBasic::create_top_level_acceleration_structure() VkAccelerationStructureBuildSizesInfoKHR acceleration_structure_build_sizes_info{}; acceleration_structure_build_sizes_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR; - vkGetAccelerationStructureBuildSizesKHR( - get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, - &acceleration_structure_build_geometry_info, - &primitive_count, - &acceleration_structure_build_sizes_info); + vkGetAccelerationStructureBuildSizesKHR(get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, + &acceleration_structure_build_geometry_info, &primitive_count, &acceleration_structure_build_sizes_info); // Create a buffer to hold the acceleration structure top_level_acceleration_structure.buffer = std::make_unique( - get_device(), - acceleration_structure_build_sizes_info.accelerationStructureSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + get_device(), acceleration_structure_build_sizes_info.accelerationStructureSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Create the acceleration structure VkAccelerationStructureCreateInfoKHR acceleration_structure_create_info{}; @@ -424,13 +395,10 @@ void RaytracingBasic::create_top_level_acceleration_structure() std::vector acceleration_build_structure_range_infos = {&acceleration_structure_build_range_info}; // Build the acceleration structure on the device via a one-time command buffer submission - // Some implementations may support acceleration structure building on the host (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds + // Some implementations may support acceleration structure building on the host + // (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkCmdBuildAccelerationStructuresKHR( - command_buffer, - 1, - &acceleration_build_geometry_info, - acceleration_build_structure_range_infos.data()); + vkCmdBuildAccelerationStructuresKHR(command_buffer, 1, &acceleration_build_geometry_info, acceleration_build_structure_range_infos.data()); get_device().flush_command_buffer(command_buffer, queue); delete_scratch_buffer(scratch_buffer); @@ -439,8 +407,7 @@ void RaytracingBasic::create_top_level_acceleration_structure() VkAccelerationStructureDeviceAddressInfoKHR acceleration_device_address_info{}; acceleration_device_address_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR; acceleration_device_address_info.accelerationStructure = top_level_acceleration_structure.handle; - top_level_acceleration_structure.device_address = - vkGetAccelerationStructureDeviceAddressKHR(get_device().get_handle(), &acceleration_device_address_info); + top_level_acceleration_structure.device_address = vkGetAccelerationStructureDeviceAddressKHR(get_device().get_handle(), &acceleration_device_address_info); } inline uint32_t aligned_size(uint32_t value, uint32_t alignment) @@ -473,13 +440,15 @@ void RaytracingBasic::create_scene() void RaytracingBasic::create_shader_binding_tables() { - const uint32_t handle_size = ray_tracing_pipeline_properties.shaderGroupHandleSize; - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); - const uint32_t handle_alignment = ray_tracing_pipeline_properties.shaderGroupHandleAlignment; - const uint32_t group_count = static_cast(shader_groups.size()); - const uint32_t sbt_size = group_count * handle_size_aligned; - const VkBufferUsageFlags sbt_buffer_usage_flags = VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + const uint32_t handle_size = ray_tracing_pipeline_properties.shaderGroupHandleSize; + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + const uint32_t handle_alignment = ray_tracing_pipeline_properties.shaderGroupHandleAlignment; + const uint32_t group_count = static_cast(shader_groups.size()); + const uint32_t sbt_size = group_count * handle_size_aligned; + const VkBufferUsageFlags sbt_buffer_usage_flags = + VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; // Raygen // Create binding table buffers for each shader type @@ -509,9 +478,7 @@ void RaytracingBasic::create_shader_binding_tables() void RaytracingBasic::create_descriptor_sets() { std::vector pool_sizes = { - {VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}}; + {VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 1); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); @@ -539,13 +506,11 @@ void RaytracingBasic::create_descriptor_sets() VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*ubo); - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); - VkWriteDescriptorSet uniform_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); + VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + VkWriteDescriptorSet uniform_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); - std::vector write_descriptor_sets = { - acceleration_structure_write, - result_image_write, - uniform_buffer_write}; + std::vector write_descriptor_sets = {acceleration_structure_write, result_image_write, uniform_buffer_write}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); } @@ -573,10 +538,7 @@ void RaytracingBasic::create_ray_tracing_pipeline() uniform_buffer_binding.descriptorCount = 1; uniform_buffer_binding.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR; - std::vector bindings = { - acceleration_structure_layout_binding, - result_image_layout_binding, - uniform_buffer_binding}; + std::vector bindings = {acceleration_structure_layout_binding, result_image_layout_binding, uniform_buffer_binding}; VkDescriptorSetLayoutCreateInfo layout_info{}; layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; @@ -647,7 +609,8 @@ void RaytracingBasic::create_ray_tracing_pipeline() raytracing_pipeline_create_info.pGroups = shader_groups.data(); raytracing_pipeline_create_info.maxPipelineRayRecursionDepth = 1; raytracing_pipeline_create_info.layout = pipeline_layout; - VK_CHECK(vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); + VK_CHECK( + vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); } /* @@ -670,10 +633,7 @@ void RaytracingBasic::delete_acceleration_structure(AccelerationStructure &accel */ void RaytracingBasic::create_uniform_buffer() { - ubo = std::make_unique(get_device(), - sizeof(uniform_data), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + ubo = std::make_unique(get_device(), sizeof(uniform_data), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); ubo->convert_and_update(uniform_data); update_uniform_buffers(); @@ -693,9 +653,10 @@ void RaytracingBasic::build_command_buffers() create_storage_image(); // The descriptor also needs to be updated to reference the new image VkDescriptorImageInfo image_descriptor{}; - image_descriptor.imageView = storage_image.view; - image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + image_descriptor.imageView = storage_image.view; + image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; + VkWriteDescriptorSet result_image_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); vkUpdateDescriptorSets(get_device().get_handle(), 1, &result_image_write, 0, VK_NULL_HANDLE); } @@ -711,7 +672,8 @@ void RaytracingBasic::build_command_buffers() Setup the strided device address regions pointing at the shader identifiers in the shader binding table */ - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); VkStridedDeviceAddressRegionKHR raygen_shader_sbt_entry{}; raygen_shader_sbt_entry.deviceAddress = get_buffer_device_address(raygen_shader_binding_table->get_handle()); @@ -736,41 +698,21 @@ void RaytracingBasic::build_command_buffers() vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline); vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline_layout, 0, 1, &descriptor_set, 0, 0); - vkCmdTraceRaysKHR( - draw_cmd_buffers[i], - &raygen_shader_sbt_entry, - &miss_shader_sbt_entry, - &hit_shader_sbt_entry, - &callable_shader_sbt_entry, - width, - height, - 1); + vkCmdTraceRaysKHR(draw_cmd_buffers[i], &raygen_shader_sbt_entry, &miss_shader_sbt_entry, &hit_shader_sbt_entry, &callable_shader_sbt_entry, width, + height, 1); /* Copy ray tracing output to swap chain image */ // Prepare current swap chain image as transfer destination - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, {}, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Prepare ray tracing output image as transfer source - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {}, + VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); VkImageCopy copy_region{}; copy_region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; @@ -778,25 +720,16 @@ void RaytracingBasic::build_command_buffers() copy_region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; copy_region.dstOffset = {0, 0, 0}; copy_region.extent = {width, height, 1}; - vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, get_render_context().get_swapchain().get_images()[i], + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); // Transition swap chain image back for presentation - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); // Transition ray tracing output image back to general layout - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - {}, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_IMAGE_LAYOUT_GENERAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_TRANSFER_READ_BIT, {}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresource_range); /* Start a new render pass to draw the UI overlay on top of the ray traced image diff --git a/samples/extensions/ray_tracing_extended/ray_tracing_extended.cpp b/samples/extensions/ray_tracing_extended/ray_tracing_extended.cpp index 0b4a504848..362a321317 100644 --- a/samples/extensions/ray_tracing_extended/ray_tracing_extended.cpp +++ b/samples/extensions/ray_tracing_extended/ray_tracing_extended.cpp @@ -35,8 +35,7 @@ struct QuickTimer const char *name; const clock::time_point start; bool print_on_exit; - explicit QuickTimer(const char *name_, bool print_on_exit_ = true) : - name(name_), start(clock::now()), print_on_exit(print_on_exit_) + explicit QuickTimer(const char *name_, bool print_on_exit_ = true) : name(name_), start(clock::now()), print_on_exit(print_on_exit_) {} ~QuickTimer() @@ -76,12 +75,7 @@ struct RaytracingExtended::Model VkTransformMatrixKHR default_transform; uint32_t texture_index; uint32_t object_type; - Model() : - default_transform({1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}), - texture_index(0), - object_type(0) + Model() : default_transform({1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}), texture_index(0), object_type(0) {} }; @@ -202,15 +196,8 @@ void RaytracingExtended::create_storage_image() VK_CHECK(vkCreateImageView(get_device().get_handle(), &color_image_view, nullptr, &storage_image.view)); VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkb::image_layout_transition(command_buffer, - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - {}, - {}, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_GENERAL, - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); + vkb::image_layout_transition(command_buffer, storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, {}, {}, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); get_device().flush_command_buffer(command_buffer, queue); } @@ -228,12 +215,8 @@ uint64_t RaytracingExtended::get_buffer_device_address(VkBuffer buffer) void RaytracingExtended::create_flame_model() { flame_texture = load_texture("textures/generated_flame.ktx", vkb::sg::Image::Color); - std::vector pts_ = {{0, 0, 0}, - {1, 0, 0}, - {1, 1, 0}, - {0, 1, 0}}; - std::vector indices_ = {{0, 1, 2}, - {0, 2, 3}}; + std::vector pts_ = {{0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}}; + std::vector indices_ = {{0, 1, 2}, {0, 2, 3}}; std::vector vertices; for (auto &pt : pts_) @@ -286,10 +269,11 @@ void RaytracingExtended::create_static_object_buffers() // Create a staging buffer. (If staging buffer use is disabled, then this will be the final buffer) std::unique_ptr staging_vertex_buffer = nullptr, staging_index_buffer = nullptr; - static constexpr VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; - const VkBufferUsageFlags staging_flags = scene_options.use_vertex_staging_buffer ? VK_BUFFER_USAGE_TRANSFER_SRC_BIT : buffer_usage_flags; - staging_vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); - staging_index_buffer = std::make_unique(get_device(), index_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + static constexpr VkBufferUsageFlags buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + const VkBufferUsageFlags staging_flags = scene_options.use_vertex_staging_buffer ? VK_BUFFER_USAGE_TRANSFER_SRC_BIT : buffer_usage_flags; + staging_vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + staging_index_buffer = std::make_unique(get_device(), index_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); // Copy over the data for each of the models for (size_t i = 0; i < models.size(); ++i) @@ -305,7 +289,8 @@ void RaytracingExtended::create_static_object_buffers() auto cmd = get_device().get_command_pool().request_command_buffer(); cmd->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, VK_NULL_HANDLE); auto copy = [this, &cmd](vkb::core::BufferC &staging_buffer) { - auto output_buffer = std::make_unique(get_device(), staging_buffer.get_size(), buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + auto output_buffer = std::make_unique(get_device(), staging_buffer.get_size(), + buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); cmd->copy_buffer(staging_buffer, *output_buffer, staging_buffer.get_size()); vkb::BufferMemoryBarrier barrier; @@ -370,53 +355,46 @@ void RaytracingExtended::create_bottom_level_acceleration_structure(bool is_upda { continue; } - const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; // Set up a single transformation matrix that can be used to transform the whole geometry for a single bottom level acceleration structure VkTransformMatrixKHR transform_matrix = model_buffer.default_transform; if (!model_buffer.transform_matrix_buffer || model_buffer.transform_matrix_buffer->get_size() != sizeof(transform_matrix)) { - model_buffer.transform_matrix_buffer = std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + model_buffer.transform_matrix_buffer = + std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); } model_buffer.transform_matrix_buffer->update(&transform_matrix, sizeof(transform_matrix)); #ifdef USE_FRAMEWORK_ACCELERATION_STRUCTURE if (model_buffer.bottom_level_acceleration_structure == nullptr) { - model_buffer.bottom_level_acceleration_structure = std::make_unique( - get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); + model_buffer.bottom_level_acceleration_structure = + std::make_unique(get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); model_buffer.object_id = model_buffer.bottom_level_acceleration_structure->add_triangle_geometry( - model_buffer.is_static ? *vertex_buffer : *dynamic_vertex_buffer, - model_buffer.is_static ? *index_buffer : *dynamic_index_buffer, - *model_buffer.transform_matrix_buffer, - static_cast(model_buffer.num_triangles), - static_cast(model_buffer.num_vertices) - 1, - sizeof(NewVertex), - 0, - VK_FORMAT_R32G32B32_SFLOAT, - VK_INDEX_TYPE_UINT32, - VK_GEOMETRY_OPAQUE_BIT_KHR, + model_buffer.is_static ? *vertex_buffer : *dynamic_vertex_buffer, model_buffer.is_static ? *index_buffer : *dynamic_index_buffer, + *model_buffer.transform_matrix_buffer, static_cast(model_buffer.num_triangles), static_cast(model_buffer.num_vertices) - 1, + sizeof(NewVertex), 0, VK_FORMAT_R32G32B32_SFLOAT, VK_INDEX_TYPE_UINT32, VK_GEOMETRY_OPAQUE_BIT_KHR, model_buffer.vertex_offset + (model_buffer.is_static ? static_vertex_handle : dynamic_vertex_handle), model_buffer.index_offset + (model_buffer.is_static ? static_index_handle : dynamic_index_handle)); } else { model_buffer.bottom_level_acceleration_structure->update_triangle_geometry( - model_buffer.object_id, - dynamic_vertex_buffer, - dynamic_index_buffer, - model_buffer.transform_matrix_buffer, - static_cast(model_buffer.num_triangles), - static_cast(model_buffer.num_vertices) - 1, - sizeof(NewVertex), - 0, VK_FORMAT_R32G32B32_SFLOAT, VK_GEOMETRY_OPAQUE_BIT_KHR, + model_buffer.object_id, dynamic_vertex_buffer, dynamic_index_buffer, model_buffer.transform_matrix_buffer, + static_cast(model_buffer.num_triangles), static_cast(model_buffer.num_vertices) - 1, sizeof(NewVertex), 0, + VK_FORMAT_R32G32B32_SFLOAT, VK_GEOMETRY_OPAQUE_BIT_KHR, model_buffer.vertex_offset + (model_buffer.is_static ? static_vertex_handle : dynamic_vertex_handle), model_buffer.index_offset + (model_buffer.is_static ? static_index_handle : dynamic_index_handle)); } - model_buffer.bottom_level_acceleration_structure->set_scrach_buffer_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment); - model_buffer.bottom_level_acceleration_structure->build(queue, - model_buffer.is_static ? VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR : VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR, - is_update ? VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR : VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); + model_buffer.bottom_level_acceleration_structure->set_scrach_buffer_alignment( + acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment); + model_buffer.bottom_level_acceleration_structure->build( + queue, + model_buffer.is_static ? VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR : + VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR, + is_update ? VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR : VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); #else VkDeviceOrHostAddressConstKHR vertex_data_device_address{}; VkDeviceOrHostAddressConstKHR index_data_device_address{}; @@ -452,10 +430,12 @@ void RaytracingExtended::create_bottom_level_acceleration_structure(bool is_upda // now create BLAS VkAccelerationStructureBuildGeometryInfoKHR acceleration_structure_build_geometry_info{}; - acceleration_structure_build_geometry_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR; - acceleration_structure_build_geometry_info.pNext = nullptr; - acceleration_structure_build_geometry_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; - acceleration_structure_build_geometry_info.flags = model_buffer.is_static ? VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR : VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; + acceleration_structure_build_geometry_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR; + acceleration_structure_build_geometry_info.pNext = nullptr; + acceleration_structure_build_geometry_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; + acceleration_structure_build_geometry_info.flags = + model_buffer.is_static ? VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR : + VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; acceleration_structure_build_geometry_info.geometryCount = 1; if (is_update) { @@ -469,22 +449,17 @@ void RaytracingExtended::create_bottom_level_acceleration_structure(bool is_upda auto &acceleration_structure_build_sizes_info = model_buffer.buildSize; acceleration_structure_build_sizes_info.pNext = nullptr; acceleration_structure_build_sizes_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR; - vkGetAccelerationStructureBuildSizesKHR( - get_device().get_handle(), - VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, - &acceleration_structure_build_geometry_info, - &primitive_count, - &acceleration_structure_build_sizes_info); + vkGetAccelerationStructureBuildSizesKHR(get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, + &acceleration_structure_build_geometry_info, &primitive_count, &acceleration_structure_build_sizes_info); // Create a buffer to hold the acceleration structure auto &bottom_level_acceleration_structure = model_buffer.bottom_level_acceleration_structure; - if (!bottom_level_acceleration_structure.buffer || bottom_level_acceleration_structure.buffer->get_size() != model_buffer.buildSize.accelerationStructureSize) + if (!bottom_level_acceleration_structure.buffer || + bottom_level_acceleration_structure.buffer->get_size() != model_buffer.buildSize.accelerationStructureSize) { bottom_level_acceleration_structure.buffer = std::make_unique( - get_device(), - model_buffer.buildSize.accelerationStructureSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + get_device(), model_buffer.buildSize.accelerationStructureSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_GPU_ONLY); } if (!is_update && bottom_level_acceleration_structure.handle == nullptr) { @@ -500,17 +475,21 @@ void RaytracingExtended::create_bottom_level_acceleration_structure(bool is_upda // The actual build process starts here // Create a scratch buffer as a temporary storage for the acceleration structure build - auto scratch_buffer = std::make_unique(get_device(), vkb::core::BufferBuilderC(model_buffer.buildSize.buildScratchSize) - .with_usage(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) - .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY) - .with_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment)); + auto scratch_buffer = std::make_unique( + get_device(), vkb::core::BufferBuilderC(model_buffer.buildSize.buildScratchSize) + .with_usage(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) + .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY) + .with_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment)); { VkAccelerationStructureBuildGeometryInfoKHR acceleration_build_geometry_info{}; acceleration_build_geometry_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR; acceleration_build_geometry_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; - acceleration_build_geometry_info.flags = model_buffer.is_static ? VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR : VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; - acceleration_build_geometry_info.mode = is_update ? VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR : VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR; + acceleration_build_geometry_info.flags = + model_buffer.is_static ? VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR : + VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; + acceleration_build_geometry_info.mode = + is_update ? VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR : VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR; if (is_update) { acceleration_build_geometry_info.srcAccelerationStructure = bottom_level_acceleration_structure.handle; @@ -521,14 +500,11 @@ void RaytracingExtended::create_bottom_level_acceleration_structure(bool is_upda acceleration_build_geometry_info.scratchData.deviceAddress = scratch_buffer->get_device_address(); // Build the acceleration structure on the device via a one-time command buffer submission - // Some implementations may support acceleration structure building on the host (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds - VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); + // Some implementations may support acceleration structure building on the host + // (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds + VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); std::array build_range_infos = {&model_buffer.buildRangeInfo}; - vkCmdBuildAccelerationStructuresKHR( - command_buffer, - 1, - &acceleration_build_geometry_info, - &build_range_infos[0]); + vkCmdBuildAccelerationStructuresKHR(command_buffer, 1, &acceleration_build_geometry_info, &build_range_infos[0]); get_device().flush_command_buffer(command_buffer, queue); } @@ -559,10 +535,7 @@ VkTransformMatrixKHR RaytracingExtended::calculate_rotation(glm::vec3 pt, float normal *= scale; u *= scale; v *= scale; - return { - u.x, v.x, normal.x, pt.x, - u.y, v.y, normal.y, pt.y, - u.z, v.z, normal.z, pt.z}; + return {u.x, v.x, normal.x, pt.x, u.y, v.y, normal.y, pt.y, u.z, v.z, normal.z, pt.z}; } /* @@ -575,10 +548,7 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time */ QuickTimer timer{"TLAS Build", print_time}; assert(!!raytracing_scene); - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // This buffer is used to correlate the instance information with model information // and is required because the number and type of instances is dynamic @@ -586,13 +556,13 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time // Add the instances for the static scene, billboard texture, and refraction model std::vector instances; - auto add_instance = [&](ModelBuffer &model_buffer, const VkTransformMatrixKHR &transform_matrix, uint32_t instance_index) { - VkAccelerationStructureInstanceKHR acceleration_structure_instance{}; - acceleration_structure_instance.transform = transform_matrix; - acceleration_structure_instance.instanceCustomIndex = instance_index; - acceleration_structure_instance.mask = 0xFF; - acceleration_structure_instance.instanceShaderBindingTableRecordOffset = 0; - acceleration_structure_instance.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR; + auto add_instance = [&](ModelBuffer &model_buffer, const VkTransformMatrixKHR &transform_matrix, uint32_t instance_index) { + VkAccelerationStructureInstanceKHR acceleration_structure_instance{}; + acceleration_structure_instance.transform = transform_matrix; + acceleration_structure_instance.instanceCustomIndex = instance_index; + acceleration_structure_instance.mask = 0xFF; + acceleration_structure_instance.instanceShaderBindingTableRecordOffset = 0; + acceleration_structure_instance.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR; #ifdef USE_FRAMEWORK_ACCELERATION_STRUCTURE acceleration_structure_instance.accelerationStructureReference = model_buffer.bottom_level_acceleration_structure->get_device_address(); #else @@ -610,7 +580,8 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time scene_instance.indices_index = static_cast(model_buffer.index_offset / sizeof(Triangle)); scene_instance.object_type = model_buffer.object_type; scene_instance.image_index = model_buffer.texture_index; - ASSERT_LOG(scene_instance.object_type == ObjectType::OBJECT_REFRACTION || scene_instance.image_index < raytracing_scene->imageInfos.size(), "Only the refraction model can be texture less.") + ASSERT_LOG(scene_instance.object_type == ObjectType::OBJECT_REFRACTION || scene_instance.image_index < raytracing_scene->imageInfos.size(), + "Only the refraction model can be texture less.") model_instance_data.emplace_back(scene_instance); // these objects have a single instance with the identity transform @@ -631,9 +602,7 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time { // find the flame particle object, then add the particles as instances auto &model_buffers = raytracing_scene->model_buffers; - auto iter = std::ranges::find_if(model_buffers, [](const ModelBuffer &model_buffer) { - return model_buffer.object_type == ObjectType::OBJECT_FLAME; - }); + auto iter = std::ranges::find_if(model_buffers, [](const ModelBuffer &model_buffer) { return model_buffer.object_type == ObjectType::OBJECT_FLAME; }); ASSERT_LOG(iter != model_buffers.cend(), "Can't find flame object.") auto &model_buffer = *iter; uint32_t index = static_cast(std::distance(model_buffers.begin(), iter)); @@ -646,17 +615,17 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time size_t data_to_model_size = model_instance_data.size() * sizeof(model_instance_data[0]); if (!data_to_model_buffer || data_to_model_buffer->get_size() < data_to_model_size) { - data_to_model_buffer = std::make_unique(get_device(), data_to_model_size, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + data_to_model_buffer = std::make_unique( + get_device(), data_to_model_size, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } data_to_model_buffer->update(model_instance_data.data(), data_to_model_size, 0); const size_t instancesDataSize = sizeof(VkAccelerationStructureInstanceKHR) * instances.size(); if (!instances_buffer || instances_buffer->get_size() != instancesDataSize) { - instances_buffer = std::make_unique(get_device(), - instancesDataSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + instances_buffer = std::make_unique( + get_device(), instancesDataSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); } instances_buffer->update(instances.data(), instancesDataSize); @@ -698,20 +667,15 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time VkAccelerationStructureBuildSizesInfoKHR acceleration_structure_build_sizes_info{}; acceleration_structure_build_sizes_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR; - vkGetAccelerationStructureBuildSizesKHR( - get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, - &acceleration_structure_build_geometry_info, - &primitive_count, - &acceleration_structure_build_sizes_info); + vkGetAccelerationStructureBuildSizesKHR(get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, + &acceleration_structure_build_geometry_info, &primitive_count, &acceleration_structure_build_sizes_info); // Create a buffer to hold the acceleration structure if (top_level_acceleration_structure.buffer == nullptr) { top_level_acceleration_structure.buffer = std::make_unique( - get_device(), - acceleration_structure_build_sizes_info.accelerationStructureSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + get_device(), acceleration_structure_build_sizes_info.accelerationStructureSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_GPU_ONLY); } // Create the acceleration structure @@ -723,8 +687,7 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time acceleration_structure_create_info.buffer = top_level_acceleration_structure.buffer->get_handle(); acceleration_structure_create_info.size = acceleration_structure_build_sizes_info.accelerationStructureSize; acceleration_structure_create_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR; - vkCreateAccelerationStructureKHR(get_device().get_handle(), &acceleration_structure_create_info, nullptr, - &top_level_acceleration_structure.handle); + vkCreateAccelerationStructureKHR(get_device().get_handle(), &acceleration_structure_create_info, nullptr, &top_level_acceleration_structure.handle); } else { @@ -734,11 +697,11 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time // The actual build process starts here // Create a scratch buffer as a temporary storage for the acceleration structure build - auto scratch_buffer = std::make_unique(get_device(), - vkb::core::BufferBuilderC(acceleration_structure_build_sizes_info.buildScratchSize) - .with_usage(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_2_SHADER_DEVICE_ADDRESS_BIT) - .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY) - .with_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment)); + auto scratch_buffer = std::make_unique( + get_device(), vkb::core::BufferBuilderC(acceleration_structure_build_sizes_info.buildScratchSize) + .with_usage(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_2_SHADER_DEVICE_ADDRESS_BIT) + .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY) + .with_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment)); VkAccelerationStructureBuildGeometryInfoKHR acceleration_build_geometry_info{}; acceleration_build_geometry_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR; @@ -762,13 +725,10 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time std::vector acceleration_build_structure_range_infos = {&acceleration_structure_build_range_info}; // Build the acceleration structure on the device via a one-time command buffer submission - // Some implementations may support acceleration structure building on the host (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds + // Some implementations may support acceleration structure building on the host + // (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkCmdBuildAccelerationStructuresKHR( - command_buffer, - 1, - &acceleration_build_geometry_info, - acceleration_build_structure_range_infos.data()); + vkCmdBuildAccelerationStructuresKHR(command_buffer, 1, &acceleration_build_geometry_info, acceleration_build_structure_range_infos.data()); get_device().flush_command_buffer(command_buffer, queue); scratch_buffer.reset(); @@ -777,8 +737,7 @@ void RaytracingExtended::create_top_level_acceleration_structure(bool print_time VkAccelerationStructureDeviceAddressInfoKHR acceleration_device_address_info{}; acceleration_device_address_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR; acceleration_device_address_info.accelerationStructure = top_level_acceleration_structure.handle; - top_level_acceleration_structure.device_address = - vkGetAccelerationStructureDeviceAddressKHR(get_device().get_handle(), &acceleration_device_address_info); + top_level_acceleration_structure.device_address = vkGetAccelerationStructureDeviceAddressKHR(get_device().get_handle(), &acceleration_device_address_info); #endif } @@ -828,10 +787,7 @@ void RaytracingExtended::create_scene() refraction_indices.resize(2 * grid_size * grid_size); std::vector scenesToLoad; const float sponza_scale = 0.01f; - const glm::mat4x4 sponza_transform{0.f, 0.f, sponza_scale, 0.f, - sponza_scale, 0.f, 0.f, 0.f, - 0.f, sponza_scale, 0.f, 0.f, - 0.f, 0.f, 0.f, 1.f}; + const glm::mat4x4 sponza_transform{0.f, 0.f, sponza_scale, 0.f, sponza_scale, 0.f, 0.f, 0.f, 0.f, sponza_scale, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f}; scenesToLoad.emplace_back("scenes/sponza/Sponza01.gltf", sponza_transform, ObjectType::OBJECT_NORMAL); raytracing_scene = std::make_unique(get_device(), std::move(scenesToLoad)); @@ -861,30 +817,35 @@ void RaytracingExtended::create_scene() void RaytracingExtended::create_shader_binding_tables() { - const uint32_t handle_size = ray_tracing_pipeline_properties.shaderGroupHandleSize; - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); - auto group_count = static_cast(shader_groups.size()); - const uint32_t sbt_size = group_count * handle_size_aligned; - const VkBufferUsageFlags sbt_buffer_usage_flags = VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + const uint32_t handle_size = ray_tracing_pipeline_properties.shaderGroupHandleSize; + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + auto group_count = static_cast(shader_groups.size()); + const uint32_t sbt_size = group_count * handle_size_aligned; + const VkBufferUsageFlags sbt_buffer_usage_flags = + VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; // Raygen // Create binding table buffers for each shader type - raygen_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_vma_flags(0) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); - miss_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_vma_flags(0) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); - hit_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_vma_flags(0) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + raygen_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_vma_flags(0) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + miss_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_vma_flags(0) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + hit_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_vma_flags(0) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); // Copy the pipeline's shader handles into a host buffer std::vector shader_handle_storage(sbt_size); @@ -907,14 +868,13 @@ void RaytracingExtended::create_shader_binding_tables() */ void RaytracingExtended::create_descriptor_sets() { - std::vector pool_sizes = { - {VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, - {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast(raytracing_scene->imageInfos.size())}}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 1); + std::vector pool_sizes = {{VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, + {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5}, + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, + {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast(raytracing_scene->imageInfos.size())}}; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 1); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); VkDescriptorSetAllocateInfo descriptor_set_allocate_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); @@ -951,25 +911,24 @@ void RaytracingExtended::create_descriptor_sets() VkDescriptorBufferInfo dynamic_index_descriptor = create_descriptor(*dynamic_index_buffer); VkDescriptorBufferInfo data_map_descriptor = create_descriptor(*data_to_model_buffer); - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); - VkWriteDescriptorSet uniform_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); - VkWriteDescriptorSet vertex_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4, &vertex_descriptor); - VkWriteDescriptorSet index_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5, &index_descriptor); - VkWriteDescriptorSet data_map_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 6, &data_map_descriptor); - VkWriteDescriptorSet texture_array_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 7, raytracing_scene->imageInfos.data(), static_cast(raytracing_scene->imageInfos.size())); - VkWriteDescriptorSet dynamic_vertex_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 8, &dynamic_vertex_descriptor); - VkWriteDescriptorSet dynamic_index_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 9, &dynamic_index_descriptor); - - std::vector write_descriptor_sets = { - acceleration_structure_write, - result_image_write, - uniform_buffer_write, - vertex_buffer_write, - index_buffer_write, - data_map_write, - texture_array_write, - dynamic_vertex_buffer_write, - dynamic_index_buffer_write}; + VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + VkWriteDescriptorSet uniform_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); + VkWriteDescriptorSet vertex_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4, &vertex_descriptor); + VkWriteDescriptorSet index_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5, &index_descriptor); + VkWriteDescriptorSet data_map_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 6, &data_map_descriptor); + VkWriteDescriptorSet texture_array_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 7, raytracing_scene->imageInfos.data(), + static_cast(raytracing_scene->imageInfos.size())); + VkWriteDescriptorSet dynamic_vertex_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 8, &dynamic_vertex_descriptor); + VkWriteDescriptorSet dynamic_index_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 9, &dynamic_index_descriptor); + + std::vector write_descriptor_sets = {acceleration_structure_write, result_image_write, uniform_buffer_write, + vertex_buffer_write, index_buffer_write, data_map_write, + texture_array_write, dynamic_vertex_buffer_write, dynamic_index_buffer_write}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); } @@ -983,9 +942,7 @@ void RaytracingExtended::create_dynamic_object_buffers(float time) const float y = static_cast(j) / static_cast(grid_size); const float lateral_scale = std::min(std::min(std::min(std::min(x, 1 - x), y), 1 - y), 0.2f) * 5.f; refraction_model[grid_size * i + j].normal = {0.f, 0.f, 0.f}; - refraction_model[grid_size * i + j].pos = {y - 0.5f, - 2 * x - 1.f, - lateral_scale * 0.025f * cos(2 * 3.14159 * (4 * x + time / 2))}; + refraction_model[grid_size * i + j].pos = {y - 0.5f, 2 * x - 1.f, lateral_scale * 0.025f * cos(2 * 3.14159 * (4 * x + time / 2))}; refraction_model[grid_size * i + j].tex_coord = glm::vec2{x, y}; if (i + 1 < grid_size && j + 1 < grid_size) @@ -997,7 +954,8 @@ void RaytracingExtended::create_dynamic_object_buffers(float time) } for (auto &&tri : refraction_indices) { - glm::vec3 normal = glm::normalize(glm::cross(refraction_model[tri[1]].pos - refraction_model[tri[0]].pos, refraction_model[tri[2]].pos - refraction_model[tri[0]].pos)); + glm::vec3 normal = glm::normalize( + glm::cross(refraction_model[tri[1]].pos - refraction_model[tri[0]].pos, refraction_model[tri[2]].pos - refraction_model[tri[0]].pos)); for (auto &&index : tri) { ASSERT_LOG(index >= 0 && index < refraction_model.size(), "Valid tri") @@ -1016,8 +974,16 @@ void RaytracingExtended::create_dynamic_object_buffers(float time) if (!dynamic_vertex_buffer || !dynamic_index_buffer) { // note these flags are different because they will be read/write, in contrast to static - dynamic_vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); - dynamic_index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + dynamic_vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); + dynamic_index_buffer = std::make_unique(get_device(), index_buffer_size, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); } dynamic_vertex_buffer->update(refraction_model.data(), vertex_buffer_size); @@ -1122,16 +1088,15 @@ void RaytracingExtended::create_ray_tracing_pipeline() dynamic_index_binding.descriptorCount = 1; dynamic_index_binding.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR; - std::vector bindings = { - acceleration_structure_layout_binding, - result_image_layout_binding, - uniform_buffer_binding, - vertex_binding, - index_binding, - data_map_binding, - texture_array_binding, - dynamic_vertex_binding, - dynamic_index_binding}; + std::vector bindings = {acceleration_structure_layout_binding, + result_image_layout_binding, + uniform_buffer_binding, + vertex_binding, + index_binding, + data_map_binding, + texture_array_binding, + dynamic_vertex_binding, + dynamic_index_binding}; VkDescriptorSetLayoutCreateInfo layout_info{}; layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; @@ -1204,7 +1169,8 @@ void RaytracingExtended::create_ray_tracing_pipeline() raytracing_pipeline_create_info.pGroups = shader_groups.data(); raytracing_pipeline_create_info.maxPipelineRayRecursionDepth = 1; raytracing_pipeline_create_info.layout = pipeline_layout; - VK_CHECK(vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); + VK_CHECK( + vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); } #ifndef USE_FRAMEWORK_ACCELERATION_STRUCTURE @@ -1229,10 +1195,7 @@ void RaytracingExtended::delete_acceleration_structure(AccelerationStructureExte */ void RaytracingExtended::create_uniform_buffer() { - ubo = std::make_unique(get_device(), - sizeof(uniform_data), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + ubo = std::make_unique(get_device(), sizeof(uniform_data), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); ubo->convert_and_update(uniform_data); update_uniform_buffers(); } @@ -1251,9 +1214,10 @@ void RaytracingExtended::build_command_buffers() create_storage_image(); // The descriptor also needs to be updated to reference the new image VkDescriptorImageInfo image_descriptor{}; - image_descriptor.imageView = storage_image.view; - image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + image_descriptor.imageView = storage_image.view; + image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; + VkWriteDescriptorSet result_image_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); vkUpdateDescriptorSets(get_device().get_handle(), 1, &result_image_write, 0, VK_NULL_HANDLE); } @@ -1281,7 +1245,8 @@ void RaytracingExtended::build_command_buffers() Set up the stride device address regions pointing at the shader identifiers in the shader binding table */ - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); VkStridedDeviceAddressRegionKHR raygen_shader_sbt_entry{}; raygen_shader_sbt_entry.deviceAddress = get_buffer_device_address(raygen_shader_binding_table->get_handle()); @@ -1332,10 +1297,10 @@ void RaytracingExtended::build_command_buffers() barriers.emplace_back(getBufferBarrier(*instances_buffer)); barriers.emplace_back(getBufferBarrier(*ubo)); - vkCmdPipelineBarrier(raytracing_command_buffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR | VK_PIPELINE_STAGE_HOST_BIT, 0, - 0, VK_NULL_HANDLE, // memory barrier - static_cast(barriers.size()), barriers.data(), // buffer memory barrier - 0, VK_NULL_HANDLE); // image memory barrier + vkCmdPipelineBarrier(raytracing_command_buffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, + VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR | VK_PIPELINE_STAGE_HOST_BIT, 0, 0, VK_NULL_HANDLE, // memory barrier + static_cast(barriers.size()), barriers.data(), // buffer memory barrier + 0, VK_NULL_HANDLE); // image memory barrier /* Dispatch the ray tracing commands @@ -1343,15 +1308,8 @@ void RaytracingExtended::build_command_buffers() vkCmdBindPipeline(raytracing_command_buffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline); vkCmdBindDescriptorSets(raytracing_command_buffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr); - vkCmdTraceRaysKHR( - raytracing_command_buffer, - &raygen_shader_sbt_entry, - &miss_shader_sbt_entry, - &hit_shader_sbt_entry, - &callable_shader_sbt_entry, - width, - height, - 1); + vkCmdTraceRaysKHR(raytracing_command_buffer, &raygen_shader_sbt_entry, &miss_shader_sbt_entry, &hit_shader_sbt_entry, &callable_shader_sbt_entry, width, + height, 1); VK_CHECK(vkEndCommandBuffer(raytracing_command_buffer)); } @@ -1435,26 +1393,13 @@ void RaytracingExtended::draw() Copy ray tracing output to swap chain image */ // Prepare current swap chain image as transfer destination - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, {}, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Prepare ray tracing output image as transfer source - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {}, + VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); VkImageCopy copy_region{}; copy_region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; @@ -1462,25 +1407,16 @@ void RaytracingExtended::draw() copy_region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; copy_region.dstOffset = {0, 0, 0}; copy_region.extent = {width, height, 1}; - vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, get_render_context().get_swapchain().get_images()[i], + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); // Transition swap chain image back for presentation - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); // Transition ray tracing output image back to general layout - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - {}, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_IMAGE_LAYOUT_GENERAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_TRANSFER_READ_BIT, {}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresource_range); VK_CHECK(vkEndCommandBuffer(draw_cmd_buffers[i])); submit_info.commandBufferCount = 1; @@ -1561,9 +1497,7 @@ RaytracingExtended::RaytracingScene::RaytracingScene(vkb::core::DeviceC &device, if (is_vase) { const float sponza_scale = 0.01f; - transform = glm::mat3x4{0.f, 0.f, sponza_scale, 4.3f, - sponza_scale, 0.f, 0.f, 0.f, - 0.f, sponza_scale, 0.f, 9.5f}; + transform = glm::mat3x4{0.f, 0.f, sponza_scale, 4.3f, sponza_scale, 0.f, 0.f, 0.f, 0.f, sponza_scale, 0.f, 9.5f}; } for (auto &&pt : pts_) { @@ -1597,15 +1531,12 @@ RaytracingExtended::RaytracingScene::RaytracingScene(vkb::core::DeviceC &device, memcpy(&tempBuffer[0], ptr, sz); for (size_t i = 0; i < nTriangles; ++i) { - model.triangles[i] = {static_cast(tempBuffer[3 * i]), - static_cast(tempBuffer[3 * i + 1]), + model.triangles[i] = {static_cast(tempBuffer[3 * i]), static_cast(tempBuffer[3 * i + 1]), static_cast(tempBuffer[3 * i + 2])}; } } - model.default_transform = VkTransformMatrixKHR{1.f, 0.f, 0.f, 0.f, - 0.f, 1.f, 0.f, 0.f, - 0.f, 0.f, 1.f, 0.f}; + model.default_transform = VkTransformMatrixKHR{1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f}; model.texture_index = textureIndex32; model.object_type = scenesToLoad[sceneIndex].object_type; models.emplace_back(std::move(model)); diff --git a/samples/extensions/ray_tracing_extended/ray_tracing_extended.h b/samples/extensions/ray_tracing_extended/ray_tracing_extended.h index 7fc709e746..cc7c683834 100644 --- a/samples/extensions/ray_tracing_extended/ray_tracing_extended.h +++ b/samples/extensions/ray_tracing_extended/ray_tracing_extended.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025 Holochip Corporation +/* Copyright (c) 2021-2026 Holochip Corporation * * SPDX-License-Identifier: Apache-2.0 * @@ -76,10 +76,15 @@ class RaytracingExtended : public ApiVulkanSample FlameParticleGenerator() = default; FlameParticleGenerator(glm::vec3 generator_origin, glm::vec3 generator_direction, float generator_radius, size_t n_particles) : - origin(generator_origin), direction(generator_direction), radius(generator_radius), n_particles(n_particles), generator(std::chrono::system_clock::now().time_since_epoch().count()) + origin(generator_origin), + direction(generator_direction), + radius(generator_radius), + n_particles(n_particles), + generator(std::chrono::system_clock::now().time_since_epoch().count()) { using namespace glm; - u = normalize(abs(dot(generator_direction, vec3(0, 0, 1))) > 0.9f ? cross(generator_direction, vec3(1, 0, 0)) : cross(generator_direction, vec3(0, 0, 1))); + u = normalize(abs(dot(generator_direction, vec3(0, 0, 1))) > 0.9f ? cross(generator_direction, vec3(1, 0, 0)) : + cross(generator_direction, vec3(0, 0, 1))); v = normalize(cross(generator_direction, u)); for (size_t i = 0; i < n_particles; ++i) @@ -109,10 +114,10 @@ class RaytracingExtended : public ApiVulkanSample } void update_particles(float time_delta) { - particles.erase(std::remove_if(particles.begin(), particles.end(), [this, lifetime{this->lifetime}](const FlameParticle &particle) { - return particle.duration > (generate_random() * lifetime); - }), - particles.end()); + particles.erase( + std::remove_if(particles.begin(), particles.end(), + [this, lifetime{this->lifetime}](const FlameParticle &particle) { return particle.duration > (generate_random() * lifetime); }), + particles.end()); for (auto &&particle : particles) { @@ -184,8 +189,7 @@ class RaytracingExtended : public ApiVulkanSample struct SceneLoadInfo { SceneLoadInfo() = default; - SceneLoadInfo(const char *filename, glm::mat3x4 transform, uint32_t object_type) : - filename(filename), transform(transform), object_type(object_type) + SceneLoadInfo(const char *filename, glm::mat3x4 transform, uint32_t object_type) : filename(filename), transform(transform), object_type(object_type) {} const char *filename = ""; glm::mat3x4 transform; @@ -227,8 +231,7 @@ class RaytracingExtended : public ApiVulkanSample VkFormat format; uint32_t width; uint32_t height; - StorageImage() : - memory(VK_NULL_HANDLE), image(VK_NULL_HANDLE), view(VK_NULL_HANDLE), format(), width(0), height(0) + StorageImage() : memory(VK_NULL_HANDLE), image(VK_NULL_HANDLE), view(VK_NULL_HANDLE), format(), width(0), height(0) {} } storage_image; diff --git a/samples/extensions/ray_tracing_invocation_reorder/ray_tracing_invocation_reorder.cpp b/samples/extensions/ray_tracing_invocation_reorder/ray_tracing_invocation_reorder.cpp index 4f9f24ab9d..f18c8b89e1 100644 --- a/samples/extensions/ray_tracing_invocation_reorder/ray_tracing_invocation_reorder.cpp +++ b/samples/extensions/ray_tracing_invocation_reorder/ray_tracing_invocation_reorder.cpp @@ -51,12 +51,7 @@ struct RaytracingInvocationReorder::Model VkTransformMatrixKHR default_transform; uint32_t texture_index; uint32_t object_type; - Model() : - default_transform({1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}), - texture_index(0), - object_type(0) + Model() : default_transform({1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}), texture_index(0), object_type(0) {} }; @@ -211,15 +206,8 @@ void RaytracingInvocationReorder::create_storage_image() VK_CHECK(vkCreateImageView(get_device().get_handle(), &color_image_view, nullptr, &storage_image.view)); VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkb::image_layout_transition(command_buffer, - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - {}, - {}, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_GENERAL, - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); + vkb::image_layout_transition(command_buffer, storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, {}, {}, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); get_device().flush_command_buffer(command_buffer, queue); } @@ -237,12 +225,8 @@ uint64_t RaytracingInvocationReorder::get_buffer_device_address(VkBuffer buffer) void RaytracingInvocationReorder::create_flame_model() { flame_texture = load_texture("textures/generated_flame.ktx", vkb::sg::Image::Color); - std::vector pts_ = {{0, 0, 0}, - {1, 0, 0}, - {1, 1, 0}, - {0, 1, 0}}; - std::vector indices_ = {{0, 1, 2}, - {0, 2, 3}}; + std::vector pts_ = {{0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}}; + std::vector indices_ = {{0, 1, 2}, {0, 2, 3}}; std::vector vertices; for (auto &pt : pts_) @@ -294,10 +278,11 @@ void RaytracingInvocationReorder::create_static_object_buffers() // Create a staging buffer. (If staging buffer use is disabled, then this will be the final buffer) std::unique_ptr staging_vertex_buffer = nullptr, staging_index_buffer = nullptr; - static constexpr VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; - const VkBufferUsageFlags staging_flags = scene_options.use_vertex_staging_buffer ? VK_BUFFER_USAGE_TRANSFER_SRC_BIT : buffer_usage_flags; - staging_vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); - staging_index_buffer = std::make_unique(get_device(), index_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + static constexpr VkBufferUsageFlags buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + const VkBufferUsageFlags staging_flags = scene_options.use_vertex_staging_buffer ? VK_BUFFER_USAGE_TRANSFER_SRC_BIT : buffer_usage_flags; + staging_vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + staging_index_buffer = std::make_unique(get_device(), index_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); // Copy over the data for each of the models for (size_t i = 0; i < models.size(); ++i) @@ -313,7 +298,8 @@ void RaytracingInvocationReorder::create_static_object_buffers() auto cmd = get_device().get_command_pool().request_command_buffer(); cmd->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, VK_NULL_HANDLE); auto copy = [this, &cmd](vkb::core::BufferC &staging_buffer) { - auto output_buffer = std::make_unique(get_device(), staging_buffer.get_size(), buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + auto output_buffer = std::make_unique(get_device(), staging_buffer.get_size(), + buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); cmd->copy_buffer(staging_buffer, *output_buffer, staging_buffer.get_size()); vkb::BufferMemoryBarrier barrier; @@ -377,52 +363,45 @@ void RaytracingInvocationReorder::create_bottom_level_acceleration_structure(boo { continue; } - const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; // Set up a single transformation matrix that can be used to transform the whole geometry for a single bottom level acceleration structure VkTransformMatrixKHR transform_matrix = model_buffer.default_transform; if (!model_buffer.transform_matrix_buffer || model_buffer.transform_matrix_buffer->get_size() != sizeof(transform_matrix)) { - model_buffer.transform_matrix_buffer = std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + model_buffer.transform_matrix_buffer = + std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); } model_buffer.transform_matrix_buffer->update(&transform_matrix, sizeof(transform_matrix)); if (model_buffer.bottom_level_acceleration_structure == nullptr) { - model_buffer.bottom_level_acceleration_structure = std::make_unique( - get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); + model_buffer.bottom_level_acceleration_structure = + std::make_unique(get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); model_buffer.object_id = model_buffer.bottom_level_acceleration_structure->add_triangle_geometry( - model_buffer.is_static ? *vertex_buffer : *dynamic_vertex_buffer, - model_buffer.is_static ? *index_buffer : *dynamic_index_buffer, - *model_buffer.transform_matrix_buffer, - static_cast(model_buffer.num_triangles), - static_cast(model_buffer.num_vertices) - 1, - sizeof(NewVertex), - 0, - VK_FORMAT_R32G32B32_SFLOAT, - VK_INDEX_TYPE_UINT32, - VK_GEOMETRY_OPAQUE_BIT_KHR, + model_buffer.is_static ? *vertex_buffer : *dynamic_vertex_buffer, model_buffer.is_static ? *index_buffer : *dynamic_index_buffer, + *model_buffer.transform_matrix_buffer, static_cast(model_buffer.num_triangles), static_cast(model_buffer.num_vertices) - 1, + sizeof(NewVertex), 0, VK_FORMAT_R32G32B32_SFLOAT, VK_INDEX_TYPE_UINT32, VK_GEOMETRY_OPAQUE_BIT_KHR, model_buffer.vertex_offset + (model_buffer.is_static ? static_vertex_handle : dynamic_vertex_handle), model_buffer.index_offset + (model_buffer.is_static ? static_index_handle : dynamic_index_handle)); } else { model_buffer.bottom_level_acceleration_structure->update_triangle_geometry( - model_buffer.object_id, - dynamic_vertex_buffer, - dynamic_index_buffer, - model_buffer.transform_matrix_buffer, - static_cast(model_buffer.num_triangles), - static_cast(model_buffer.num_vertices) - 1, - sizeof(NewVertex), - 0, VK_FORMAT_R32G32B32_SFLOAT, VK_GEOMETRY_OPAQUE_BIT_KHR, + model_buffer.object_id, dynamic_vertex_buffer, dynamic_index_buffer, model_buffer.transform_matrix_buffer, + static_cast(model_buffer.num_triangles), static_cast(model_buffer.num_vertices) - 1, sizeof(NewVertex), 0, + VK_FORMAT_R32G32B32_SFLOAT, VK_GEOMETRY_OPAQUE_BIT_KHR, model_buffer.vertex_offset + (model_buffer.is_static ? static_vertex_handle : dynamic_vertex_handle), model_buffer.index_offset + (model_buffer.is_static ? static_index_handle : dynamic_index_handle)); } - model_buffer.bottom_level_acceleration_structure->set_scrach_buffer_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment); - model_buffer.bottom_level_acceleration_structure->build(queue, - model_buffer.is_static ? VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR : VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR, - is_update ? VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR : VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); + model_buffer.bottom_level_acceleration_structure->set_scrach_buffer_alignment( + acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment); + model_buffer.bottom_level_acceleration_structure->build( + queue, + model_buffer.is_static ? VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR : + VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR, + is_update ? VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR : VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); } } @@ -441,10 +420,7 @@ VkTransformMatrixKHR RaytracingInvocationReorder::calculate_rotation(glm::vec3 p normal *= scale; u *= scale; v *= scale; - return { - u.x, v.x, normal.x, pt.x, - u.y, v.y, normal.y, pt.y, - u.z, v.z, normal.z, pt.z}; + return {u.x, v.x, normal.x, pt.x, u.y, v.y, normal.y, pt.y, u.z, v.z, normal.z, pt.z}; } /* @@ -456,10 +432,7 @@ void RaytracingInvocationReorder::create_top_level_acceleration_structure(bool p Often, good performance can be obtained when the TLAS uses PREFER_FAST_TRACE with full rebuilds. */ assert(!!raytracing_scene); - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // This buffer is used to correlate the instance information with model information // and is required because the number and type of instances is dynamic @@ -467,18 +440,18 @@ void RaytracingInvocationReorder::create_top_level_acceleration_structure(bool p // Add the instances for the static scene, billboard texture, and refraction model std::vector instances; - auto add_instance = [&](ModelBuffer &model_buffer, const VkTransformMatrixKHR &transform_matrix, uint32_t instance_index) { - VkAccelerationStructureInstanceKHR acceleration_structure_instance{}; - acceleration_structure_instance.transform = transform_matrix; - acceleration_structure_instance.instanceCustomIndex = instance_index; - acceleration_structure_instance.mask = 0xFF; - // Use object_type to select the appropriate hit group shader - // This creates shader divergence that SER can optimize by reordering threads - // Hit group 0 = OBJECT_NORMAL, Hit group 1 = OBJECT_REFRACTION, Hit group 2 = OBJECT_FLAME - acceleration_structure_instance.instanceShaderBindingTableRecordOffset = model_buffer.object_type; - acceleration_structure_instance.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR; - acceleration_structure_instance.accelerationStructureReference = model_buffer.bottom_level_acceleration_structure->get_device_address(); - instances.emplace_back(acceleration_structure_instance); + auto add_instance = [&](ModelBuffer &model_buffer, const VkTransformMatrixKHR &transform_matrix, uint32_t instance_index) { + VkAccelerationStructureInstanceKHR acceleration_structure_instance{}; + acceleration_structure_instance.transform = transform_matrix; + acceleration_structure_instance.instanceCustomIndex = instance_index; + acceleration_structure_instance.mask = 0xFF; + // Use object_type to select the appropriate hit group shader + // This creates shader divergence that SER can optimize by reordering threads + // Hit group 0 = OBJECT_NORMAL, Hit group 1 = OBJECT_REFRACTION, Hit group 2 = OBJECT_FLAME + acceleration_structure_instance.instanceShaderBindingTableRecordOffset = model_buffer.object_type; + acceleration_structure_instance.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR; + acceleration_structure_instance.accelerationStructureReference = model_buffer.bottom_level_acceleration_structure->get_device_address(); + instances.emplace_back(acceleration_structure_instance); }; for (size_t i = 0; i < raytracing_scene->model_buffers.size(); ++i) @@ -490,7 +463,8 @@ void RaytracingInvocationReorder::create_top_level_acceleration_structure(bool p scene_instance.indices_index = static_cast(model_buffer.index_offset / sizeof(Triangle)); scene_instance.object_type = model_buffer.object_type; scene_instance.image_index = model_buffer.texture_index; - ASSERT_LOG(scene_instance.object_type == ObjectType::OBJECT_REFRACTION || scene_instance.image_index < raytracing_scene->imageInfos.size(), "Only the refraction model can be texture less.") + ASSERT_LOG(scene_instance.object_type == ObjectType::OBJECT_REFRACTION || scene_instance.image_index < raytracing_scene->imageInfos.size(), + "Only the refraction model can be texture less.") model_instance_data.emplace_back(scene_instance); // these objects have a single instance with the identity transform @@ -511,9 +485,7 @@ void RaytracingInvocationReorder::create_top_level_acceleration_structure(bool p { // find the flame particle object, then add the particles as instances auto &model_buffers = raytracing_scene->model_buffers; - auto iter = std::ranges::find_if(model_buffers, [](const ModelBuffer &model_buffer) { - return model_buffer.object_type == ObjectType::OBJECT_FLAME; - }); + auto iter = std::ranges::find_if(model_buffers, [](const ModelBuffer &model_buffer) { return model_buffer.object_type == ObjectType::OBJECT_FLAME; }); ASSERT_LOG(iter != model_buffers.cend(), "Can't find flame object.") auto &model_buffer = *iter; uint32_t index = static_cast(std::distance(model_buffers.begin(), iter)); @@ -526,17 +498,17 @@ void RaytracingInvocationReorder::create_top_level_acceleration_structure(bool p size_t data_to_model_size = model_instance_data.size() * sizeof(model_instance_data[0]); if (!data_to_model_buffer || data_to_model_buffer->get_size() < data_to_model_size) { - data_to_model_buffer = std::make_unique(get_device(), data_to_model_size, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + data_to_model_buffer = std::make_unique( + get_device(), data_to_model_size, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } data_to_model_buffer->update(model_instance_data.data(), data_to_model_size, 0); const size_t instancesDataSize = sizeof(VkAccelerationStructureInstanceKHR) * instances.size(); if (!instances_buffer || instances_buffer->get_size() != instancesDataSize) { - instances_buffer = std::make_unique(get_device(), - instancesDataSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + instances_buffer = std::make_unique( + get_device(), instancesDataSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); } instances_buffer->update(instances.data(), instancesDataSize); @@ -599,10 +571,7 @@ void RaytracingInvocationReorder::create_scene() refraction_indices.resize(2 * grid_size * grid_size); std::vector scenesToLoad; const float sponza_scale = 0.01f; - const glm::mat4x4 sponza_transform{0.f, 0.f, sponza_scale, 0.f, - sponza_scale, 0.f, 0.f, 0.f, - 0.f, sponza_scale, 0.f, 0.f, - 0.f, 0.f, 0.f, 1.f}; + const glm::mat4x4 sponza_transform{0.f, 0.f, sponza_scale, 0.f, sponza_scale, 0.f, 0.f, 0.f, 0.f, sponza_scale, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f}; scenesToLoad.emplace_back("scenes/sponza/Sponza01.gltf", sponza_transform, ObjectType::OBJECT_NORMAL); raytracing_scene = std::make_unique(get_device(), std::move(scenesToLoad)); @@ -630,12 +599,14 @@ void RaytracingInvocationReorder::create_scene() void RaytracingInvocationReorder::create_shader_binding_tables() { - const uint32_t handle_size = ray_tracing_pipeline_properties.shaderGroupHandleSize; - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); - auto group_count = static_cast(shader_groups.size()); - const uint32_t sbt_size = group_count * handle_size_aligned; - const VkBufferUsageFlags sbt_buffer_usage_flags = VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + const uint32_t handle_size = ray_tracing_pipeline_properties.shaderGroupHandleSize; + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + auto group_count = static_cast(shader_groups.size()); + const uint32_t sbt_size = group_count * handle_size_aligned; + const VkBufferUsageFlags sbt_buffer_usage_flags = + VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; // Number of hit groups (one per object type for SER demonstration) const uint32_t hit_group_count = 3; // OBJECT_NORMAL, OBJECT_REFRACTION, OBJECT_FLAME @@ -644,7 +615,8 @@ void RaytracingInvocationReorder::create_shader_binding_tables() // Hit shader binding table needs space for all 3 hit groups raygen_shader_binding_table = std::make_unique(get_device(), handle_size_aligned, sbt_buffer_usage_flags, sbt_memory_usage, 0); miss_shader_binding_table = std::make_unique(get_device(), handle_size_aligned, sbt_buffer_usage_flags, sbt_memory_usage, 0); - hit_shader_binding_table = std::make_unique(get_device(), handle_size_aligned * hit_group_count, sbt_buffer_usage_flags, sbt_memory_usage, 0); + hit_shader_binding_table = + std::make_unique(get_device(), handle_size_aligned * hit_group_count, sbt_buffer_usage_flags, sbt_memory_usage, 0); // Copy the pipeline's shader handles into a host buffer std::vector shader_handle_storage(sbt_size); @@ -675,14 +647,13 @@ void RaytracingInvocationReorder::create_shader_binding_tables() */ void RaytracingInvocationReorder::create_descriptor_sets() { - std::vector pool_sizes = { - {VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, - {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast(raytracing_scene->imageInfos.size())}}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 1); + std::vector pool_sizes = {{VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, + {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5}, + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}, + {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast(raytracing_scene->imageInfos.size())}}; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 1); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); VkDescriptorSetAllocateInfo descriptor_set_allocate_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); @@ -715,25 +686,24 @@ void RaytracingInvocationReorder::create_descriptor_sets() VkDescriptorBufferInfo dynamic_index_descriptor = create_descriptor(*dynamic_index_buffer); VkDescriptorBufferInfo data_map_descriptor = create_descriptor(*data_to_model_buffer); - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); - VkWriteDescriptorSet uniform_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); - VkWriteDescriptorSet vertex_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4, &vertex_descriptor); - VkWriteDescriptorSet index_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5, &index_descriptor); - VkWriteDescriptorSet data_map_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 6, &data_map_descriptor); - VkWriteDescriptorSet texture_array_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 7, raytracing_scene->imageInfos.data(), static_cast(raytracing_scene->imageInfos.size())); - VkWriteDescriptorSet dynamic_vertex_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 8, &dynamic_vertex_descriptor); - VkWriteDescriptorSet dynamic_index_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 9, &dynamic_index_descriptor); - - std::vector write_descriptor_sets = { - acceleration_structure_write, - result_image_write, - uniform_buffer_write, - vertex_buffer_write, - index_buffer_write, - data_map_write, - texture_array_write, - dynamic_vertex_buffer_write, - dynamic_index_buffer_write}; + VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + VkWriteDescriptorSet uniform_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); + VkWriteDescriptorSet vertex_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4, &vertex_descriptor); + VkWriteDescriptorSet index_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 5, &index_descriptor); + VkWriteDescriptorSet data_map_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 6, &data_map_descriptor); + VkWriteDescriptorSet texture_array_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 7, raytracing_scene->imageInfos.data(), + static_cast(raytracing_scene->imageInfos.size())); + VkWriteDescriptorSet dynamic_vertex_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 8, &dynamic_vertex_descriptor); + VkWriteDescriptorSet dynamic_index_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 9, &dynamic_index_descriptor); + + std::vector write_descriptor_sets = {acceleration_structure_write, result_image_write, uniform_buffer_write, + vertex_buffer_write, index_buffer_write, data_map_write, + texture_array_write, dynamic_vertex_buffer_write, dynamic_index_buffer_write}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); } @@ -747,9 +717,7 @@ void RaytracingInvocationReorder::create_dynamic_object_buffers(float time) const float y = static_cast(j) / static_cast(grid_size); const float lateral_scale = std::min(std::min(std::min(std::min(x, 1 - x), y), 1 - y), 0.2f) * 5.f; refraction_model[grid_size * i + j].normal = {0.f, 0.f, 0.f}; - refraction_model[grid_size * i + j].pos = {y - 0.5f, - 2 * x - 1.f, - lateral_scale * 0.025f * cos(2 * 3.14159 * (4 * x + time / 2))}; + refraction_model[grid_size * i + j].pos = {y - 0.5f, 2 * x - 1.f, lateral_scale * 0.025f * cos(2 * 3.14159 * (4 * x + time / 2))}; refraction_model[grid_size * i + j].tex_coord = glm::vec2{x, y}; if (i + 1 < grid_size && j + 1 < grid_size) @@ -761,7 +729,8 @@ void RaytracingInvocationReorder::create_dynamic_object_buffers(float time) } for (auto &&tri : refraction_indices) { - glm::vec3 normal = glm::normalize(glm::cross(refraction_model[tri[1]].pos - refraction_model[tri[0]].pos, refraction_model[tri[2]].pos - refraction_model[tri[0]].pos)); + glm::vec3 normal = glm::normalize( + glm::cross(refraction_model[tri[1]].pos - refraction_model[tri[0]].pos, refraction_model[tri[2]].pos - refraction_model[tri[0]].pos)); for (auto &&index : tri) { ASSERT_LOG(index >= 0 && index < refraction_model.size(), "Valid tri") @@ -780,8 +749,16 @@ void RaytracingInvocationReorder::create_dynamic_object_buffers(float time) if (!dynamic_vertex_buffer || !dynamic_index_buffer) { // note these flags are different because they will be read/write, in contrast to static - dynamic_vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); - dynamic_index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + dynamic_vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); + dynamic_index_buffer = std::make_unique(get_device(), index_buffer_size, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); } dynamic_vertex_buffer->update(refraction_model.data(), vertex_buffer_size); @@ -886,16 +863,15 @@ void RaytracingInvocationReorder::create_ray_tracing_pipeline() dynamic_index_binding.descriptorCount = 1; dynamic_index_binding.stageFlags = VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR; - std::vector bindings = { - acceleration_structure_layout_binding, - result_image_layout_binding, - uniform_buffer_binding, - vertex_binding, - index_binding, - data_map_binding, - texture_array_binding, - dynamic_vertex_binding, - dynamic_index_binding}; + std::vector bindings = {acceleration_structure_layout_binding, + result_image_layout_binding, + uniform_buffer_binding, + vertex_binding, + index_binding, + data_map_binding, + texture_array_binding, + dynamic_vertex_binding, + dynamic_index_binding}; VkDescriptorSetLayoutCreateInfo layout_info{}; layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; @@ -1001,7 +977,8 @@ void RaytracingInvocationReorder::create_ray_tracing_pipeline() raytracing_pipeline_create_info.pGroups = shader_groups.data(); raytracing_pipeline_create_info.maxPipelineRayRecursionDepth = 1; raytracing_pipeline_create_info.layout = pipeline_layout; - VK_CHECK(vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); + VK_CHECK( + vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); } #ifndef USE_FRAMEWORK_ACCELERATION_STRUCTURE @@ -1026,10 +1003,7 @@ void RaytracingInvocationReorder::delete_acceleration_structure(AccelerationStru */ void RaytracingInvocationReorder::create_uniform_buffer() { - ubo = std::make_unique(get_device(), - sizeof(uniform_data), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + ubo = std::make_unique(get_device(), sizeof(uniform_data), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); ubo->convert_and_update(uniform_data); update_uniform_buffers(); } @@ -1048,9 +1022,10 @@ void RaytracingInvocationReorder::build_command_buffers() create_storage_image(); // The descriptor also needs to be updated to reference the new image VkDescriptorImageInfo image_descriptor{}; - image_descriptor.imageView = storage_image.view; - image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + image_descriptor.imageView = storage_image.view; + image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; + VkWriteDescriptorSet result_image_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); vkUpdateDescriptorSets(get_device().get_handle(), 1, &result_image_write, 0, VK_NULL_HANDLE); } @@ -1078,7 +1053,8 @@ void RaytracingInvocationReorder::build_command_buffers() Set up the stride device address regions pointing at the shader identifiers in the shader binding table */ - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); VkStridedDeviceAddressRegionKHR raygen_shader_sbt_entry{}; raygen_shader_sbt_entry.deviceAddress = get_buffer_device_address(raygen_shader_binding_table->get_handle()); @@ -1126,10 +1102,10 @@ void RaytracingInvocationReorder::build_command_buffers() barriers.emplace_back(getBufferBarrier(*instances_buffer)); barriers.emplace_back(getBufferBarrier(*ubo)); - vkCmdPipelineBarrier(raytracing_command_buffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR | VK_PIPELINE_STAGE_HOST_BIT, 0, - 0, VK_NULL_HANDLE, // memory barrier - static_cast(barriers.size()), barriers.data(), // buffer memory barrier - 0, VK_NULL_HANDLE); // image memory barrier + vkCmdPipelineBarrier(raytracing_command_buffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, + VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR | VK_PIPELINE_STAGE_HOST_BIT, 0, 0, VK_NULL_HANDLE, // memory barrier + static_cast(barriers.size()), barriers.data(), // buffer memory barrier + 0, VK_NULL_HANDLE); // image memory barrier /* Dispatch the ray tracing commands @@ -1137,15 +1113,8 @@ void RaytracingInvocationReorder::build_command_buffers() vkCmdBindPipeline(raytracing_command_buffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline); vkCmdBindDescriptorSets(raytracing_command_buffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline_layout, 0, 1, &descriptor_set, 0, nullptr); - vkCmdTraceRaysKHR( - raytracing_command_buffer, - &raygen_shader_sbt_entry, - &miss_shader_sbt_entry, - &hit_shader_sbt_entry, - &callable_shader_sbt_entry, - width, - height, - 1); + vkCmdTraceRaysKHR(raytracing_command_buffer, &raygen_shader_sbt_entry, &miss_shader_sbt_entry, &hit_shader_sbt_entry, &callable_shader_sbt_entry, width, + height, 1); VK_CHECK(vkEndCommandBuffer(raytracing_command_buffer)); } @@ -1157,7 +1126,8 @@ void RaytracingInvocationReorder::update_uniform_buffers() uniform_data.view_inverse = glm::inverse(camera.matrices.view); uniform_data.enable_ser = ser_enabled ? 1 : 0; uniform_data.use_coherence_hint = coherence_hint_enabled ? 1 : 0; - uniform_data.time = static_cast(std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - start).count()) / 1000000.0f; + uniform_data.time = + static_cast(std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - start).count()) / 1000000.0f; ubo->convert_and_update(uniform_data); } @@ -1183,8 +1153,8 @@ bool RaytracingInvocationReorder::prepare(const vkb::ApplicationOptions &options // Get the ray tracing pipeline properties, which we'll need later on in the sample ray_tracing_pipeline_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR; VkPhysicalDeviceProperties2 device_properties{}; - device_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; - device_properties.pNext = &ray_tracing_pipeline_properties; + device_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; + device_properties.pNext = &ray_tracing_pipeline_properties; ray_tracing_pipeline_properties.pNext = &acceleration_structure_properties; vkGetPhysicalDeviceProperties2(get_device().get_gpu().get_handle(), &device_properties); @@ -1270,26 +1240,13 @@ void RaytracingInvocationReorder::draw() Copy ray tracing output to swap chain image */ // Prepare current swap chain image as transfer destination - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, {}, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Prepare ray tracing output image as transfer source - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {}, + VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); VkImageCopy copy_region{}; copy_region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; @@ -1297,30 +1254,17 @@ void RaytracingInvocationReorder::draw() copy_region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; copy_region.dstOffset = {0, 0, 0}; copy_region.extent = {width, height, 1}; - vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, get_render_context().get_swapchain().get_images()[i], + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); // Transition swap chain image for render pass (render pass expects PRESENT_SRC_KHR as initial layout) - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, subresource_range); // Transition ray tracing output image back to general layout - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - {}, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_IMAGE_LAYOUT_GENERAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_TRANSFER_READ_BIT, {}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresource_range); // Begin render pass for UI rendering // Note: Even though we use ColorAttachmentLoad, the depth attachment still uses CLEAR, @@ -1441,9 +1385,7 @@ RaytracingInvocationReorder::RaytracingScene::RaytracingScene(vkb::core::DeviceC if (is_vase) { const float sponza_scale = 0.01f; - transform = glm::mat3x4{0.f, 0.f, sponza_scale, 4.3f, - sponza_scale, 0.f, 0.f, 0.f, - 0.f, sponza_scale, 0.f, 9.5f}; + transform = glm::mat3x4{0.f, 0.f, sponza_scale, 4.3f, sponza_scale, 0.f, 0.f, 0.f, 0.f, sponza_scale, 0.f, 9.5f}; } for (auto &&pt : pts_) { @@ -1477,15 +1419,12 @@ RaytracingInvocationReorder::RaytracingScene::RaytracingScene(vkb::core::DeviceC memcpy(&tempBuffer[0], ptr, sz); for (size_t i = 0; i < nTriangles; ++i) { - model.triangles[i] = {static_cast(tempBuffer[3 * i]), - static_cast(tempBuffer[3 * i + 1]), + model.triangles[i] = {static_cast(tempBuffer[3 * i]), static_cast(tempBuffer[3 * i + 1]), static_cast(tempBuffer[3 * i + 2])}; } } - model.default_transform = VkTransformMatrixKHR{1.f, 0.f, 0.f, 0.f, - 0.f, 1.f, 0.f, 0.f, - 0.f, 0.f, 1.f, 0.f}; + model.default_transform = VkTransformMatrixKHR{1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f}; model.texture_index = textureIndex32; model.object_type = scenesToLoad[sceneIndex].object_type; models.emplace_back(std::move(model)); diff --git a/samples/extensions/ray_tracing_invocation_reorder/ray_tracing_invocation_reorder.h b/samples/extensions/ray_tracing_invocation_reorder/ray_tracing_invocation_reorder.h index 598e58a181..8ecb10fc45 100644 --- a/samples/extensions/ray_tracing_invocation_reorder/ray_tracing_invocation_reorder.h +++ b/samples/extensions/ray_tracing_invocation_reorder/ray_tracing_invocation_reorder.h @@ -33,7 +33,8 @@ class RaytracingInvocationReorder : public ApiVulkanSample VkPhysicalDeviceRayTracingPipelinePropertiesKHR ray_tracing_pipeline_properties{}; VkPhysicalDeviceAccelerationStructureFeaturesKHR acceleration_structure_features{}; // Acceleration structure properties. - VkPhysicalDeviceAccelerationStructurePropertiesKHR acceleration_structure_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_PROPERTIES_KHR}; + VkPhysicalDeviceAccelerationStructurePropertiesKHR acceleration_structure_properties{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_PROPERTIES_KHR}; #ifdef VK_EXT_ray_tracing_invocation_reorder VkPhysicalDeviceRayTracingInvocationReorderPropertiesEXT invocation_reorder_properties_ext{}; #endif @@ -76,10 +77,15 @@ class RaytracingInvocationReorder : public ApiVulkanSample FlameParticleGenerator() = default; FlameParticleGenerator(glm::vec3 generator_origin, glm::vec3 generator_direction, float generator_radius, size_t n_particles) : - origin(generator_origin), direction(generator_direction), radius(generator_radius), n_particles(n_particles), generator(std::chrono::system_clock::now().time_since_epoch().count()) + origin(generator_origin), + direction(generator_direction), + radius(generator_radius), + n_particles(n_particles), + generator(std::chrono::system_clock::now().time_since_epoch().count()) { using namespace glm; - u = normalize(abs(dot(generator_direction, vec3(0, 0, 1))) > 0.9f ? cross(generator_direction, vec3(1, 0, 0)) : cross(generator_direction, vec3(0, 0, 1))); + u = normalize(abs(dot(generator_direction, vec3(0, 0, 1))) > 0.9f ? cross(generator_direction, vec3(1, 0, 0)) : + cross(generator_direction, vec3(0, 0, 1))); v = normalize(cross(generator_direction, u)); for (size_t i = 0; i < n_particles; ++i) @@ -109,10 +115,10 @@ class RaytracingInvocationReorder : public ApiVulkanSample } void update_particles(float time_delta) { - particles.erase(std::remove_if(particles.begin(), particles.end(), [this, lifetime{this->lifetime}](const FlameParticle &particle) { - return particle.duration > (generate_random() * lifetime); - }), - particles.end()); + particles.erase( + std::remove_if(particles.begin(), particles.end(), + [this, lifetime{this->lifetime}](const FlameParticle &particle) { return particle.duration > (generate_random() * lifetime); }), + particles.end()); for (auto &&particle : particles) { @@ -180,8 +186,7 @@ class RaytracingInvocationReorder : public ApiVulkanSample struct SceneLoadInfo { SceneLoadInfo() = default; - SceneLoadInfo(const char *filename, glm::mat3x4 transform, uint32_t object_type) : - filename(filename), transform(transform), object_type(object_type) + SceneLoadInfo(const char *filename, glm::mat3x4 transform, uint32_t object_type) : filename(filename), transform(transform), object_type(object_type) {} const char *filename = ""; glm::mat3x4 transform; @@ -223,8 +228,7 @@ class RaytracingInvocationReorder : public ApiVulkanSample VkFormat format; uint32_t width; uint32_t height; - StorageImage() : - memory(VK_NULL_HANDLE), image(VK_NULL_HANDLE), view(VK_NULL_HANDLE), format(), width(0), height(0) + StorageImage() : memory(VK_NULL_HANDLE), image(VK_NULL_HANDLE), view(VK_NULL_HANDLE), format(), width(0), height(0) {} } storage_image; diff --git a/samples/extensions/ray_tracing_position_fetch/ray_tracing_position_fetch.cpp b/samples/extensions/ray_tracing_position_fetch/ray_tracing_position_fetch.cpp index 63bfc13f95..071b057560 100644 --- a/samples/extensions/ray_tracing_position_fetch/ray_tracing_position_fetch.cpp +++ b/samples/extensions/ray_tracing_position_fetch/ray_tracing_position_fetch.cpp @@ -122,15 +122,8 @@ void RayTracingPositionFetch::create_storage_image() VK_CHECK(vkCreateImageView(get_device().get_handle(), &color_image_view, nullptr, &storage_image.view)); VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkb::image_layout_transition(command_buffer, - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - {}, - {}, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_GENERAL, - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); + vkb::image_layout_transition(command_buffer, storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, {}, {}, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); get_device().flush_command_buffer(command_buffer, queue); } @@ -141,17 +134,18 @@ void RayTracingPositionFetch::create_bottom_level_acceleration_structure() { // Setup a single transformation matrix that can be used to transform the whole geometry for a single bottom level acceleration structure // Note: We flip the Y-Axis to match the glTF coordinate system and also offset the model to center it - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, -1.0f, 0.0f, 2.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; - std::unique_ptr transform_matrix_buffer = std::make_unique(get_device(), sizeof(transform_matrix), VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 2.0f, 0.0f, 0.0f, 1.0f, 0.0f}; + std::unique_ptr transform_matrix_buffer = std::make_unique( + get_device(), sizeof(transform_matrix), + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); transform_matrix_buffer->update(&transform_matrix, sizeof(transform_matrix)); bottom_level_acceleration_structure = std::make_unique(get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); - // For ray tracing, the vertex and index buffers of the glTF scene need to be used for acceleration structure builds and getting device addresses, so we provide additional flags in this sample - const VkBufferUsageFlags additional_buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + // For ray tracing, the vertex and index buffers of the glTF scene need to be used for acceleration structure builds and getting device addresses, so we + // provide additional flags in this sample + const VkBufferUsageFlags additional_buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; // Add all parts of the glTF scene to the bottom level architecture vkb::GLTFLoader loader{get_device()}; @@ -167,22 +161,16 @@ void RayTracingPositionFetch::create_bottom_level_acceleration_structure() vkb::sg::VertexAttribute attrib; sub_mesh->get_attribute("position", attrib); - bottom_level_acceleration_structure->add_triangle_geometry( - sub_mesh->vertex_buffers.at("position"), - *sub_mesh->index_buffer, - *transform_matrix_buffer, - num_triangles, - num_vertices, - attrib.stride, - 0, - attrib.format, - sub_mesh->index_type, - VK_GEOMETRY_OPAQUE_BIT_KHR); + bottom_level_acceleration_structure->add_triangle_geometry(sub_mesh->vertex_buffers.at("position"), *sub_mesh->index_buffer, + *transform_matrix_buffer, num_triangles, num_vertices, attrib.stride, 0, attrib.format, + sub_mesh->index_type, VK_GEOMETRY_OPAQUE_BIT_KHR); } } bottom_level_acceleration_structure->set_scrach_buffer_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment); - // To access vertex positions from a shader, we need to set the VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_DATA_ACCESS_KHR for the bottom level acceleration structure - VkBuildAccelerationStructureFlagsKHR acceleration_build_flags = VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_DATA_ACCESS_KHR | VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; + // To access vertex positions from a shader, we need to set the VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_DATA_ACCESS_KHR for the bottom level acceleration + // structure + VkBuildAccelerationStructureFlagsKHR acceleration_build_flags = + VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_DATA_ACCESS_KHR | VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; bottom_level_acceleration_structure->build(queue, acceleration_build_flags, VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); } @@ -191,10 +179,7 @@ void RayTracingPositionFetch::create_bottom_level_acceleration_structure() */ void RayTracingPositionFetch::create_top_level_acceleration_structure() { - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; VkAccelerationStructureInstanceKHR acceleration_structure_instance{}; acceleration_structure_instance.transform = transform_matrix; @@ -204,10 +189,9 @@ void RayTracingPositionFetch::create_top_level_acceleration_structure() acceleration_structure_instance.flags = VK_GEOMETRY_INSTANCE_TRIANGLE_FACING_CULL_DISABLE_BIT_KHR; acceleration_structure_instance.accelerationStructureReference = bottom_level_acceleration_structure->get_device_address(); - std::unique_ptr instances_buffer = std::make_unique(get_device(), - sizeof(VkAccelerationStructureInstanceKHR), - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr instances_buffer = std::make_unique( + get_device(), sizeof(VkAccelerationStructureInstanceKHR), + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); instances_buffer->update(&acceleration_structure_instance, sizeof(VkAccelerationStructureInstanceKHR)); top_level_acceleration_structure = std::make_unique(get_device(), VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR); @@ -246,27 +230,32 @@ inline uint32_t aligned_size(uint32_t value, uint32_t alignment) void RayTracingPositionFetch::create_shader_binding_tables() { - const uint32_t handle_size = ray_tracing_pipeline_properties.shaderGroupHandleSize; - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); - const uint32_t group_count = static_cast(shader_groups.size()); - const uint32_t sbt_size = group_count * handle_size_aligned; - const VkBufferUsageFlags sbt_buffer_usage_flags = VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + const uint32_t handle_size = ray_tracing_pipeline_properties.shaderGroupHandleSize; + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + const uint32_t group_count = static_cast(shader_groups.size()); + const uint32_t sbt_size = group_count * handle_size_aligned; + const VkBufferUsageFlags sbt_buffer_usage_flags = + VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; // Raygen // Create binding table buffers for each shader type - raygen_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); - miss_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); - hit_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + raygen_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + miss_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + hit_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); // Copy the pipeline's shader handles into a host buffer std::vector shader_handle_storage(sbt_size); @@ -290,9 +279,7 @@ void RayTracingPositionFetch::create_shader_binding_tables() void RayTracingPositionFetch::create_descriptor_sets() { std::vector pool_sizes = { - {VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}}; + {VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 1); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); @@ -322,13 +309,11 @@ void RayTracingPositionFetch::create_descriptor_sets() VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*ubo); - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); - VkWriteDescriptorSet uniform_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); + VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + VkWriteDescriptorSet uniform_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); - std::vector write_descriptor_sets = { - acceleration_structure_write, - result_image_write, - uniform_buffer_write}; + std::vector write_descriptor_sets = {acceleration_structure_write, result_image_write, uniform_buffer_write}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); } @@ -340,7 +325,8 @@ void RayTracingPositionFetch::create_ray_tracing_pipeline() std::vector bindings = { vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, VK_SHADER_STAGE_RAYGEN_BIT_KHR, 0, 1), vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_RAYGEN_BIT_KHR, 1, 1), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, 2, 1)}; + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR, 2, 1)}; VkDescriptorSetLayoutCreateInfo layout_info = vkb::initializers::descriptor_set_layout_create_info(bindings.data(), static_cast(bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &layout_info, nullptr, &descriptor_set_layout)); @@ -398,7 +384,8 @@ void RayTracingPositionFetch::create_ray_tracing_pipeline() raytracing_pipeline_create_info.pGroups = shader_groups.data(); raytracing_pipeline_create_info.maxPipelineRayRecursionDepth = 1; raytracing_pipeline_create_info.layout = pipeline_layout; - VK_CHECK(vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); + VK_CHECK( + vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); } /* @@ -425,9 +412,10 @@ void RayTracingPositionFetch::build_command_buffers() create_storage_image(); // The descriptor also needs to be updated to reference the new image VkDescriptorImageInfo image_descriptor{}; - image_descriptor.imageView = storage_image.view; - image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + image_descriptor.imageView = storage_image.view; + image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; + VkWriteDescriptorSet result_image_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); vkUpdateDescriptorSets(get_device().get_handle(), 1, &result_image_write, 0, VK_NULL_HANDLE); } @@ -439,22 +427,14 @@ void RayTracingPositionFetch::build_command_buffers() Setup the strided device address regions pointing at the shader identifiers in the shader binding table */ - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); - const VkStridedDeviceAddressRegionKHR raygen_shader_sbt_entry{ - raygen_shader_binding_table->get_device_address(), - handle_size_aligned, - handle_size_aligned}; + const VkStridedDeviceAddressRegionKHR raygen_shader_sbt_entry{raygen_shader_binding_table->get_device_address(), handle_size_aligned, handle_size_aligned}; - const VkStridedDeviceAddressRegionKHR miss_shader_sbt_entry{ - miss_shader_binding_table->get_device_address(), - handle_size_aligned, - handle_size_aligned}; + const VkStridedDeviceAddressRegionKHR miss_shader_sbt_entry{miss_shader_binding_table->get_device_address(), handle_size_aligned, handle_size_aligned}; - const VkStridedDeviceAddressRegionKHR hit_shader_sbt_entry{ - hit_shader_binding_table->get_device_address(), - handle_size_aligned, - handle_size_aligned}; + const VkStridedDeviceAddressRegionKHR hit_shader_sbt_entry{hit_shader_binding_table->get_device_address(), handle_size_aligned, handle_size_aligned}; const VkStridedDeviceAddressRegionKHR callable_shader_sbt_entry{}; @@ -468,41 +448,21 @@ void RayTracingPositionFetch::build_command_buffers() vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline); vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline_layout, 0, 1, &descriptor_set, 0, 0); - vkCmdTraceRaysKHR( - draw_cmd_buffers[i], - &raygen_shader_sbt_entry, - &miss_shader_sbt_entry, - &hit_shader_sbt_entry, - &callable_shader_sbt_entry, - width, - height, - 1); + vkCmdTraceRaysKHR(draw_cmd_buffers[i], &raygen_shader_sbt_entry, &miss_shader_sbt_entry, &hit_shader_sbt_entry, &callable_shader_sbt_entry, width, + height, 1); /* Copy ray tracing output to swap chain image */ // Prepare current swap chain image as transfer destination - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, {}, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Prepare ray tracing output image as transfer source - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {}, + VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); VkImageCopy copy_region{}; copy_region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; @@ -510,25 +470,16 @@ void RayTracingPositionFetch::build_command_buffers() copy_region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; copy_region.dstOffset = {0, 0, 0}; copy_region.extent = {width, height, 1}; - vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, get_render_context().get_swapchain().get_images()[i], + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); // Transition swap chain image back for presentation - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); // Transition ray tracing output image back to general layout - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - {}, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_IMAGE_LAYOUT_GENERAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_TRANSFER_READ_BIT, {}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresource_range); /* Start a new render pass to draw the UI overlay on top of the ray traced image diff --git a/samples/extensions/ray_tracing_reflection/ray_tracing_reflection.cpp b/samples/extensions/ray_tracing_reflection/ray_tracing_reflection.cpp index 39fd8cd903..a175bc7b77 100644 --- a/samples/extensions/ray_tracing_reflection/ray_tracing_reflection.cpp +++ b/samples/extensions/ray_tracing_reflection/ray_tracing_reflection.cpp @@ -44,35 +44,23 @@ struct ObjCube : ObjModelCpu { vertices = { {{+0.5f, +0.5f, +0.5f}, {+0.f, +1.f, +0.f}}, // Top - {{-0.5f, +0.5f, +0.5f}, {+0.f, +1.f, +0.f}}, - {{+0.5f, +0.5f, -0.5f}, {+0.f, +1.f, +0.f}}, - {{-0.5f, +0.5f, -0.5f}, {+0.f, +1.f, +0.f}}, + {{-0.5f, +0.5f, +0.5f}, {+0.f, +1.f, +0.f}}, {{+0.5f, +0.5f, -0.5f}, {+0.f, +1.f, +0.f}}, {{-0.5f, +0.5f, -0.5f}, {+0.f, +1.f, +0.f}}, {{+0.5f, -0.5f, +0.5f}, {+0.f, -1.f, +0.f}}, // Bottom - {{-0.5f, -0.5f, +0.5f}, {+0.f, -1.f, +0.f}}, - {{+0.5f, -0.5f, -0.5f}, {+0.f, -1.f, +0.f}}, - {{-0.5f, -0.5f, -0.5f}, {+0.f, -1.f, +0.f}}, + {{-0.5f, -0.5f, +0.5f}, {+0.f, -1.f, +0.f}}, {{+0.5f, -0.5f, -0.5f}, {+0.f, -1.f, +0.f}}, {{-0.5f, -0.5f, -0.5f}, {+0.f, -1.f, +0.f}}, {{+0.5f, +0.5f, +0.5f}, {+1.f, +0.f, +0.f}}, // Right - {{+0.5f, +0.5f, -0.5f}, {+1.f, +0.f, +0.f}}, - {{+0.5f, -0.5f, -0.5f}, {+1.f, +0.f, +0.f}}, - {{+0.5f, -0.5f, +0.5f}, {+1.f, +0.f, +0.f}}, + {{+0.5f, +0.5f, -0.5f}, {+1.f, +0.f, +0.f}}, {{+0.5f, -0.5f, -0.5f}, {+1.f, +0.f, +0.f}}, {{+0.5f, -0.5f, +0.5f}, {+1.f, +0.f, +0.f}}, {{-0.5f, +0.5f, +0.5f}, {-1.f, +0.f, +0.f}}, // left - {{-0.5f, +0.5f, -0.5f}, {-1.f, +0.f, +0.f}}, - {{-0.5f, -0.5f, -0.5f}, {-1.f, +0.f, +0.f}}, - {{-0.5f, -0.5f, +0.5f}, {-1.f, +0.f, +0.f}}, + {{-0.5f, +0.5f, -0.5f}, {-1.f, +0.f, +0.f}}, {{-0.5f, -0.5f, -0.5f}, {-1.f, +0.f, +0.f}}, {{-0.5f, -0.5f, +0.5f}, {-1.f, +0.f, +0.f}}, {{-0.5f, +0.5f, +0.5f}, {+0.f, +0.f, +1.f}}, // front - {{+0.5f, +0.5f, +0.5f}, {+0.f, +0.f, +1.f}}, - {{+0.5f, -0.5f, +0.5f}, {+0.f, +0.f, +1.f}}, - {{-0.5f, -0.5f, +0.5f}, {+0.f, +0.f, +1.f}}, + {{+0.5f, +0.5f, +0.5f}, {+0.f, +0.f, +1.f}}, {{+0.5f, -0.5f, +0.5f}, {+0.f, +0.f, +1.f}}, {{-0.5f, -0.5f, +0.5f}, {+0.f, +0.f, +1.f}}, {{-0.5f, +0.5f, -0.5f}, {+0.f, +0.f, -1.f}}, // back - {{+0.5f, +0.5f, -0.5f}, {+0.f, +0.f, -1.f}}, - {{+0.5f, -0.5f, -0.5f}, {+0.f, +0.f, -1.f}}, - {{-0.5f, -0.5f, -0.5f}, {+0.f, +0.f, -1.f}}, + {{+0.5f, +0.5f, -0.5f}, {+0.f, +0.f, -1.f}}, {{+0.5f, -0.5f, -0.5f}, {+0.f, +0.f, -1.f}}, {{-0.5f, -0.5f, -0.5f}, {+0.f, +0.f, -1.f}}, }; indices = { - 0, 1, 2, 1, 2, 3, /*top*/ - 4, 5, 6, 5, 6, 7, /*bottom*/ - 8, 9, 10, 8, 10, 11, /*right*/ + 0, 1, 2, 1, 2, 3, /*top*/ + 4, 5, 6, 5, 6, 7, /*bottom*/ + 8, 9, 10, 8, 10, 11, /*right*/ 12, 13, 14, 12, 14, 15, /*left*/ 16, 17, 18, 16, 18, 19, /*front*/ 20, 21, 22, 20, 22, 23, /*back*/ @@ -202,15 +190,8 @@ void RaytracingReflection::create_storage_image() VK_CHECK(vkCreateImageView(get_device().get_handle(), &color_image_view, nullptr, &storage_image.view)); VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkb::image_layout_transition(command_buffer, - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - {}, - {}, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_GENERAL, - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); + vkb::image_layout_transition(command_buffer, storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, {}, {}, + VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}); get_device().flush_command_buffer(command_buffer, queue); } @@ -220,14 +201,13 @@ void RaytracingReflection::create_storage_image() void RaytracingReflection::create_bottom_level_acceleration_structure(ObjModelGpu &obj_model) { // Note that the buffer usage flags for buffers consumed by the bottom level acceleration structure require special flags - const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VkBufferUsageFlags buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; // Setup a single transformation matrix that can be used to transform the whole geometry for a single bottom level acceleration structure - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; - std::unique_ptr transform_matrix_buffer = std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; + std::unique_ptr transform_matrix_buffer = + std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); transform_matrix_buffer->update(&transform_matrix, sizeof(transform_matrix)); VkDeviceOrHostAddressConstKHR vertex_data_device_address{}; @@ -264,15 +244,14 @@ void RaytracingReflection::create_bottom_level_acceleration_structure(ObjModelGp const uint32_t triangle_count = obj_model.nb_indices / 3; VkAccelerationStructureBuildSizesInfoKHR acceleration_structure_build_sizes_info{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR}; - vkGetAccelerationStructureBuildSizesKHR(get_device().get_handle(), - VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, - &acceleration_structure_build_geometry_info, - &triangle_count, - &acceleration_structure_build_sizes_info); + vkGetAccelerationStructureBuildSizesKHR(get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, + &acceleration_structure_build_geometry_info, &triangle_count, &acceleration_structure_build_sizes_info); // Create a buffer to hold the acceleration structure AccelerationStructure blas; - blas.buffer = std::make_unique(get_device(), acceleration_structure_build_sizes_info.accelerationStructureSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + blas.buffer = std::make_unique(get_device(), acceleration_structure_build_sizes_info.accelerationStructureSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VMA_MEMORY_USAGE_GPU_ONLY); // Create the acceleration structure VkAccelerationStructureCreateInfoKHR acceleration_structure_create_info{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR}; @@ -285,10 +264,11 @@ void RaytracingReflection::create_bottom_level_acceleration_structure(ObjModelGp // Create a scratch buffer as a temporary storage for the acceleration structure build std::unique_ptr sc_buffer; - sc_buffer = std::make_unique(get_device(), vkb::core::BufferBuilderC(acceleration_structure_build_sizes_info.buildScratchSize) - .with_usage(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) - .with_vma_usage(VMA_MEMORY_USAGE_CPU_TO_GPU) - .with_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment)); + sc_buffer = std::make_unique(get_device(), + vkb::core::BufferBuilderC(acceleration_structure_build_sizes_info.buildScratchSize) + .with_usage(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) + .with_vma_usage(VMA_MEMORY_USAGE_CPU_TO_GPU) + .with_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment)); VkAccelerationStructureBuildGeometryInfoKHR acceleration_build_geometry_info{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR}; acceleration_build_geometry_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; @@ -307,12 +287,10 @@ void RaytracingReflection::create_bottom_level_acceleration_structure(ObjModelGp std::vector acceleration_build_structure_range_infos = {&acceleration_structure_build_range_info}; // Build the acceleration structure on the device via a one-time command buffer submission - // Some implementations may support acceleration structure building on the host (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds + // Some implementations may support acceleration structure building on the host + // (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkCmdBuildAccelerationStructuresKHR(command_buffer, - 1, - &acceleration_build_geometry_info, - acceleration_build_structure_range_infos.data()); + vkCmdBuildAccelerationStructuresKHR(command_buffer, 1, &acceleration_build_geometry_info, acceleration_build_structure_range_infos.data()); get_device().flush_command_buffer(command_buffer, queue); // delete_scratch_buffer(scratch_buffer); @@ -327,10 +305,9 @@ void RaytracingReflection::create_bottom_level_acceleration_structure(ObjModelGp */ void RaytracingReflection::create_top_level_acceleration_structure(std::vector &blas_instances) { - std::unique_ptr instances_buffer = std::make_unique(get_device(), - sizeof(VkAccelerationStructureInstanceKHR) * blas_instances.size(), - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr instances_buffer = std::make_unique( + get_device(), sizeof(VkAccelerationStructureInstanceKHR) * blas_instances.size(), + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); instances_buffer->update(blas_instances.data(), sizeof(VkAccelerationStructureInstanceKHR) * blas_instances.size()); VkDeviceOrHostAddressConstKHR instance_data_device_address{}; @@ -354,18 +331,13 @@ void RaytracingReflection::create_top_level_acceleration_structure(std::vector(blas_instances.size()); VkAccelerationStructureBuildSizesInfoKHR acceleration_structure_build_sizes_info{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR}; - vkGetAccelerationStructureBuildSizesKHR( - get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, - &acceleration_structure_build_geometry_info, - &primitive_count, - &acceleration_structure_build_sizes_info); + vkGetAccelerationStructureBuildSizesKHR(get_device().get_handle(), VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, + &acceleration_structure_build_geometry_info, &primitive_count, &acceleration_structure_build_sizes_info); // Create a buffer to hold the acceleration structure top_level_acceleration_structure.buffer = std::make_unique( - get_device(), - acceleration_structure_build_sizes_info.accelerationStructureSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + get_device(), acceleration_structure_build_sizes_info.accelerationStructureSize, + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Create the acceleration structure VkAccelerationStructureCreateInfoKHR acceleration_structure_create_info{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR}; @@ -378,10 +350,11 @@ void RaytracingReflection::create_top_level_acceleration_structure(std::vector sc_buffer; - sc_buffer = std::make_unique(get_device(), vkb::core::BufferBuilderC(acceleration_structure_build_sizes_info.buildScratchSize) - .with_usage(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) - .with_vma_usage(VMA_MEMORY_USAGE_CPU_TO_GPU) - .with_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment)); + sc_buffer = std::make_unique(get_device(), + vkb::core::BufferBuilderC(acceleration_structure_build_sizes_info.buildScratchSize) + .with_usage(VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) + .with_vma_usage(VMA_MEMORY_USAGE_CPU_TO_GPU) + .with_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment)); VkAccelerationStructureBuildGeometryInfoKHR acceleration_build_geometry_info{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR}; acceleration_build_geometry_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR; @@ -400,13 +373,10 @@ void RaytracingReflection::create_top_level_acceleration_structure(std::vector acceleration_build_structure_range_infos = {&acceleration_structure_build_range_info}; // Build the acceleration structure on the device via a one-time command buffer submission - // Some implementations may support acceleration structure building on the host (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds + // Some implementations may support acceleration structure building on the host + // (VkPhysicalDeviceAccelerationStructureFeaturesKHR->accelerationStructureHostCommands), but we prefer device builds VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkCmdBuildAccelerationStructuresKHR( - command_buffer, - 1, - &acceleration_build_geometry_info, - acceleration_build_structure_range_infos.data()); + vkCmdBuildAccelerationStructuresKHR(command_buffer, 1, &acceleration_build_geometry_info, acceleration_build_structure_range_infos.data()); get_device().flush_command_buffer(command_buffer, queue); // delete_scratch_buffer(scratch_buffer); @@ -441,7 +411,8 @@ void RaytracingReflection::create_model(ObjModelCpu &obj, const std::vector(get_device(), vertex_buffer_size, buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); model.vertex_buffer->update(obj.vertices.data(), vertex_buffer_size); @@ -472,7 +443,7 @@ auto RaytracingReflection::create_blas_instance(uint32_t blas_id, glm::mat4 &mat // Get the bottom acceleration structure's handle, which will be used during the top level acceleration build VkAccelerationStructureDeviceAddressInfoKHR acceleration_device_address_info{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; acceleration_device_address_info.accelerationStructure = blas.handle; - auto device_address = vkGetAccelerationStructureDeviceAddressKHR(get_device().get_handle(), &acceleration_device_address_info); + auto device_address = vkGetAccelerationStructureDeviceAddressKHR(get_device().get_handle(), &acceleration_device_address_info); VkAccelerationStructureInstanceKHR blas_instance{}; blas_instance.transform = transform_matrix; @@ -504,7 +475,7 @@ void RaytracingReflection::create_buffer_references() obj_data.emplace_back(data); } VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - scene_desc = std::make_unique(get_device(), nbObj * sizeof(ObjBuffers), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + scene_desc = std::make_unique(get_device(), nbObj * sizeof(ObjBuffers), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); scene_desc->update(obj_data.data(), nbObj * sizeof(ObjBuffers)); } @@ -587,22 +558,26 @@ void RaytracingReflection::create_shader_binding_tables() const uint32_t handle_alignment = ray_tracing_pipeline_properties.shaderGroupHandleAlignment; const uint32_t handle_size_aligned = aligned_size(handle_size, handle_alignment); - const VkBufferUsageFlags sbt_buffer_usage_flags = VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + const VkBufferUsageFlags sbt_buffer_usage_flags = + VK_BUFFER_USAGE_SHADER_BINDING_TABLE_BIT_KHR | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VmaMemoryUsage sbt_memory_usage = VMA_MEMORY_USAGE_CPU_TO_GPU; // Create binding table buffers for each shader type - raygen_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size_aligned * rgen_index.size()) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); - miss_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size_aligned * miss_index.size()) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); - hit_shader_binding_table = std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size_aligned * hit_index.size()) - .with_usage(sbt_buffer_usage_flags) - .with_vma_usage(sbt_memory_usage) - .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + raygen_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size_aligned * rgen_index.size()) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + miss_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size_aligned * miss_index.size()) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); + hit_shader_binding_table = + std::make_unique(get_device(), vkb::core::BufferBuilderC(handle_size_aligned * hit_index.size()) + .with_usage(sbt_buffer_usage_flags) + .with_vma_usage(sbt_memory_usage) + .with_alignment(ray_tracing_pipeline_properties.shaderGroupBaseAlignment)); // Copy the pipeline's shader handles into a host buffer const auto group_count = static_cast(rgen_index.size() + miss_index.size() + hit_index.size()); @@ -667,9 +642,10 @@ void RaytracingReflection::create_descriptor_sets() VkDescriptorBufferInfo uniform_descriptor = create_descriptor(*ubo); VkDescriptorBufferInfo scene_descriptor = create_descriptor(*scene_desc); - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); - VkWriteDescriptorSet uniform_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniform_descriptor); - VkWriteDescriptorSet scene_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 3, &scene_descriptor); + VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + VkWriteDescriptorSet uniform_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniform_descriptor); + VkWriteDescriptorSet scene_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 3, &scene_descriptor); std::vector write_descriptor_sets = { acceleration_structure_write, @@ -793,7 +769,8 @@ void RaytracingReflection::create_ray_tracing_pipeline() raytracing_pipeline_create_info.pGroups = shader_groups.data(); raytracing_pipeline_create_info.maxPipelineRayRecursionDepth = 2; raytracing_pipeline_create_info.layout = pipeline_layout; - VK_CHECK(vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); + VK_CHECK( + vkCreateRayTracingPipelinesKHR(get_device().get_handle(), VK_NULL_HANDLE, VK_NULL_HANDLE, 1, &raytracing_pipeline_create_info, nullptr, &pipeline)); } /* @@ -837,9 +814,10 @@ void RaytracingReflection::build_command_buffers() // The descriptor also needs to be updated to reference the new image VkDescriptorImageInfo image_descriptor{}; - image_descriptor.imageView = storage_image.view; - image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; - VkWriteDescriptorSet result_image_write = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); + image_descriptor.imageView = storage_image.view; + image_descriptor.imageLayout = VK_IMAGE_LAYOUT_GENERAL; + VkWriteDescriptorSet result_image_write = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &image_descriptor); vkUpdateDescriptorSets(get_device().get_handle(), 1, &result_image_write, 0, VK_NULL_HANDLE); } @@ -855,7 +833,8 @@ void RaytracingReflection::build_command_buffers() Setup the strided device address regions pointing at the shader identifiers in the shader binding table */ - const uint32_t handle_size_aligned = aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); + const uint32_t handle_size_aligned = + aligned_size(ray_tracing_pipeline_properties.shaderGroupHandleSize, ray_tracing_pipeline_properties.shaderGroupHandleAlignment); VkStridedDeviceAddressRegionKHR raygen_shader_sbt_entry{}; raygen_shader_sbt_entry.deviceAddress = raygen_shader_binding_table->get_device_address(); @@ -880,40 +859,21 @@ void RaytracingReflection::build_command_buffers() vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline); vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, pipeline_layout, 0, 1, &descriptor_set, 0, 0); - vkCmdTraceRaysKHR( - draw_cmd_buffers[i], - &raygen_shader_sbt_entry, - &miss_shader_sbt_entry, - &hit_shader_sbt_entry, - &callable_shader_sbt_entry, - width, - height, - 1); + vkCmdTraceRaysKHR(draw_cmd_buffers[i], &raygen_shader_sbt_entry, &miss_shader_sbt_entry, &hit_shader_sbt_entry, &callable_shader_sbt_entry, width, + height, 1); /* Copy ray tracing output to swap chain image */ // Prepare current swap chain image as transfer destination - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, {}, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Prepare ray tracing output image as transfer source - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - {}, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_GENERAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, {}, + VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); VkImageCopy copy_region{}; copy_region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; @@ -921,25 +881,16 @@ void RaytracingReflection::build_command_buffers() copy_region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; copy_region.dstOffset = {0, 0, 0}; copy_region.extent = {width, height, 1}; - vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + vkCmdCopyImage(draw_cmd_buffers[i], storage_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, get_render_context().get_swapchain().get_images()[i], + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); // Transition swap chain image back for presentation - vkb::image_layout_transition(draw_cmd_buffers[i], - get_render_context().get_swapchain().get_images()[i], - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + vkb::image_layout_transition(draw_cmd_buffers[i], get_render_context().get_swapchain().get_images()[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); // Transition ray tracing output image back to general layout - vkb::image_layout_transition(draw_cmd_buffers[i], - storage_image.image, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - {}, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - VK_IMAGE_LAYOUT_GENERAL, - subresource_range); + vkb::image_layout_transition(draw_cmd_buffers[i], storage_image.image, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_TRANSFER_READ_BIT, {}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, subresource_range); /* Start a new render pass to draw the UI overlay on top of the ray traced image diff --git a/samples/extensions/ray_tracing_reflection/ray_tracing_reflection.h b/samples/extensions/ray_tracing_reflection/ray_tracing_reflection.h index f80adf60ed..58f6001ce2 100644 --- a/samples/extensions/ray_tracing_reflection/ray_tracing_reflection.h +++ b/samples/extensions/ray_tracing_reflection/ray_tracing_reflection.h @@ -63,7 +63,8 @@ class RaytracingReflection : public ApiVulkanSample public: VkPhysicalDeviceRayTracingPipelinePropertiesKHR ray_tracing_pipeline_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_PROPERTIES_KHR}; VkPhysicalDeviceAccelerationStructureFeaturesKHR acceleration_structure_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; - VkPhysicalDeviceAccelerationStructurePropertiesKHR acceleration_structure_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_PROPERTIES_KHR}; + VkPhysicalDeviceAccelerationStructurePropertiesKHR acceleration_structure_properties{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_PROPERTIES_KHR}; std::vector bottom_level_acceleration_structure; AccelerationStructure top_level_acceleration_structure; diff --git a/samples/extensions/shader_debugprintf/shader_debugprintf.cpp b/samples/extensions/shader_debugprintf/shader_debugprintf.cpp index 1392664dcf..be361efabb 100644 --- a/samples/extensions/shader_debugprintf/shader_debugprintf.cpp +++ b/samples/extensions/shader_debugprintf/shader_debugprintf.cpp @@ -24,17 +24,18 @@ std::string ShaderDebugPrintf::debug_output{}; -VKAPI_ATTR VkBool32 VKAPI_CALL ShaderDebugPrintf::debug_utils_message_callback( - VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, - VkDebugUtilsMessageTypeFlagsEXT messageType, - const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, - void *pUserData) +VKAPI_ATTR VkBool32 VKAPI_CALL ShaderDebugPrintf::debug_utils_message_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, + void *pUserData) { - // Look for Validation Layer message id names: VVL-DEBUG-PRINTF or WARNING-DEBUG-PRINTF or UNASSIGNED-DEBUG-PRINTF (have observed WARNING and UNASSIGNED with older Vulkan SDKs) - if (strcmp(pCallbackData->pMessageIdName, "VVL-DEBUG-PRINTF") == 0 || strcmp(pCallbackData->pMessageIdName, "WARNING-DEBUG-PRINTF") == 0 || strcmp(pCallbackData->pMessageIdName, "UNASSIGNED-DEBUG-PRINTF") == 0) + // Look for Validation Layer message id names: VVL-DEBUG-PRINTF or WARNING-DEBUG-PRINTF or UNASSIGNED-DEBUG-PRINTF (have observed WARNING and UNASSIGNED + // with older Vulkan SDKs) + if (strcmp(pCallbackData->pMessageIdName, "VVL-DEBUG-PRINTF") == 0 || strcmp(pCallbackData->pMessageIdName, "WARNING-DEBUG-PRINTF") == 0 || + strcmp(pCallbackData->pMessageIdName, "UNASSIGNED-DEBUG-PRINTF") == 0) { - // Validation messages are a bit verbose, but we only want the text from the shader, so we cut off everything before the first word from the shader message - // See scene.vert: debugPrintfEXT("Position = %v3f", outPos); + // Validation messages are a bit verbose, but we only want the text from the shader, so we cut off everything before the first word from the shader + // message See scene.vert: debugPrintfEXT("Position = %v3f", outPos); std::string shader_message{pCallbackData->pMessage}; shader_message = shader_message.substr(shader_message.find("Position")); debug_output.append(shader_message + "\n"); @@ -72,8 +73,8 @@ uint32_t ShaderDebugPrintf::get_api_version() const std::vector layer_properties(layer_property_count); VK_CHECK(vkEnumerateInstanceLayerProperties(&layer_property_count, layer_properties.data())); - const auto vvl_properties = std::ranges::find_if(layer_properties, - [](VkLayerProperties const &properties) { return strcmp(properties.layerName, validation_layer_name) == 0; }); + const auto vvl_properties = + std::ranges::find_if(layer_properties, [](VkLayerProperties const &properties) { return strcmp(properties.layerName, validation_layer_name) == 0; }); // Make sure we have found the validation layer before checking the VVL version and enumerating VVL instance extensions for VK_EXT_layer_settings if (vvl_properties != layer_properties.end()) @@ -103,7 +104,8 @@ void ShaderDebugPrintf::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) } else { - throw vkb::VulkanException(VK_ERROR_FEATURE_NOT_PRESENT, "Selected GPU does not support features fragmentStoresAndAtomics and/or vertexPipelineStoresAndAtomics"); + throw vkb::VulkanException(VK_ERROR_FEATURE_NOT_PRESENT, + "Selected GPU does not support features fragmentStoresAndAtomics and/or vertexPipelineStoresAndAtomics"); } // Enable anisotropic filtering if supported @@ -185,7 +187,8 @@ void ShaderDebugPrintf::build_command_buffers() { vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.skysphere); push_const_block.object_type = 0; - vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), &push_const_block); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), + &push_const_block); vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &descriptor_sets.skysphere, 0, nullptr); draw_model(models.skysphere, draw_cmd_buffers[i]); @@ -209,7 +212,8 @@ void ShaderDebugPrintf::build_command_buffers() push_const_block.object_type = 1; push_const_block.offset = glm::vec4(mesh_offsets[j], 0.0f); push_const_block.color = glm::vec4(mesh_colors[j], 0.0f); - vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), &push_const_block); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(push_const_block), + &push_const_block); draw_model(models.scene, draw_cmd_buffers[i]); } @@ -231,11 +235,10 @@ void ShaderDebugPrintf::load_assets() void ShaderDebugPrintf::setup_descriptor_pool() { // Note: Using debugprintf in a shader consumes a descriptor set, so we need to allocate one additional descriptor set - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; - uint32_t num_descriptor_sets = 2; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; + uint32_t num_descriptor_sets = 2; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -252,13 +255,11 @@ void ShaderDebugPrintf::setup_descriptor_set_layout() vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); // Pass object offset and color via push constant - VkPushConstantRange push_constant_range = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); + VkPushConstantRange push_constant_range = + vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(push_const_block), 0); pipeline_layout_create_info.pushConstantRangeCount = 1; pipeline_layout_create_info.pPushConstantRanges = &push_constant_range; @@ -267,11 +268,7 @@ void ShaderDebugPrintf::setup_descriptor_set_layout() void ShaderDebugPrintf::setup_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); // Sphere model object descriptor set VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets.sphere)); @@ -299,57 +296,28 @@ void ShaderDebugPrintf::setup_descriptor_sets() void ShaderDebugPrintf::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); std::vector blend_attachment_states = { vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE), @@ -410,10 +378,8 @@ void ShaderDebugPrintf::prepare_pipelines() void ShaderDebugPrintf::prepare_uniform_buffers() { // Matrices vertex shader uniform buffer - uniform_buffers.matrices = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers.matrices = + std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -463,8 +429,8 @@ bool ShaderDebugPrintf::prepare(const vkb::ApplicationOptions &options) VkDebugUtilsMessengerCreateInfoEXT const *ShaderDebugPrintf::get_debug_utils_messenger_create_info() const { // Register a sample specific debug utils callback in addition to the one registered by the base class - static VkDebugUtilsMessengerCreateInfoEXT local_debug_utils_messenger_create_info{.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, - .pNext = ApiVulkanSample::get_debug_utils_messenger_create_info(), + static VkDebugUtilsMessengerCreateInfoEXT local_debug_utils_messenger_create_info{.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, + .pNext = ApiVulkanSample::get_debug_utils_messenger_create_info(), .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT, .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT, .pfnUserCallback = debug_utils_message_callback}; diff --git a/samples/extensions/shader_debugprintf/shader_debugprintf.h b/samples/extensions/shader_debugprintf/shader_debugprintf.h index 6fe2b5aac7..81f2d71f47 100644 --- a/samples/extensions/shader_debugprintf/shader_debugprintf.h +++ b/samples/extensions/shader_debugprintf/shader_debugprintf.h @@ -72,28 +72,27 @@ class ShaderDebugPrintf : public ApiVulkanSample static std::string debug_output; - VKAPI_ATTR static VkBool32 VKAPI_CALL debug_utils_message_callback( - VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, - VkDebugUtilsMessageTypeFlagsEXT messageType, - const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, - void *pUserData); + VKAPI_ATTR static VkBool32 VKAPI_CALL debug_utils_message_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, + VkDebugUtilsMessageTypeFlagsEXT messageType, + const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, + void *pUserData); ShaderDebugPrintf(); ~ShaderDebugPrintf(); - void request_gpu_features(vkb::core::PhysicalDeviceC &gpu) override; - void request_instance_extensions(std::unordered_map &requested_extensions) const override; - void request_layer_settings(std::vector &requested_layer_settings) const override; - void request_validation_feature_enables(std::vector &requested_layer_settings) const override; - void build_command_buffers() override; - void load_assets(); - void setup_descriptor_pool(); - void setup_descriptor_set_layout(); - void setup_descriptor_sets(); - void prepare_pipelines(); - void prepare_uniform_buffers(); - void update_uniform_buffers(); - void draw(); - bool prepare(const vkb::ApplicationOptions &options) override; + void request_gpu_features(vkb::core::PhysicalDeviceC &gpu) override; + void request_instance_extensions(std::unordered_map &requested_extensions) const override; + void request_layer_settings(std::vector &requested_layer_settings) const override; + void request_validation_feature_enables(std::vector &requested_layer_settings) const override; + void build_command_buffers() override; + void load_assets(); + void setup_descriptor_pool(); + void setup_descriptor_set_layout(); + void setup_descriptor_sets(); + void prepare_pipelines(); + void prepare_uniform_buffers(); + void update_uniform_buffers(); + void draw(); + bool prepare(const vkb::ApplicationOptions &options) override; virtual VkDebugUtilsMessengerCreateInfoEXT const *get_debug_utils_messenger_create_info() const override; virtual void render(float delta_time) override; virtual void on_update_ui_overlay(vkb::Drawer &drawer) override; diff --git a/samples/extensions/shader_object/shader_object.cpp b/samples/extensions/shader_object/shader_object.cpp index 894963dc67..c756cee8d8 100644 --- a/samples/extensions/shader_object/shader_object.cpp +++ b/samples/extensions/shader_object/shader_object.cpp @@ -250,12 +250,14 @@ void ShaderObject::setup_render_pass() VkSubpassDependency dependency{}; // Setup color destination stages for output, early, and late frag test so scene drawing finishes before drawing up - dependency.srcSubpass = VK_SUBPASS_EXTERNAL; - dependency.dstSubpass = 0; - dependency.srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT; - dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dependency.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + dependency.srcSubpass = VK_SUBPASS_EXTERNAL; + dependency.dstSubpass = 0; + dependency.srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT; + dependency.dstStageMask = + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; + dependency.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; dependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; // Setup create info for the render pass for the UI @@ -293,7 +295,8 @@ void ShaderObject::create_default_sampler() // Note that for simplicity always use max. available anisotropy level for the current device // This may have an impact on performance, esp. on lower-specced devices // In a real-world scenario the level of anisotropy should be a user setting or e.g. lowered for mobile devices by default - sampler_create_info.maxAnisotropy = get_device().get_gpu().get_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f; + sampler_create_info.maxAnisotropy = + get_device().get_gpu().get_features().samplerAnisotropy ? (get_device().get_gpu().get_properties().limits.maxSamplerAnisotropy) : 1.0f; sampler_create_info.anisotropyEnable = get_device().get_gpu().get_features().samplerAnisotropy; sampler_create_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK(vkCreateSampler(get_device().get_handle(), &sampler_create_info, nullptr, &standard_sampler)); @@ -339,8 +342,7 @@ void ShaderObject::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) VkImageFormatProperties2 image_properties; image_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; image_properties.pNext = nullptr; - VkResult format_result = vkGetPhysicalDeviceImageFormatProperties2(gpu.get_handle(), &image_format, - &image_properties); + VkResult format_result = vkGetPhysicalDeviceImageFormatProperties2(gpu.get_handle(), &image_format, &image_properties); // Add supported depth formats if (format_result == VK_SUCCESS) @@ -364,8 +366,7 @@ void ShaderObject::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) VkImageFormatProperties2 image_properties; image_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; image_properties.pNext = nullptr; - VkResult format_result = vkGetPhysicalDeviceImageFormatProperties2(gpu.get_handle(), &image_format, - &image_properties); + VkResult format_result = vkGetPhysicalDeviceImageFormatProperties2(gpu.get_handle(), &image_format, &image_properties); // Add supported output formats if (format_result == VK_SUCCESS) @@ -443,7 +444,8 @@ void ShaderObject::load_assets() void ShaderObject::prepare_uniform_buffers() { - camera_mats_ubo_buffer = std::make_unique(get_device(), sizeof(camera_mats_ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + camera_mats_ubo_buffer = + std::make_unique(get_device(), sizeof(camera_mats_ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } void ShaderObject::update_uniform_buffers() @@ -469,48 +471,41 @@ void ShaderObject::create_descriptor_pool() void ShaderObject::setup_descriptor_set_layout() { - std::vector set_layout_bindings[ShaderTypeCOUNT] = + std::vector set_layout_bindings[ShaderTypeCOUNT] = { + {// ShaderTypeBasic + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, + 2), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 3)}, { - {// ShaderTypeBasic - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 2), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 3)}, - { - // ShaderTypeMaterial - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), - }, - {// ShaderTypePostProcess - vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0)}}; + // ShaderTypeMaterial + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2), + }, + {// ShaderTypePostProcess + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0)}}; // Set push constant for basic shader types to be in the vertex shader - push_constant_ranges[ShaderTypeBasic] = vkb::initializers::push_constant_range( - VK_SHADER_STAGE_VERTEX_BIT, - sizeof(BasicPushConstant), - 0); + push_constant_ranges[ShaderTypeBasic] = vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT, sizeof(BasicPushConstant), 0); // Set push constant for material shader types to be in the vertex, geometry, and fragment shader push_constant_ranges[ShaderTypeMaterial] = vkb::initializers::push_constant_range( - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - sizeof(MaterialPushConstant), - 0); + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(MaterialPushConstant), 0); // Set push constant for post processing shader types to be in the vertex and fragment shader - push_constant_ranges[ShaderTypePostProcess] = vkb::initializers::push_constant_range( - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - sizeof(PostProcessPushConstant), - 0); + push_constant_ranges[ShaderTypePostProcess] = + vkb::initializers::push_constant_range(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(PostProcessPushConstant), 0); // Create the pipeline layout for each of the shader types for (int i = 0; i < ShaderTypeCOUNT; ++i) { - VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = {vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings[i].data(), static_cast(set_layout_bindings[i].size()))}; + VkDescriptorSetLayoutCreateInfo descriptor_layout_create_info = { + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings[i].data(), static_cast(set_layout_bindings[i].size()))}; VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layouts[i])); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layouts[i], - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layouts[i], 1); // Create pipeline layouts for each shader type pipeline_layout_create_info.pushConstantRangeCount = 1; @@ -524,11 +519,7 @@ void ShaderObject::create_descriptor_sets() for (int i = 0; i < ShaderTypeCOUNT; ++i) { // Allocate descriptor set for each shader type - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layouts[i], - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layouts[i], 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_sets[i])); } @@ -562,17 +553,9 @@ void ShaderObject::create_shaders() std::vector frag_shader_data = vkb::fs::read_shader_binary_u32("shader_object/" + frag_shader_name); // Create shaders with current and next stage bits and set the shaders GLSL shader data, descriptor sets, and push constants - skybox_vert_shader = new Shader(VK_SHADER_STAGE_VERTEX_BIT, - VK_SHADER_STAGE_FRAGMENT_BIT, - "skybox vert", - vert_shader_data, - &descriptor_set_layouts[ShaderTypeBasic], - &push_constant_ranges[ShaderTypeBasic]); - skybox_frag_shader = new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, - 0, - "skybox frag", - frag_shader_data, - &descriptor_set_layouts[ShaderTypeBasic], + skybox_vert_shader = new Shader(VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, "skybox vert", vert_shader_data, + &descriptor_set_layouts[ShaderTypeBasic], &push_constant_ranges[ShaderTypeBasic]); + skybox_frag_shader = new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, 0, "skybox frag", frag_shader_data, &descriptor_set_layouts[ShaderTypeBasic], &push_constant_ranges[ShaderTypeBasic]); // Set the fragment shader as linked to build them linked and build the shader @@ -592,12 +575,8 @@ void ShaderObject::create_shaders() std::vector vert_shader_data = vkb::fs::read_shader_binary_u32("shader_object/" + vert_shader_name); // Create shader with current and next stage bits and set the GLSL shader data, descriptor sets, and push constants - post_process_vert_shader = new Shader(VK_SHADER_STAGE_VERTEX_BIT, - VK_SHADER_STAGE_FRAGMENT_BIT, - "FSQ", - vert_shader_data, - &descriptor_set_layouts[ShaderTypePostProcess], - &push_constant_ranges[ShaderTypePostProcess]); + post_process_vert_shader = new Shader(VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, "FSQ", vert_shader_data, + &descriptor_set_layouts[ShaderTypePostProcess], &push_constant_ranges[ShaderTypePostProcess]); // Build shader build_shader(device, post_process_vert_shader); @@ -618,17 +597,9 @@ void ShaderObject::create_shaders() std::vector frag_shader_data = vkb::fs::read_shader_binary_u32("shader_object/" + frag_shader_name); // Create shaders with current and next stage bits and set the shaders GLSL shader data, descriptor sets, and push constants - terrain_vert_shader = new Shader(VK_SHADER_STAGE_VERTEX_BIT, - VK_SHADER_STAGE_FRAGMENT_BIT, - "Terrain vert", - vert_shader_data, - &descriptor_set_layouts[ShaderTypeBasic], - &push_constant_ranges[ShaderTypeBasic]); - terrain_frag_shader = new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, - 0, - "Terrain frag", - frag_shader_data, - &descriptor_set_layouts[ShaderTypeBasic], + terrain_vert_shader = new Shader(VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, "Terrain vert", vert_shader_data, + &descriptor_set_layouts[ShaderTypeBasic], &push_constant_ranges[ShaderTypeBasic]); + terrain_frag_shader = new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, 0, "Terrain frag", frag_shader_data, &descriptor_set_layouts[ShaderTypeBasic], &push_constant_ranges[ShaderTypeBasic]); // Set the fragment shader as linked to build them linked and build the shader @@ -653,19 +624,11 @@ void ShaderObject::create_shaders() LOGI("Compiling Shader Set {}", shader_name.c_str()); // Create shader with current and next stage bits and set the GLSL shader data, descriptor sets, and push constants - basic_vert_shaders.emplace_back(new Shader(VK_SHADER_STAGE_VERTEX_BIT, - VK_SHADER_STAGE_FRAGMENT_BIT, - shader_name, - vert_shader_data, - &descriptor_set_layouts[ShaderTypeBasic], - &push_constant_ranges[ShaderTypeBasic])); + basic_vert_shaders.emplace_back(new Shader(VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, shader_name, vert_shader_data, + &descriptor_set_layouts[ShaderTypeBasic], &push_constant_ranges[ShaderTypeBasic])); // Create shaders with current and next stage bits and set the GLSL shader data, descriptor sets, and push constants - basic_frag_shaders.emplace_back(new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, - 0, - shader_name, - frag_shader_data, - &descriptor_set_layouts[ShaderTypeBasic], + basic_frag_shaders.emplace_back(new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, 0, shader_name, frag_shader_data, &descriptor_set_layouts[ShaderTypeBasic], &push_constant_ranges[ShaderTypeBasic])); // Set the fragment shader as linked to build them linked and build the shader @@ -686,12 +649,9 @@ void ShaderObject::create_shaders() // Create shader with current and next stage bits and set the GLSL shader data, descriptor sets, and push constants post_process_frag_shaders.emplace_back( - new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, - 0, + new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, 0, shader_name.substr(unlinked_post_process_prefix_size, shader_name.length() - (unlinked_post_process_prefix_size + frag_suffix_size)), - shader_data, - &descriptor_set_layouts[ShaderTypePostProcess], - &push_constant_ranges[ShaderTypePostProcess])); + shader_data, &descriptor_set_layouts[ShaderTypePostProcess], &push_constant_ranges[ShaderTypePostProcess])); // Build shader build_shader(device, post_process_frag_shaders.back()); @@ -710,12 +670,9 @@ void ShaderObject::create_shaders() // Create shader with current and next stage bits set the GLSL shader data, descriptor sets, and push constants material_vert_shaders.emplace_back( - new Shader(VK_SHADER_STAGE_VERTEX_BIT, - VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, + new Shader(VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, shader_name.substr(unlinked_material_prefix_size, shader_name.length() - (unlinked_material_prefix_size + frag_suffix_size)), - shader_data, - &descriptor_set_layouts[ShaderTypeMaterial], - &push_constant_ranges[ShaderTypeMaterial])); + shader_data, &descriptor_set_layouts[ShaderTypeMaterial], &push_constant_ranges[ShaderTypeMaterial])); // Build shader build_shader(device, material_vert_shaders.back()); @@ -734,12 +691,9 @@ void ShaderObject::create_shaders() // Create shader with current and next stage bits and set the GLSL shader data, descriptor sets, and push constants material_geo_shaders.emplace_back( - new Shader(VK_SHADER_STAGE_GEOMETRY_BIT, - VK_SHADER_STAGE_FRAGMENT_BIT, - shader_name.substr(unlinked_material_prefix_size, shader_name.length() - (unlinked_material_prefix_size + geo_suffix_size)), - shader_data, - &descriptor_set_layouts[ShaderTypeMaterial], - &push_constant_ranges[ShaderTypeMaterial])); + new Shader(VK_SHADER_STAGE_GEOMETRY_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, + shader_name.substr(unlinked_material_prefix_size, shader_name.length() - (unlinked_material_prefix_size + geo_suffix_size)), shader_data, + &descriptor_set_layouts[ShaderTypeMaterial], &push_constant_ranges[ShaderTypeMaterial])); // Build shader build_shader(device, material_geo_shaders.back()); @@ -758,12 +712,9 @@ void ShaderObject::create_shaders() // Create shader with current and next stage bits and set the GLSL shader data, descriptor sets, and push constants material_frag_shaders.emplace_back( - new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, - 0, + new Shader(VK_SHADER_STAGE_FRAGMENT_BIT, 0, shader_name.substr(unlinked_material_prefix_size, shader_name.length() - (unlinked_material_prefix_size + frag_suffix_size)), - shader_data, - &descriptor_set_layouts[ShaderTypeMaterial], - &push_constant_ranges[ShaderTypeMaterial])); + shader_data, &descriptor_set_layouts[ShaderTypeMaterial], &push_constant_ranges[ShaderTypeMaterial])); // Build shader build_shader(device, material_frag_shaders.back()); @@ -780,21 +731,24 @@ void ShaderObject::create_images() depth_images.reserve(supported_depth_formats.size()); // Create image and set sampler for the post process image - post_process_image = create_output_image(VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT); + post_process_image = create_output_image(VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT); post_process_input_sampler.sampler = standard_sampler; // Create an output image for all supported formats for (auto format : supported_output_formats) { LOGI("Creating output image format of type {}", format.name); - output_images.emplace_back(create_output_image(format.format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)); + output_images.emplace_back(create_output_image(format.format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT)); } // Create a depth output image for all supported formats for (auto format : supported_depth_formats) { LOGI("Creating output image format of type {}", format.name); - depth_images.emplace_back(create_output_image(format.format, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_ASPECT_DEPTH_BIT)); + depth_images.emplace_back( + create_output_image(format.format, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_ASPECT_DEPTH_BIT)); } } @@ -815,15 +769,19 @@ void ShaderObject::initialize_descriptor_sets() vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeBasic], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_buffer_descriptor), vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeBasic], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &environment_image_descriptor), vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeBasic], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &heightmap_image_descriptor), - vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeBasic], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3, &texture_array_image_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeBasic], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3, + &texture_array_image_descriptor), // Buffer initial descriptor set data for ShaderTypeMaterial vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeMaterial], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_buffer_descriptor), - vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeMaterial], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &checkerboard_image_descriptor), - vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeMaterial], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &environment_image_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeMaterial], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, + &checkerboard_image_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeMaterial], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, + &environment_image_descriptor), // Buffer initial descriptor set data for ShaderTypePostProcess - vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypePostProcess], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &post_process_image_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypePostProcess], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, + &post_process_image_descriptor), }; // Update descriptor sets @@ -906,14 +864,10 @@ void ShaderObject::generate_terrain() vkb::core::BufferC vertex_staging = vkb::core::BufferC::create_staging_buffer(get_device(), vertices); vkb::core::BufferC index_staging = vkb::core::BufferC::create_staging_buffer(get_device(), indices); - terrain.vertices = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + terrain.vertices = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); - terrain.indices = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + terrain.indices = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Copy from staging buffers @@ -922,20 +876,10 @@ void ShaderObject::generate_terrain() VkBufferCopy copy_region = {}; copy_region.size = vertex_buffer_size; - vkCmdCopyBuffer( - copy_command, - vertex_staging.get_handle(), - terrain.vertices->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, vertex_staging.get_handle(), terrain.vertices->get_handle(), 1, ©_region); copy_region.size = index_buffer_size; - vkCmdCopyBuffer( - copy_command, - index_staging.get_handle(), - terrain.indices->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, index_staging.get_handle(), terrain.indices->get_handle(), 1, ©_region); get_device().flush_command_buffer(copy_command, queue, true); } @@ -967,23 +911,14 @@ void ShaderObject::build_command_buffers() depth_range.layerCount = 1; // Barriers for images that are rendered to - vkb::image_layout_transition(draw_cmd_buffer, - output_images[current_output_format].image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - 0, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, + vkb::image_layout_transition(draw_cmd_buffer, output_images[current_output_format].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, range); - vkb::image_layout_transition(draw_cmd_buffer, - depth_images[current_depth_format].image, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, - 0, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, depth_range); + vkb::image_layout_transition(draw_cmd_buffer, depth_images[current_depth_format].image, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, 0, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + depth_range); // Setup dynamic rendering attachment info and begin rendering { @@ -1043,7 +978,8 @@ void ShaderObject::build_command_buffers() // Bind descriptors and push constants for the skybox draw glm::mat4 model_matrix = glm::mat4(1.0f); - vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout[ShaderTypeBasic], 0, 1, &descriptor_sets[ShaderTypeBasic], 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout[ShaderTypeBasic], 0, 1, &descriptor_sets[ShaderTypeBasic], + 0, nullptr); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeBasic], VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(BasicPushConstant), &model_matrix); // Bind shaders for the skybox @@ -1087,7 +1023,8 @@ void ShaderObject::build_command_buffers() vkCmdSetCullModeEXT(draw_cmd_buffer, VK_CULL_MODE_FRONT_BIT); // Bind descriptors for models - vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout[ShaderTypeMaterial], 0, 1, &descriptor_sets[ShaderTypeMaterial], 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout[ShaderTypeMaterial], 0, 1, + &descriptor_sets[ShaderTypeMaterial], 0, nullptr); // Setup and initialize push constants for material shader types MaterialPushConstant material_push_constant; @@ -1095,10 +1032,11 @@ void ShaderObject::build_command_buffers() material_push_constant.camera_pos = camera.position; // Update and push constants for torus - material_push_constant.model = glm::translate(glm::vec3(1.2f, 0, 0)) * glm::rotate(elapsed_time, glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.015f)); + material_push_constant.model = + glm::translate(glm::vec3(1.2f, 0, 0)) * glm::rotate(elapsed_time, glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.015f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeMaterial], - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0, sizeof(MaterialPushConstant), &material_push_constant); + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(MaterialPushConstant), + &material_push_constant); // Bind shaders for the torus bind_material_shader(draw_cmd_buffer, 0); @@ -1107,10 +1045,11 @@ void ShaderObject::build_command_buffers() draw_model(torus, draw_cmd_buffer); // Update and push constants for rock 1 - material_push_constant.model = glm::translate(glm::vec3(1.2f, 1.f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 0, 1)) * glm::scale(glm::vec3(4.0f)); + material_push_constant.model = + glm::translate(glm::vec3(1.2f, 1.f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 0, 1)) * glm::scale(glm::vec3(4.0f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeMaterial], - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0, sizeof(MaterialPushConstant), &material_push_constant); + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(MaterialPushConstant), + &material_push_constant); // Bind shaders for rock 1 bind_material_shader(draw_cmd_buffer, 1); @@ -1119,10 +1058,11 @@ void ShaderObject::build_command_buffers() draw_model(rock, draw_cmd_buffer); // Update and push constants for cube 1 - material_push_constant.model = glm::translate(glm::vec3(1.2f, -1.f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 1, 0)) * glm::scale(glm::vec3(0.05f)); + material_push_constant.model = + glm::translate(glm::vec3(1.2f, -1.f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 1, 0)) * glm::scale(glm::vec3(0.05f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeMaterial], - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0, sizeof(MaterialPushConstant), &material_push_constant); + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(MaterialPushConstant), + &material_push_constant); // Bind shaders for cube 1 bind_material_shader(draw_cmd_buffer, 2); @@ -1131,10 +1071,11 @@ void ShaderObject::build_command_buffers() draw_model(cube, draw_cmd_buffer); // Update and push constants for torus 2 - material_push_constant.model = glm::translate(glm::vec3(-1.2f, 1.0f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 1, 0)) * glm::scale(glm::vec3(0.015f)); + material_push_constant.model = + glm::translate(glm::vec3(-1.2f, 1.0f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 1, 0)) * glm::scale(glm::vec3(0.015f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeMaterial], - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0, sizeof(MaterialPushConstant), &material_push_constant); + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(MaterialPushConstant), + &material_push_constant); // Bind shaders for torus 2 bind_material_shader(draw_cmd_buffer, 3); @@ -1143,10 +1084,11 @@ void ShaderObject::build_command_buffers() draw_model(torus, draw_cmd_buffer); // Update and push constants for rock 2 - material_push_constant.model = glm::translate(glm::vec3(-1.2f, -1.f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 1, 0)) * glm::scale(glm::vec3(4.0f)); + material_push_constant.model = + glm::translate(glm::vec3(-1.2f, -1.f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 1, 0)) * glm::scale(glm::vec3(4.0f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeMaterial], - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0, sizeof(MaterialPushConstant), &material_push_constant); + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(MaterialPushConstant), + &material_push_constant); // Bind shaders for rock 2 bind_material_shader(draw_cmd_buffer, 4); @@ -1155,10 +1097,11 @@ void ShaderObject::build_command_buffers() draw_model(rock, draw_cmd_buffer); // Update and push constants for cube 2 - material_push_constant.model = glm::translate(glm::vec3(-1.2f, 0, 0)) * glm::rotate(elapsed_time, glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.05f)); + material_push_constant.model = + glm::translate(glm::vec3(-1.2f, 0, 0)) * glm::rotate(elapsed_time, glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.05f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeMaterial], - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, - 0, sizeof(MaterialPushConstant), &material_push_constant); + VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(MaterialPushConstant), + &material_push_constant); // Bind shaders for cube 2 bind_material_shader(draw_cmd_buffer, 5); @@ -1174,7 +1117,8 @@ void ShaderObject::build_command_buffers() // Basic Shaders { // Bind basic shader descriptor set - vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout[ShaderTypeBasic], 0, 1, &descriptor_sets[ShaderTypeBasic], 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout[ShaderTypeBasic], 0, 1, &descriptor_sets[ShaderTypeBasic], + 0, nullptr); // Update and push constants for rock glm::mat4 model_matrix = glm::translate(glm::vec3(0, 0, -1.2f)) * glm::rotate(elapsed_time, glm::vec3(0, 0, 1)) * glm::scale(glm::vec3(4.0f)); @@ -1187,7 +1131,8 @@ void ShaderObject::build_command_buffers() draw_model(rock, draw_cmd_buffer); // Update and push constants for teapot 1 - model_matrix = glm::translate(glm::vec3(0, 0, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 1, 0)) * glm::rotate(glm::radians(180.0f), glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.2f)); + model_matrix = glm::translate(glm::vec3(0, 0, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 1, 0)) * + glm::rotate(glm::radians(180.0f), glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.2f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeBasic], VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(BasicPushConstant), &model_matrix); // Bind shaders for teapot 1 @@ -1197,7 +1142,8 @@ void ShaderObject::build_command_buffers() draw_model(teapot, draw_cmd_buffer); // Update and push constants for teapot 2 - model_matrix = glm::translate(glm::vec3(0, -1.2f, 0)) * glm::rotate(elapsed_time, glm::vec3(1, 0, 0)) * glm::rotate(glm::radians(180.0f), glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.2f)); + model_matrix = glm::translate(glm::vec3(0, -1.2f, 0)) * glm::rotate(elapsed_time, glm::vec3(1, 0, 0)) * + glm::rotate(glm::radians(180.0f), glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.2f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeBasic], VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(BasicPushConstant), &model_matrix); // Bind shaders for teapot 2 @@ -1207,7 +1153,8 @@ void ShaderObject::build_command_buffers() draw_model(teapot, draw_cmd_buffer); // Update and push constants for teapot 3 - model_matrix = glm::translate(glm::vec3(0, 1.2f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 0, 1)) * glm::rotate(glm::radians(180.0f), glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.2f)); + model_matrix = glm::translate(glm::vec3(0, 1.2f, 0)) * glm::rotate(elapsed_time, glm::vec3(0, 0, 1)) * + glm::rotate(glm::radians(180.0f), glm::vec3(1, 0, 0)) * glm::scale(glm::vec3(0.2f)); vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypeBasic], VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(BasicPushConstant), &model_matrix); // Bind shaders for teapot 3 @@ -1249,15 +1196,8 @@ void ShaderObject::build_command_buffers() blit.dstOffsets[1] = {static_cast(width), static_cast(height), 1}; // Add barrier for swapchain buffer image - vkb::image_layout_transition(draw_cmd_buffer, - swapchain_buffers[i].image, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - range); + vkb::image_layout_transition(draw_cmd_buffer, swapchain_buffers[i].image, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, + VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, range); if (post_processing == true) { @@ -1265,24 +1205,13 @@ void ShaderObject::build_command_buffers() vkCmdSetPolygonModeEXT(draw_cmd_buffer, VK_POLYGON_MODE_FILL); // Add barrier for the output image of the current output to be read from - vkb::image_layout_transition(draw_cmd_buffer, - output_images[current_output_format].image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_ACCESS_SHADER_READ_BIT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - range); + vkb::image_layout_transition(draw_cmd_buffer, output_images[current_output_format].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, range); // Add barrier for the post process image to be drawn to - vkb::image_layout_transition(draw_cmd_buffer, - post_process_image.image, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - 0, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_IMAGE_LAYOUT_UNDEFINED, + vkb::image_layout_transition(draw_cmd_buffer, post_process_image.image, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, range); { @@ -1310,8 +1239,10 @@ void ShaderObject::build_command_buffers() vkCmdSetDepthWriteEnableEXT(draw_cmd_buffer, VK_FALSE); // Bind post-process descriptor and push constants - vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout[ShaderTypePostProcess], 0, 1, &descriptor_sets[ShaderTypePostProcess], 0, nullptr); - vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypePostProcess], VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PostProcessPushConstant), &elapsed_time); + vkCmdBindDescriptorSets(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout[ShaderTypePostProcess], 0, 1, + &descriptor_sets[ShaderTypePostProcess], 0, nullptr); + vkCmdPushConstants(draw_cmd_buffer, pipeline_layout[ShaderTypePostProcess], VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, + sizeof(PostProcessPushConstant), &elapsed_time); // Bind shaders for post processing bind_shader(draw_cmd_buffer, post_process_vert_shader); @@ -1322,48 +1253,24 @@ void ShaderObject::build_command_buffers() vkCmdEndRenderingKHR(draw_cmd_buffer); // Add barrier on the post processing image so drawing finishes - vkb::image_layout_transition(draw_cmd_buffer, - post_process_image.image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - range); + vkb::image_layout_transition(draw_cmd_buffer, post_process_image.image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, range); // Copy the post processing image to the swapchain buffer - vkCmdBlitImage(draw_cmd_buffer, - post_process_image.image, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - swapchain_buffers[i].image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1, - &blit, - VK_FILTER_LINEAR); + vkCmdBlitImage(draw_cmd_buffer, post_process_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, swapchain_buffers[i].image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR); } else { // Add barrier on the output image so drawing finishes - vkb::image_layout_transition(draw_cmd_buffer, - output_images[current_output_format].image, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_ACCESS_TRANSFER_READ_BIT, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - range); + vkb::image_layout_transition(draw_cmd_buffer, output_images[current_output_format].image, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, range); // Copy the output processing image to the swapchain buffer - vkCmdBlitImage(draw_cmd_buffer, - output_images[current_output_format].image, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - swapchain_buffers[i].image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1, - &blit, - VK_FILTER_LINEAR); + vkCmdBlitImage(draw_cmd_buffer, output_images[current_output_format].image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, swapchain_buffers[i].image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR); } // Showing interop between pipelined render passes and shader object with the UI system @@ -1411,7 +1318,8 @@ void ShaderObject::update_descriptor_sets() vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypeMaterial], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &matrix_buffer_descriptor), // Buffer changing descriptor set data for ShaderTypePostProcess - vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypePostProcess], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &post_process_image_descriptor), + vkb::initializers::write_descriptor_set(descriptor_sets[ShaderTypePostProcess], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, + &post_process_image_descriptor), }; // Update descriptor sets @@ -1438,30 +1346,17 @@ void ShaderObject::set_initial_state(VkCommandBuffer cmd) { // Setup vertex input with position, normals, and uv - const VkVertexInputBindingDescription2EXT vertex_binding[] = - { - vkb::initializers::vertex_input_binding_description2ext(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX, 1)}; - - const VkVertexInputAttributeDescription2EXT vertex_attribute_description_ext[] = - { - vkb::initializers::vertex_input_attribute_description2ext( - 0, - 0, - VK_FORMAT_R32G32B32_SFLOAT, - offsetof(Vertex, pos)), - vkb::initializers::vertex_input_attribute_description2ext( - 0, - 1, - VK_FORMAT_R32G32B32_SFLOAT, - offsetof(Vertex, normal)), - vkb::initializers::vertex_input_attribute_description2ext( - 0, - 2, - VK_FORMAT_R32G32_SFLOAT, - offsetof(Vertex, uv)), - }; - - vkCmdSetVertexInputEXT(cmd, sizeof(vertex_binding) / sizeof(vertex_binding[0]), vertex_binding, sizeof(vertex_attribute_description_ext) / sizeof(vertex_attribute_description_ext[0]), vertex_attribute_description_ext); + const VkVertexInputBindingDescription2EXT vertex_binding[] = { + vkb::initializers::vertex_input_binding_description2ext(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX, 1)}; + + const VkVertexInputAttributeDescription2EXT vertex_attribute_description_ext[] = { + vkb::initializers::vertex_input_attribute_description2ext(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, pos)), + vkb::initializers::vertex_input_attribute_description2ext(0, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, normal)), + vkb::initializers::vertex_input_attribute_description2ext(0, 2, VK_FORMAT_R32G32_SFLOAT, offsetof(Vertex, uv)), + }; + + vkCmdSetVertexInputEXT(cmd, sizeof(vertex_binding) / sizeof(vertex_binding[0]), vertex_binding, + sizeof(vertex_attribute_description_ext) / sizeof(vertex_attribute_description_ext[0]), vertex_attribute_description_ext); } // Set the topology to triangles, don't restart primitives, set samples to only 1 per pixel @@ -1506,7 +1401,8 @@ void ShaderObject::set_initial_state(VkCommandBuffer cmd) { // Use RGBA color write mask - VkColorComponentFlags color_component_flags[] = {VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_A_BIT}; + VkColorComponentFlags color_component_flags[] = {VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_G_BIT | + VK_COLOR_COMPONENT_A_BIT}; vkCmdSetColorWriteMaskEXT(cmd, 0, 1, color_component_flags); } } @@ -1710,7 +1606,13 @@ void ShaderObject::randomize_current() } // Helper function for imgui slider for togglable sliders -void imgui_slider(bool *enabled, std::string formatted_slider, std::string shader_name, int *slider_int, int num_shaders, const int alignment = 290, const int checkbox_alignment = 30) +void imgui_slider(bool *enabled, + std::string formatted_slider, + std::string shader_name, + int *slider_int, + int num_shaders, + const int alignment = 290, + const int checkbox_alignment = 30) { ImGui::Checkbox(fmt::format("##{}", formatted_slider.c_str()).c_str(), enabled); ImGui::SameLine(checkbox_alignment); @@ -1761,42 +1663,34 @@ void ShaderObject::on_update_ui_overlay(vkb::Drawer &drawer) ImGui::SliderInt("Selected Basic Object:", &selected_basic_object, 0, num_basic_objects - 1); - imgui_slider(&iterate_basic, "Basic Linked Shader Set:", - basic_vert_shaders[current_basic_linked_shaders[selected_basic_object]]->get_name(), - ¤t_basic_linked_shaders[selected_basic_object], static_cast(basic_vert_shaders.size() - 1), - slider_spacing, checkbox_spacing); + imgui_slider(&iterate_basic, "Basic Linked Shader Set:", basic_vert_shaders[current_basic_linked_shaders[selected_basic_object]]->get_name(), + ¤t_basic_linked_shaders[selected_basic_object], static_cast(basic_vert_shaders.size() - 1), slider_spacing, + checkbox_spacing); ImGui::SliderInt("Selected Material Object:", &selected_material_object, 0, num_material_objects - 1); - imgui_slider(&iterate_material_vert, "Material Vert Shader:", - material_vert_shaders[current_material_shaders[selected_material_object].vert]->get_name(), - ¤t_material_shaders[selected_material_object].vert, static_cast(material_vert_shaders.size() - 1), - slider_spacing, checkbox_spacing); + imgui_slider(&iterate_material_vert, + "Material Vert Shader:", material_vert_shaders[current_material_shaders[selected_material_object].vert]->get_name(), + ¤t_material_shaders[selected_material_object].vert, static_cast(material_vert_shaders.size() - 1), slider_spacing, + checkbox_spacing); - imgui_slider(&iterate_material_geo, "Material Geo Shader:", - material_geo_shaders[current_material_shaders[selected_material_object].geo]->get_name(), - ¤t_material_shaders[selected_material_object].geo, static_cast(material_geo_shaders.size() - 1), - slider_spacing, checkbox_spacing); + imgui_slider(&iterate_material_geo, "Material Geo Shader:", material_geo_shaders[current_material_shaders[selected_material_object].geo]->get_name(), + ¤t_material_shaders[selected_material_object].geo, static_cast(material_geo_shaders.size() - 1), slider_spacing, + checkbox_spacing); - imgui_slider(&iterate_material_frag, "Material Frag Shader:", - material_frag_shaders[current_material_shaders[selected_material_object].frag]->get_name(), - ¤t_material_shaders[selected_material_object].frag, static_cast(material_frag_shaders.size() - 1), - slider_spacing, checkbox_spacing); + imgui_slider(&iterate_material_frag, + "Material Frag Shader:", material_frag_shaders[current_material_shaders[selected_material_object].frag]->get_name(), + ¤t_material_shaders[selected_material_object].frag, static_cast(material_frag_shaders.size() - 1), slider_spacing, + checkbox_spacing); - imgui_slider(&iterate_post_process, "Post Process Frag Shader:", - post_process_frag_shaders[current_post_process_shader]->get_name(), - ¤t_post_process_shader, static_cast(post_process_frag_shaders.size() - 1), - slider_spacing, checkbox_spacing); + imgui_slider(&iterate_post_process, "Post Process Frag Shader:", post_process_frag_shaders[current_post_process_shader]->get_name(), + ¤t_post_process_shader, static_cast(post_process_frag_shaders.size() - 1), slider_spacing, checkbox_spacing); - imgui_slider(&iterate_output, "Output Format:", - supported_output_formats[current_output_format].name.c_str(), - ¤t_output_format, static_cast(supported_output_formats.size() - 1), - slider_spacing, checkbox_spacing); + imgui_slider(&iterate_output, "Output Format:", supported_output_formats[current_output_format].name.c_str(), ¤t_output_format, + static_cast(supported_output_formats.size() - 1), slider_spacing, checkbox_spacing); - imgui_slider(&iterate_depth, "Depth Format:", - supported_depth_formats[current_depth_format].name, - ¤t_depth_format, static_cast(supported_depth_formats.size() - 1), - slider_spacing, checkbox_spacing); + imgui_slider(&iterate_depth, "Depth Format:", supported_depth_formats[current_depth_format].name, ¤t_depth_format, + static_cast(supported_depth_formats.size() - 1), slider_spacing, checkbox_spacing); if (drawer.button("Randomize All")) { @@ -1814,15 +1708,16 @@ void ShaderObject::on_update_ui_overlay(vkb::Drawer &drawer) ImGui::SetNextWindowSize(ImVec2(width, window_height)); ImGui::PushStyleColor(ImGuiCol_WindowBg, 0); - if (ImGui::Begin("Histograms of CPU Frame time in (ms) of last 2000 frames", 0, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs)) + if (ImGui::Begin("Histograms of CPU Frame time in (ms) of last 2000 frames", 0, + ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoInputs)) { float max_value = *std::max_element(timestamp_values.begin(), timestamp_values.end()); ImGui::Text("16.667 ms"); ImGui::SameLine(-font_size); ImGui::PushStyleColor(ImGuiCol_FrameBg, 0); - ImGui::PlotLines("##Frame Times", timestamp_values.data(), static_cast(timestamp_values.size()), current_timestamp + 1, 0, 0.0f, - 16.667f, ImVec2(1.08f * width * dpi_factor, graph_height)); + ImGui::PlotLines("##Frame Times", timestamp_values.data(), static_cast(timestamp_values.size()), current_timestamp + 1, 0, 0.0f, 16.667f, + ImVec2(1.08f * width * dpi_factor, graph_height)); ImGui::PopStyleColor(); ImGui::Text("CPU Frame Time: %f ms (max %f ms)", timestamp_values[current_timestamp], max_value); @@ -1948,11 +1843,7 @@ void ShaderObject::build_linked_shaders(VkDevice device, ShaderObject::Shader *v VkShaderEXT shaderEXTs[2]; // Create the shader objects - VkResult result = vkCreateShadersEXT(device, - 2, - shader_create_infos, - nullptr, - shaderEXTs); + VkResult result = vkCreateShadersEXT(device, 2, shader_create_infos, nullptr, shaderEXTs); if (result != VK_SUCCESS) { diff --git a/samples/extensions/sparse_image/sparse_image.cpp b/samples/extensions/sparse_image/sparse_image.cpp index f5648b2027..19d624789d 100644 --- a/samples/extensions/sparse_image/sparse_image.cpp +++ b/samples/extensions/sparse_image/sparse_image.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Mobica Limited +/* Copyright (c) 2023-2026, Mobica Limited * * SPDX-License-Identifier: Apache-2.0 * @@ -43,7 +43,8 @@ SparseImage::~SparseImage() */ void SparseImage::load_assets() { - virtual_texture.raw_data_image = vkb::sg::Image::load("/textures/vulkan_logo_full.ktx", "/textures/vulkan_logo_full.ktx", vkb::sg::Image::ContentType::Color); + virtual_texture.raw_data_image = + vkb::sg::Image::load("/textures/vulkan_logo_full.ktx", "/textures/vulkan_logo_full.ktx", vkb::sg::Image::ContentType::Color); assert(virtual_texture.raw_data_image->get_format() == image_format); VkExtent3D tex_extent = virtual_texture.raw_data_image->get_extent(); @@ -63,7 +64,8 @@ void SparseImage::create_sparse_bind_queue() uint8_t sparse_queue_family_index = 0xFF; for (uint32_t i = 0; i < static_cast(queue_family_properties.size()); i++) { - if ((queue_family_properties[i].queueFlags & VK_QUEUE_TRANSFER_BIT) && (queue_family_properties[i].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) && !(queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) + if ((queue_family_properties[i].queueFlags & VK_QUEUE_TRANSFER_BIT) && (queue_family_properties[i].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) && + !(queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) { sparse_queue_family_index = i; break; @@ -107,7 +109,10 @@ bool SparseImage::prepare(const vkb::ApplicationOptions &options) load_least_detailed_level(); - mesh_data = CalculateMipLevelData(current_mvp_transform, VkExtent2D({static_cast(virtual_texture.width), static_cast(virtual_texture.height)}), VkExtent2D({static_cast(width), static_cast(height)}), static_cast(num_vertical_blocks), static_cast(num_horizontal_blocks), virtual_texture.mip_levels); + mesh_data = + CalculateMipLevelData(current_mvp_transform, VkExtent2D({static_cast(virtual_texture.width), static_cast(virtual_texture.height)}), + VkExtent2D({static_cast(width), static_cast(height)}), static_cast(num_vertical_blocks), + static_cast(num_horizontal_blocks), virtual_texture.mip_levels); next_stage = Stages::Idle; @@ -124,7 +129,8 @@ void SparseImage::prepare_pipelines() VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &layout_info, nullptr, &sample_pipeline_layout)); VkPipelineVertexInputStateCreateInfo vertex_input = vkb::initializers::pipeline_vertex_input_state_create_info(); - std::array vertex_input_bindings = {vkb::initializers::vertex_input_binding_description(0, sizeof(SimpleVertex), VK_VERTEX_INPUT_RATE_VERTEX)}; + std::array vertex_input_bindings = { + vkb::initializers::vertex_input_binding_description(0, sizeof(SimpleVertex), VK_VERTEX_INPUT_RATE_VERTEX)}; std::array vertex_input_attributes = { vkb::initializers::vertex_input_attribute_description(0U, 0U, VK_FORMAT_R32G32_SFLOAT, offsetof(SimpleVertex, norm)), @@ -137,14 +143,19 @@ void SparseImage::prepare_pipelines() std::array dynamic_states{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0U, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE); - VkPipelineColorBlendAttachmentState color_blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1U, &color_blend_attachment_state); - VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1U, 1U); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_NEVER); - VkPipelineMultisampleStateCreateInfo multisampling_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT); - VkPipelineDynamicStateCreateInfo pipeline_dynamic_states = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_states.data(), vkb::to_u32(dynamic_states.size())); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0U, VK_FALSE); + VkPipelineRasterizationStateCreateInfo rasterization_state = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE); + VkPipelineColorBlendAttachmentState color_blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state( + VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT, VK_FALSE); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1U, &color_blend_attachment_state); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1U, 1U); + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_NEVER); + VkPipelineMultisampleStateCreateInfo multisampling_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT); + VkPipelineDynamicStateCreateInfo pipeline_dynamic_states = + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_states.data(), vkb::to_u32(dynamic_states.size())); std::array shader_stages{}; @@ -267,7 +278,8 @@ void SparseImage::process_texture_block(const TextureBlock &texture_block) { if (!virtual_texture.page_table[page_index].fixed) { - virtual_texture.page_table[page_index].render_required_set.erase({static_cast(texture_block.old_mip_level), texture_block.column, texture_block.row}); + virtual_texture.page_table[page_index].render_required_set.erase( + {static_cast(texture_block.old_mip_level), texture_block.column, texture_block.row}); } } page_indices.clear(); @@ -282,7 +294,8 @@ void SparseImage::process_texture_block(const TextureBlock &texture_block) for (auto page_index : page_indices) { - virtual_texture.page_table[page_index].render_required_set.insert({static_cast(texture_block.new_mip_level), texture_block.column, texture_block.row}); + virtual_texture.page_table[page_index].render_required_set.insert( + {static_cast(texture_block.new_mip_level), texture_block.column, texture_block.row}); if (!virtual_texture.page_table[page_index].valid) { @@ -314,8 +327,10 @@ SparseImage::MemPageDescription SparseImage::get_mem_page_description(size_t pag uint8_t mip_level = get_mip_level(page_index); mem_page_description.mip_level = mip_level; - mem_page_description.x = (page_index - virtual_texture.mip_properties[mip_level].mip_base_page_index) % virtual_texture.mip_properties[mip_level].num_columns; - mem_page_description.y = (page_index - virtual_texture.mip_properties[mip_level].mip_base_page_index) / virtual_texture.mip_properties[mip_level].num_columns; + mem_page_description.x = + (page_index - virtual_texture.mip_properties[mip_level].mip_base_page_index) % virtual_texture.mip_properties[mip_level].num_columns; + mem_page_description.y = + (page_index - virtual_texture.mip_properties[mip_level].mip_base_page_index) / virtual_texture.mip_properties[mip_level].num_columns; return mem_page_description; } @@ -325,11 +340,13 @@ SparseImage::MemPageDescription SparseImage::get_mem_page_description(size_t pag */ size_t SparseImage::get_page_index(MemPageDescription mem_page_desc) { - return virtual_texture.mip_properties[mem_page_desc.mip_level].mip_base_page_index + virtual_texture.mip_properties[mem_page_desc.mip_level].num_columns * mem_page_desc.y + mem_page_desc.x; + return virtual_texture.mip_properties[mem_page_desc.mip_level].mip_base_page_index + + virtual_texture.mip_properties[mem_page_desc.mip_level].num_columns * mem_page_desc.y + mem_page_desc.x; } /** - * @brief Check if all the required resources (memory pages from the more detailed mip level) for the particular memory page to be rendered, are already allocated and valid in the memory. + * @brief Check if all the required resources (memory pages from the more detailed mip level) for the particular memory page to be rendered, are already + * allocated and valid in the memory. */ void SparseImage::check_mip_page_requirements(std::vector &mipgen_required_vec, MemPageDescription mem_page_desc) { @@ -364,7 +381,8 @@ void SparseImage::check_mip_page_requirements(std::vector &m } /** - * @brief Convert information from BLOCK-based into PAGE-based data. BLOCKS are just the abstraction units described by num_horizontal_blocks and num_vertical_blocks. PAGES are the actually allocated chunks of memory, their size is device-dependent. + * @brief Convert information from BLOCK-based into PAGE-based data. BLOCKS are just the abstraction units described by num_horizontal_blocks and + * num_vertical_blocks. PAGES are the actually allocated chunks of memory, their size is device-dependent. */ std::vector SparseImage::get_memory_dependency_for_the_block(size_t column, size_t row, uint8_t mip_level) { @@ -415,7 +433,8 @@ void SparseImage::compare_mips_table() { if (!virtual_texture.new_mip_table[y][x].on_screen && virtual_texture.current_mip_table[y][x].on_screen) { - // The particular block is removed from all render_required_set`s in page_table[] entries, because it was previously visible on screen, and is not anymore. + // The particular block is removed from all render_required_set`s in page_table[] entries, because it was previously visible on screen, and is + // not anymore. TextureBlock texture_block = {y, x, virtual_texture.current_mip_table[y][x].mip_level, virtual_texture.new_mip_table[y][x].mip_level, false}; process_texture_block(texture_block); @@ -423,10 +442,11 @@ void SparseImage::compare_mips_table() update_required = true; } else if (virtual_texture.new_mip_table[y][x].on_screen && - (!virtual_texture.current_mip_table[y][x].on_screen || - (static_cast(virtual_texture.new_mip_table[y][x].mip_level) != static_cast(virtual_texture.current_mip_table[y][x].mip_level)))) + (!virtual_texture.current_mip_table[y][x].on_screen || (static_cast(virtual_texture.new_mip_table[y][x].mip_level) != + static_cast(virtual_texture.current_mip_table[y][x].mip_level)))) { - // The particular block is visible on screen and needs to be updated, because either it wasn't previously visible on screen or the required mip_level has changed. + // The particular block is visible on screen and needs to be updated, because either it wasn't previously visible on screen or the required + // mip_level has changed. TextureBlock texture_block = {y, x, virtual_texture.current_mip_table[y][x].mip_level, virtual_texture.new_mip_table[y][x].mip_level, true}; virtual_texture.texture_block_update_set.insert(texture_block); update_required = true; @@ -542,14 +562,15 @@ void SparseImage::update_and_generate() std::vector temp_buffer(virtual_texture.page_size); - size_t level_zero_count = std::count_if( - virtual_texture.update_set.begin(), virtual_texture.update_set.end(), [this](auto page_index) { return get_mip_level(page_index) == 0; }); + size_t level_zero_count = + std::count_if(virtual_texture.update_set.begin(), virtual_texture.update_set.end(), [this](auto page_index) { return get_mip_level(page_index) == 0; }); size_t level_zero_index = 0; std::unique_ptr multi_page_buffer; if (0 < level_zero_count) { - multi_page_buffer = std::make_unique(get_device(), level_zero_count * virtual_texture.page_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU, VMA_ALLOCATION_CREATE_MAPPED_BIT); + multi_page_buffer = std::make_unique(get_device(), level_zero_count * virtual_texture.page_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU, VMA_ALLOCATION_CREATE_MAPPED_BIT); } VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); @@ -570,20 +591,24 @@ void SparseImage::update_and_generate() if (current_mip_level != 0xFF) { subresource_range.baseMipLevel = current_mip_level; - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); if (current_mip_level != 0) { subresource_range.baseMipLevel = current_mip_level - 1U; - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); } } subresource_range.baseMipLevel = mip_level; - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); if (mip_level != 0) { subresource_range.baseMipLevel = mip_level - 1U; - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); } current_mip_level = mip_level; @@ -625,31 +650,30 @@ void SparseImage::update_and_generate() region.imageOffset = VkOffset3D({block_offset.x, block_offset.y, 0}); region.imageExtent = VkExtent3D({block_extent.width, block_extent.height, 1U}); - vkCmdCopyBufferToImage(command_buffer, multi_page_buffer->get_handle(), virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1U, ®ion); + vkCmdCopyBufferToImage(command_buffer, multi_page_buffer->get_handle(), virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1U, + ®ion); virtual_texture.page_table[page_index].valid = true; } else { VkImageBlit blit_cmd{}; - blit_cmd.srcOffsets[0] = {(block_offset.x) * 2, (block_offset.y) * 2, 0}; - blit_cmd.srcOffsets[1] = {(block_offset.x + static_cast(block_extent.width)) * 2, (block_offset.y + static_cast(block_extent.height)) * 2, 1}; + blit_cmd.srcOffsets[0] = {(block_offset.x) * 2, (block_offset.y) * 2, 0}; + blit_cmd.srcOffsets[1] = {(block_offset.x + static_cast(block_extent.width)) * 2, (block_offset.y + static_cast(block_extent.height)) * 2, + 1}; blit_cmd.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; blit_cmd.srcSubresource.mipLevel = mip_level - 1U; blit_cmd.srcSubresource.baseArrayLayer = 0U; blit_cmd.srcSubresource.layerCount = 1U; blit_cmd.dstOffsets[0] = {block_offset.x, block_offset.y, 0}; - blit_cmd.dstOffsets[1] = {block_offset.x + static_cast(block_extent.width), block_offset.y + static_cast(block_extent.height), 1}; + blit_cmd.dstOffsets[1] = {block_offset.x + static_cast(block_extent.width), block_offset.y + static_cast(block_extent.height), 1}; blit_cmd.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; blit_cmd.dstSubresource.mipLevel = mip_level; blit_cmd.dstSubresource.baseArrayLayer = 0U; blit_cmd.dstSubresource.layerCount = 1U; - vkCmdBlitImage(command_buffer, - virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 1U, &blit_cmd, - VK_FILTER_LINEAR); + vkCmdBlitImage(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, virtual_texture.texture_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1U, &blit_cmd, VK_FILTER_LINEAR); virtual_texture.page_table[page_index].valid = true; } @@ -666,11 +690,13 @@ void SparseImage::update_and_generate() if (current_mip_level != 0xFF) { subresource_range.baseMipLevel = current_mip_level; - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); if (current_mip_level != 0) { subresource_range.baseMipLevel = current_mip_level - 1U; - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); } } @@ -729,7 +755,9 @@ void SparseImage::free_unused_memory() if (memory_defragmentation && !pages_to_reallocate.empty()) { - std::unique_ptr reallocation_buffer = std::make_unique(get_device(), virtual_texture.page_size * pages_to_reallocate.size(), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + std::unique_ptr reallocation_buffer = + std::make_unique(get_device(), virtual_texture.page_size * pages_to_reallocate.size(), + VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_GPU_ONLY); VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); @@ -772,8 +800,10 @@ void SparseImage::free_unused_memory() subresource_range.levelCount = virtual_texture.mip_levels; subresource_range.baseMipLevel = virtual_texture.base_mip_level; - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); - vkCmdCopyImageToBuffer(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, reallocation_buffer->get_handle(), static_cast(copy_infos.size()), copy_infos.data()); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, subresource_range); + vkCmdCopyImageToBuffer(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, reallocation_buffer->get_handle(), + static_cast(copy_infos.size()), copy_infos.data()); get_device().flush_command_buffer(command_buffer, queue, true); std::vector> temp_sectors; @@ -793,9 +823,12 @@ void SparseImage::free_unused_memory() command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); - vkCmdCopyBufferToImage(command_buffer, reallocation_buffer->get_handle(), virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast(copy_infos.size()), copy_infos.data()); - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + subresource_range); + vkCmdCopyBufferToImage(command_buffer, reallocation_buffer->get_handle(), virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(copy_infos.size()), copy_infos.data()); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); get_device().flush_command_buffer(command_buffer, queue, true); for (auto &page_index : pages_to_reallocate) @@ -956,7 +989,10 @@ void SparseImage::calculate_mips_table() num_horizontal_blocks = num_horizontal_blocks_upd; reset_mip_table(); - mesh_data = CalculateMipLevelData(current_mvp_transform, VkExtent2D({static_cast(virtual_texture.width), static_cast(virtual_texture.height)}), VkExtent2D({static_cast(width), static_cast(height)}), static_cast(num_vertical_blocks), static_cast(num_horizontal_blocks), virtual_texture.mip_levels); + mesh_data = CalculateMipLevelData(current_mvp_transform, + VkExtent2D({static_cast(virtual_texture.width), static_cast(virtual_texture.height)}), + VkExtent2D({static_cast(width), static_cast(height)}), static_cast(num_vertical_blocks), + static_cast(num_horizontal_blocks), virtual_texture.mip_levels); } else { @@ -1115,29 +1151,41 @@ void SparseImage::CalculateMipLevelData::calculate_mip_levels() double a_horizontal = ax_horizontal[row]; // Coordinates of the point which is the common point of two lines: 1) AtoB or AtoC; 2) The line going through point H, parallel to AtoC or AtoB - double x_vertical_vertical = (a_vertical * mesh[row][column].x + pH_vertical_y - (pH_vertical_x * a_horizontal) - mesh[row][column].y) / (a_vertical - a_horizontal); + double x_vertical_vertical = + (a_vertical * mesh[row][column].x + pH_vertical_y - (pH_vertical_x * a_horizontal) - mesh[row][column].y) / (a_vertical - a_horizontal); double y_vertical_vertical = (x_vertical_vertical - mesh[row][column].x) * a_vertical + mesh[row][column].y; - double x_vertical_horizontal_top = (a_horizontal * mesh[row][column].x + pH_vertical_y - (pH_vertical_x * a_vertical) - mesh[row][column].y) / (a_horizontal - a_vertical); - double y_vertical_horizontal_top = (x_vertical_horizontal_top - mesh[row][column].x) * a_horizontal + mesh[row][column].y; - double x_vertical_horizontal_bottom = (a_horizontal * mesh[row + 1][column].x + pH_vertical_y - (pH_vertical_x * a_vertical) - mesh[row + 1][column].y) / (a_horizontal - a_vertical); + double x_vertical_horizontal_top = + (a_horizontal * mesh[row][column].x + pH_vertical_y - (pH_vertical_x * a_vertical) - mesh[row][column].y) / (a_horizontal - a_vertical); + double y_vertical_horizontal_top = (x_vertical_horizontal_top - mesh[row][column].x) * a_horizontal + mesh[row][column].y; + double x_vertical_horizontal_bottom = + (a_horizontal * mesh[row + 1][column].x + pH_vertical_y - (pH_vertical_x * a_vertical) - mesh[row + 1][column].y) / (a_horizontal - a_vertical); double y_vertical_horizontal_bottom = (x_vertical_horizontal_bottom - mesh[row + 1][column].x) * a_horizontal + mesh[row + 1][column].y; - double x_horizontal_horizontal = (a_horizontal * mesh[row][column].x + pH_horizontal_y - (pH_horizontal_x * a_vertical) - mesh[row][column].y) / (a_horizontal - a_vertical); + double x_horizontal_horizontal = + (a_horizontal * mesh[row][column].x + pH_horizontal_y - (pH_horizontal_x * a_vertical) - mesh[row][column].y) / (a_horizontal - a_vertical); double y_horizontal_horizontal = (x_horizontal_horizontal - mesh[row][column].x) * a_horizontal + mesh[row][column].y; - double x_horizontal_vertical_left = (a_vertical * mesh[row][column].x + pH_horizontal_y - (pH_horizontal_x * a_horizontal) - mesh[row][column].y) / (a_vertical - a_horizontal); - double y_horizontal_vertical_left = (x_horizontal_vertical_left - mesh[row][column].x) * a_vertical + mesh[row][column].y; - double x_horizontal_vertical_right = (a_vertical * mesh[row][column + 1].x + pH_horizontal_y - (pH_horizontal_x * a_horizontal) - mesh[row][column + 1].y) / (a_vertical - a_horizontal); + double x_horizontal_vertical_left = + (a_vertical * mesh[row][column].x + pH_horizontal_y - (pH_horizontal_x * a_horizontal) - mesh[row][column].y) / (a_vertical - a_horizontal); + double y_horizontal_vertical_left = (x_horizontal_vertical_left - mesh[row][column].x) * a_vertical + mesh[row][column].y; + double x_horizontal_vertical_right = + (a_vertical * mesh[row][column + 1].x + pH_horizontal_y - (pH_horizontal_x * a_horizontal) - mesh[row][column + 1].y) / + (a_vertical - a_horizontal); double y_horizontal_vertical_right = (x_horizontal_vertical_right - mesh[row][column + 1].x) * a_vertical + mesh[row][column + 1].y; // On-screen distances from point H (vertical and horizontal) to the corresponding points calculated above - double on_screen_pH_vertical_vertical = sqrt(pow(pH_vertical_x - x_vertical_vertical, 2) + pow(pH_vertical_y - y_vertical_vertical, 2)); - double on_screen_pH_vertical_horizontal_top = sqrt(pow(pH_vertical_x - x_vertical_horizontal_top, 2) + pow(pH_vertical_y - y_vertical_horizontal_top, 2)); - double on_screen_pH_vertical_horizontal_bottom = sqrt(pow(pH_vertical_x - x_vertical_horizontal_bottom, 2) + pow(pH_vertical_y - y_vertical_horizontal_bottom, 2)); - double on_screen_pH_horizontal_horizontal = sqrt(pow(pH_horizontal_x - x_horizontal_horizontal, 2) + pow(pH_horizontal_y - y_horizontal_horizontal, 2)); - double on_screen_pH_horizontal_vertical_left = sqrt(pow(pH_horizontal_x - x_horizontal_vertical_left, 2) + pow(pH_horizontal_y - y_horizontal_vertical_left, 2)); - double on_screen_pH_horizontal_vertical_right = sqrt(pow(pH_horizontal_x - x_horizontal_vertical_right, 2) + pow(pH_horizontal_y - y_horizontal_vertical_right, 2)); + double on_screen_pH_vertical_vertical = sqrt(pow(pH_vertical_x - x_vertical_vertical, 2) + pow(pH_vertical_y - y_vertical_vertical, 2)); + double on_screen_pH_vertical_horizontal_top = + sqrt(pow(pH_vertical_x - x_vertical_horizontal_top, 2) + pow(pH_vertical_y - y_vertical_horizontal_top, 2)); + double on_screen_pH_vertical_horizontal_bottom = + sqrt(pow(pH_vertical_x - x_vertical_horizontal_bottom, 2) + pow(pH_vertical_y - y_vertical_horizontal_bottom, 2)); + double on_screen_pH_horizontal_horizontal = + sqrt(pow(pH_horizontal_x - x_horizontal_horizontal, 2) + pow(pH_horizontal_y - y_horizontal_horizontal, 2)); + double on_screen_pH_horizontal_vertical_left = + sqrt(pow(pH_horizontal_x - x_horizontal_vertical_left, 2) + pow(pH_horizontal_y - y_horizontal_vertical_left, 2)); + double on_screen_pH_horizontal_vertical_right = + sqrt(pow(pH_horizontal_x - x_horizontal_vertical_right, 2) + pow(pH_horizontal_y - y_horizontal_vertical_right, 2)); // On-texture counterparts of distances above double on_texture_pH_vertical_vertical = on_screen_pH_vertical_vertical / AC_horizontal * dTu; @@ -1148,17 +1196,31 @@ void SparseImage::CalculateMipLevelData::calculate_mip_levels() double on_texture_pH_horizontal_vertical_right = on_screen_pH_horizontal_vertical_right / AC_horizontal * dTu; // Texel-to-pixel ratios - double x_texture_to_screen_vertical_ratio = abs(pH_vertical_to_A) < 1.0 ? 0.0 : sqrt(pow(on_texture_pH_vertical_vertical, 2) + pow(on_texture_pH_vertical_horizontal_top, 2)) / abs(pH_vertical_to_A); - double y_texture_to_screen_vertical_ratio = abs(pH_vertical_to_B) < 1.0 ? 0.0 : sqrt(pow(on_texture_pH_vertical_vertical, 2) + pow(on_texture_pH_vertical_horizontal_bottom, 2)) / abs(pH_vertical_to_B); - double x_texture_to_screen_horizontal_ratio = abs(pH_horizontal_to_A) < 1.0 ? 0.0 : sqrt(pow(on_texture_pH_horizontal_horizontal, 2) + pow(on_texture_pH_horizontal_vertical_left, 2)) / abs(pH_horizontal_to_A); - double y_texture_to_screen_horizontal_ratio = abs(pH_horizontal_to_C) < 1.0 ? 0.0 : sqrt(pow(on_texture_pH_horizontal_horizontal, 2) + pow(on_texture_pH_horizontal_vertical_right, 2)) / abs(pH_horizontal_to_C); + double x_texture_to_screen_vertical_ratio = + abs(pH_vertical_to_A) < 1.0 ? + 0.0 : + sqrt(pow(on_texture_pH_vertical_vertical, 2) + pow(on_texture_pH_vertical_horizontal_top, 2)) / abs(pH_vertical_to_A); + double y_texture_to_screen_vertical_ratio = + abs(pH_vertical_to_B) < 1.0 ? + 0.0 : + sqrt(pow(on_texture_pH_vertical_vertical, 2) + pow(on_texture_pH_vertical_horizontal_bottom, 2)) / abs(pH_vertical_to_B); + double x_texture_to_screen_horizontal_ratio = + abs(pH_horizontal_to_A) < 1.0 ? + 0.0 : + sqrt(pow(on_texture_pH_horizontal_horizontal, 2) + pow(on_texture_pH_horizontal_vertical_left, 2)) / abs(pH_horizontal_to_A); + double y_texture_to_screen_horizontal_ratio = + abs(pH_horizontal_to_C) < 1.0 ? + 0.0 : + sqrt(pow(on_texture_pH_horizontal_horizontal, 2) + pow(on_texture_pH_horizontal_vertical_right, 2)) / abs(pH_horizontal_to_C); // Using the log2 formula to calculate required mip level - double delta = std::max(std::max(x_texture_to_screen_horizontal_ratio, y_texture_to_screen_horizontal_ratio), std::max(x_texture_to_screen_vertical_ratio, y_texture_to_screen_vertical_ratio)); + double delta = std::max(std::max(x_texture_to_screen_horizontal_ratio, y_texture_to_screen_horizontal_ratio), + std::max(x_texture_to_screen_vertical_ratio, y_texture_to_screen_vertical_ratio)); double mip_level = std::min(static_cast(mip_levels - 1U), std::max(log2(delta), 0.0)); mip_table[row][column].mip_level = mip_level; - mip_table[row][column].on_screen = mesh[row][column].on_screen || mesh[row + 1][column].on_screen || mesh[row][column + 1].on_screen || mesh[row + 1][column + 1].on_screen; + mip_table[row][column].on_screen = + mesh[row][column].on_screen || mesh[row + 1][column].on_screen || mesh[row][column + 1].on_screen || mesh[row + 1][column + 1].on_screen; } } } @@ -1182,7 +1244,8 @@ void SparseImage::create_vertex_buffer() vertices[3].uv = {0.0f, 1.0f}; auto staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), vertices); - vertex_buffer = std::make_unique(get_device(), vertices_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + vertex_buffer = std::make_unique(get_device(), vertices_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + VMA_MEMORY_USAGE_GPU_ONLY); VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); @@ -1205,7 +1268,8 @@ void SparseImage::create_index_buffer() index_count = indices.size(); auto staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), indices); - index_buffer = std::make_unique(get_device(), indices_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY); + index_buffer = std::make_unique(get_device(), indices_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + VMA_MEMORY_USAGE_GPU_ONLY); VkCommandBuffer command_buffer = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); @@ -1229,11 +1293,7 @@ void SparseImage::create_descriptor_pool() vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1U), }; - VkDescriptorPoolCreateInfo pool_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 1U); + VkDescriptorPoolCreateInfo pool_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 1U); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &pool_info, VK_NULL_HANDLE, &descriptor_pool)); } @@ -1244,18 +1304,9 @@ void SparseImage::create_descriptor_pool() void SparseImage::create_descriptor_set_layout() { std::array set_layout_bindings = { - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0U), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1U), - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 2U), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0U), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1U), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 2U), }; VkDescriptorSetLayoutCreateInfo set_layout_create_info = @@ -1272,11 +1323,7 @@ void SparseImage::create_descriptor_set_layout() */ void SparseImage::create_descriptor_sets() { - VkDescriptorSetAllocateInfo set_alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1U); + VkDescriptorSetAllocateInfo set_alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1U); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &set_alloc_info, &descriptor_set)); @@ -1289,24 +1336,9 @@ void SparseImage::create_descriptor_sets() image_info.sampler = texture_sampler; std::array write_descriptor_sets = { - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0U, - &mvp_buffer_desc_info, - 1U), - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - 1U, - &image_info, - 1U), - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 2U, - &frag_settings_desc_info, - 1U)}; + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0U, &mvp_buffer_desc_info, 1U), + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1U, &image_info, 1U), + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2U, &frag_settings_desc_info, 1U)}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0U, nullptr); } @@ -1330,10 +1362,12 @@ void SparseImage::update_frag_settings() void SparseImage::create_uniform_buffers() { VkDeviceSize buffer_size = sizeof(MVP); - mvp_buffer = std::make_unique(get_device(), buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU, VMA_ALLOCATION_CREATE_MAPPED_BIT); + mvp_buffer = std::make_unique(get_device(), buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU, + VMA_ALLOCATION_CREATE_MAPPED_BIT); buffer_size = sizeof(FragSettingsData); - frag_settings_data_buffer = std::make_unique(get_device(), buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU, VMA_ALLOCATION_CREATE_MAPPED_BIT); + frag_settings_data_buffer = std::make_unique(get_device(), buffer_size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU, + VMA_ALLOCATION_CREATE_MAPPED_BIT); } /** @@ -1453,11 +1487,11 @@ void SparseImage::create_sparse_texture_image() uint32_t sparse_memory_req_count; uint32_t memory_req_count; - vkGetImageSparseMemoryRequirements( - get_device().get_handle(), virtual_texture.texture_image, &sparse_memory_req_count, sparse_image_memory_requirements.data()); + vkGetImageSparseMemoryRequirements(get_device().get_handle(), virtual_texture.texture_image, &sparse_memory_req_count, + sparse_image_memory_requirements.data()); sparse_image_memory_requirements.resize(sparse_memory_req_count); - vkGetImageSparseMemoryRequirements( - get_device().get_handle(), virtual_texture.texture_image, &sparse_memory_req_count, sparse_image_memory_requirements.data()); + vkGetImageSparseMemoryRequirements(get_device().get_handle(), virtual_texture.texture_image, &sparse_memory_req_count, + sparse_image_memory_requirements.data()); vkGetImageMemoryRequirements(get_device().get_handle(), virtual_texture.texture_image, &memory_requirements); @@ -1475,17 +1509,21 @@ void SparseImage::create_sparse_texture_image() for (uint32_t mip_level = 0U; mip_level < virtual_texture.mip_levels; mip_level++) { - size_t numRows = current_mip_height / virtual_texture.format_properties.imageGranularity.height + (current_mip_height % virtual_texture.format_properties.imageGranularity.height == 0U ? 0U : 1U); - size_t numColumns = current_mip_width / virtual_texture.format_properties.imageGranularity.width + (current_mip_width % virtual_texture.format_properties.imageGranularity.width == 0U ? 0U : 1U); + size_t numRows = current_mip_height / virtual_texture.format_properties.imageGranularity.height + + (current_mip_height % virtual_texture.format_properties.imageGranularity.height == 0U ? 0U : 1U); + size_t numColumns = current_mip_width / virtual_texture.format_properties.imageGranularity.width + + (current_mip_width % virtual_texture.format_properties.imageGranularity.width == 0U ? 0U : 1U); num_total_pages += numRows * numColumns; - virtual_texture.mip_properties[mip_level].width = current_mip_width; - virtual_texture.mip_properties[mip_level].height = current_mip_height; - virtual_texture.mip_properties[mip_level].num_columns = numColumns; - virtual_texture.mip_properties[mip_level].num_rows = numRows; - virtual_texture.mip_properties[mip_level].mip_num_pages = numRows * numColumns; - virtual_texture.mip_properties[mip_level].mip_base_page_index = mip_level > 0U ? virtual_texture.mip_properties[mip_level - 1U].mip_base_page_index + virtual_texture.mip_properties[mip_level - 1U].mip_num_pages : 0U; + virtual_texture.mip_properties[mip_level].width = current_mip_width; + virtual_texture.mip_properties[mip_level].height = current_mip_height; + virtual_texture.mip_properties[mip_level].num_columns = numColumns; + virtual_texture.mip_properties[mip_level].num_rows = numRows; + virtual_texture.mip_properties[mip_level].mip_num_pages = numRows * numColumns; + virtual_texture.mip_properties[mip_level].mip_base_page_index = + mip_level > 0U ? virtual_texture.mip_properties[mip_level - 1U].mip_base_page_index + virtual_texture.mip_properties[mip_level - 1U].mip_num_pages : + 0U; if (current_mip_height > 1U) { @@ -1526,13 +1564,19 @@ void SparseImage::create_sparse_texture_image() memory_bind_info.subresource.mipLevel = mipLevel; memory_bind_info.flags = 0U; - memory_bind_info.offset.x = static_cast(((page_index - mip_properties.mip_base_page_index) % mip_properties.num_columns) * virtual_texture.format_properties.imageGranularity.width); - memory_bind_info.offset.y = static_cast(((page_index - mip_properties.mip_base_page_index) / mip_properties.num_columns) * virtual_texture.format_properties.imageGranularity.height); + memory_bind_info.offset.x = static_cast(((page_index - mip_properties.mip_base_page_index) % mip_properties.num_columns) * + virtual_texture.format_properties.imageGranularity.width); + memory_bind_info.offset.y = static_cast(((page_index - mip_properties.mip_base_page_index) / mip_properties.num_columns) * + virtual_texture.format_properties.imageGranularity.height); memory_bind_info.offset.z = 0; memory_bind_info.extent.depth = virtual_texture.format_properties.imageGranularity.depth; - memory_bind_info.extent.width = (mip_properties.width - memory_bind_info.offset.x < virtual_texture.format_properties.imageGranularity.width) ? static_cast(mip_properties.width - memory_bind_info.offset.x) : virtual_texture.format_properties.imageGranularity.width; - memory_bind_info.extent.height = (mip_properties.height - memory_bind_info.offset.y < virtual_texture.format_properties.imageGranularity.height) ? static_cast(mip_properties.height - memory_bind_info.offset.y) : virtual_texture.format_properties.imageGranularity.height; + memory_bind_info.extent.width = (mip_properties.width - memory_bind_info.offset.x < virtual_texture.format_properties.imageGranularity.width) ? + static_cast(mip_properties.width - memory_bind_info.offset.x) : + virtual_texture.format_properties.imageGranularity.width; + memory_bind_info.extent.height = (mip_properties.height - memory_bind_info.offset.y < virtual_texture.format_properties.imageGranularity.height) ? + static_cast(mip_properties.height - memory_bind_info.offset.y) : + virtual_texture.format_properties.imageGranularity.height; } //================================================================================================== @@ -1559,7 +1603,8 @@ void SparseImage::create_sparse_texture_image() subresource_range.levelCount = virtual_texture.mip_levels; subresource_range.baseMipLevel = virtual_texture.base_mip_level; - vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); + vkb::image_layout_transition(command_buffer, virtual_texture.texture_image, VK_IMAGE_LAYOUT_PREINITIALIZED, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + subresource_range); get_device().flush_command_buffer(command_buffer, queue, true); //================================================================================================== diff --git a/samples/extensions/sparse_image/sparse_image.h b/samples/extensions/sparse_image/sparse_image.h index b2845f536a..dfc009630a 100644 --- a/samples/extensions/sparse_image/sparse_image.h +++ b/samples/extensions/sparse_image/sparse_image.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Mobica Limited +/* Copyright (c) 2023-2026, Mobica Limited * * SPDX-License-Identifier: Apache-2.0 * @@ -123,7 +123,8 @@ class SparseImage : public ApiVulkanSample bool fixed = false; // not freed from the memory at any cases PageInfo page_memory_info; // memory-related info - std::set> render_required_set; // set holding information on what BLOCKS require this particular memory page to be valid for rendering + std::set> + render_required_set; // set holding information on what BLOCKS require this particular memory page to be valid for rendering }; struct MemAllocInfo @@ -178,8 +179,7 @@ class SparseImage : public ApiVulkanSample std::set available_offsets; std::set virt_page_indices; - MemSector(MemAllocInfo &mem_alloc_info) : - MemAllocInfo(mem_alloc_info) + MemSector(MemAllocInfo &mem_alloc_info) : MemAllocInfo(mem_alloc_info) { VkMemoryAllocateInfo memory_allocate_info{}; memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; @@ -275,8 +275,21 @@ class SparseImage : public ApiVulkanSample VkExtent2D texture_base_dim; VkExtent2D screen_base_dim; - CalculateMipLevelData(const glm::mat4 &mvp_transform, const VkExtent2D &texture_base_dim, const VkExtent2D &screen_base_dim, uint32_t vertical_num_blocks, uint32_t horizontal_num_blocks, uint8_t mip_levels) : - mesh(vertical_num_blocks + 1U), vertical_num_blocks(vertical_num_blocks), horizontal_num_blocks(horizontal_num_blocks), mip_levels(mip_levels), ax_vertical(horizontal_num_blocks + 1U), ax_horizontal(vertical_num_blocks + 1U), mvp_transform(mvp_transform), texture_base_dim(texture_base_dim), screen_base_dim(screen_base_dim) + CalculateMipLevelData(const glm::mat4 &mvp_transform, + const VkExtent2D &texture_base_dim, + const VkExtent2D &screen_base_dim, + uint32_t vertical_num_blocks, + uint32_t horizontal_num_blocks, + uint8_t mip_levels) : + mesh(vertical_num_blocks + 1U), + vertical_num_blocks(vertical_num_blocks), + horizontal_num_blocks(horizontal_num_blocks), + mip_levels(mip_levels), + ax_vertical(horizontal_num_blocks + 1U), + ax_horizontal(vertical_num_blocks + 1U), + mvp_transform(mvp_transform), + texture_base_dim(texture_base_dim), + screen_base_dim(screen_base_dim) { for (auto &row : mesh) { @@ -285,7 +298,13 @@ class SparseImage : public ApiVulkanSample } CalculateMipLevelData() : - mvp_transform(glm::mat4(0)), texture_base_dim(VkExtent2D{0U, 0U}), screen_base_dim(VkExtent2D{0U, 0U}), mesh{0}, vertical_num_blocks(0U), horizontal_num_blocks(0U), mip_levels(0U) + mvp_transform(glm::mat4(0)), + texture_base_dim(VkExtent2D{0U, 0U}), + screen_base_dim(VkExtent2D{0U, 0U}), + mesh{0}, + vertical_num_blocks(0U), + horizontal_num_blocks(0U), + mip_levels(0U) {} void calculate_mesh_coordinates(); void calculate_mip_levels(); diff --git a/samples/extensions/synchronization_2/synchronization_2.cpp b/samples/extensions/synchronization_2/synchronization_2.cpp index ddb8ec436e..edb0ee8bac 100644 --- a/samples/extensions/synchronization_2/synchronization_2.cpp +++ b/samples/extensions/synchronization_2/synchronization_2.cpp @@ -252,12 +252,8 @@ void Synchronization2::build_compute_command_buffer() void Synchronization2::prepare_storage_buffers() { std::vector attractors = { - glm::vec3(5.0f, 0.0f, 0.0f), - glm::vec3(-5.0f, 0.0f, 0.0f), - glm::vec3(0.0f, 0.0f, 5.0f), - glm::vec3(0.0f, 0.0f, -5.0f), - glm::vec3(0.0f, 4.0f, 0.0f), - glm::vec3(0.0f, -8.0f, 0.0f), + glm::vec3(5.0f, 0.0f, 0.0f), glm::vec3(-5.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 5.0f), + glm::vec3(0.0f, 0.0f, -5.0f), glm::vec3(0.0f, 4.0f, 0.0f), glm::vec3(0.0f, -8.0f, 0.0f), }; num_particles = static_cast(attractors.size()) * PARTICLES_PER_ATTRACTOR; @@ -265,7 +261,8 @@ void Synchronization2::prepare_storage_buffers() // Initial particle positions std::vector particle_buffer(num_particles); - std::default_random_engine rnd_engine((lock_simulation_speed || window->get_window_mode() == vkb::Window::Mode::Headless) ? 0 : static_cast(time(nullptr))); + std::default_random_engine rnd_engine( + (lock_simulation_speed || window->get_window_mode() == vkb::Window::Mode::Headless) ? 0 : static_cast(time(nullptr))); std::normal_distribution rnd_distribution(0.0f, 1.0f); for (uint32_t i = 0; i < static_cast(attractors.size()); i++) @@ -289,7 +286,8 @@ void Synchronization2::prepare_storage_buffers() // Velocity glm::vec3 angular = glm::vec3(0.5f, 1.5f, 0.5f) * (((i % 2) == 0) ? 1.0f : -1.0f); - glm::vec3 velocity = glm::cross((position - attractors[i]), angular) + glm::vec3(rnd_distribution(rnd_engine), rnd_distribution(rnd_engine), rnd_distribution(rnd_engine) * 0.025f); + glm::vec3 velocity = glm::cross((position - attractors[i]), angular) + + glm::vec3(rnd_distribution(rnd_engine), rnd_distribution(rnd_engine), rnd_distribution(rnd_engine) * 0.025f); float mass = (rnd_distribution(rnd_engine) * 0.5f + 0.5f) * 75.0f; particle.pos = glm::vec4(position, mass); @@ -309,10 +307,9 @@ void Synchronization2::prepare_storage_buffers() // SSBO won't be changed on the host after upload so copy to device local memory vkb::core::BufferC staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), particle_buffer); - compute.storage_buffer = std::make_unique(get_device(), - storage_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + compute.storage_buffer = std::make_unique( + get_device(), storage_buffer_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VMA_MEMORY_USAGE_GPU_ONLY); // Copy from staging buffer to storage buffer VkCommandBuffer copy_command = get_device().create_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); @@ -344,17 +341,12 @@ void Synchronization2::prepare_storage_buffers() void Synchronization2::setup_descriptor_pool() { - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -369,27 +361,18 @@ void Synchronization2::setup_descriptor_set_layout() }; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &graphics.descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &graphics.descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&graphics.descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &graphics.pipeline_layout)); } void Synchronization2::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &graphics.descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &graphics.descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &graphics.descriptor_set)); @@ -408,50 +391,25 @@ void Synchronization2::setup_descriptor_set() void Synchronization2::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_POINT_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_POINT_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_ALWAYS); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_ALWAYS); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamicState = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Rendering pipeline // Load shaders @@ -473,11 +431,7 @@ void Synchronization2::prepare_pipelines() vertex_input_state.vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - graphics.pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(graphics.pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -527,57 +481,34 @@ void Synchronization2::prepare_compute() std::vector set_layout_bindings = { // Binding 0 : Particle position storage buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, - VK_SHADER_STAGE_COMPUTE_BIT, - 0), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 0), // Binding 1 : Uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_COMPUTE_BIT, - 1), + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 1), }; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &compute.descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &compute.descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&compute.descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &compute.pipeline_layout)); - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &compute.descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &compute.descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &compute.descriptor_set)); - VkDescriptorBufferInfo storage_buffer_descriptor = create_descriptor(*compute.storage_buffer); - VkDescriptorBufferInfo uniform_buffer_descriptor = create_descriptor(*compute.uniform_buffer); - std::vector compute_write_descriptor_sets = - { - // Binding 0 : Particle position storage buffer - vkb::initializers::write_descriptor_set( - compute.descriptor_set, - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, - 0, - &storage_buffer_descriptor), - // Binding 1 : Uniform buffer - vkb::initializers::write_descriptor_set( - compute.descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 1, - &uniform_buffer_descriptor)}; - - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(compute_write_descriptor_sets.size()), compute_write_descriptor_sets.data(), 0, NULL); + VkDescriptorBufferInfo storage_buffer_descriptor = create_descriptor(*compute.storage_buffer); + VkDescriptorBufferInfo uniform_buffer_descriptor = create_descriptor(*compute.uniform_buffer); + std::vector compute_write_descriptor_sets = { + // Binding 0 : Particle position storage buffer + vkb::initializers::write_descriptor_set(compute.descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, &storage_buffer_descriptor), + // Binding 1 : Uniform buffer + vkb::initializers::write_descriptor_set(compute.descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &uniform_buffer_descriptor)}; + + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(compute_write_descriptor_sets.size()), compute_write_descriptor_sets.data(), 0, + NULL); // Create pipelines VkComputePipelineCreateInfo compute_pipeline_create_info = vkb::initializers::compute_pipeline_create_info(compute.pipeline_layout, 0); @@ -608,8 +539,8 @@ void Synchronization2::prepare_compute() specialization_data.power = 0.8f; specialization_data.soften = 0.7f; - VkSpecializationInfo specialization_info = - vkb::initializers::specialization_info(static_cast(specialization_map_entries.size()), specialization_map_entries.data(), sizeof(specialization_data), &specialization_data); + VkSpecializationInfo specialization_info = vkb::initializers::specialization_info( + static_cast(specialization_map_entries.size()), specialization_map_entries.data(), sizeof(specialization_data), &specialization_data); compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info; VK_CHECK(vkCreateComputePipelines(get_device().get_handle(), pipeline_cache, 1, &compute_pipeline_create_info, nullptr, &compute.pipeline_calculate)); @@ -619,8 +550,7 @@ void Synchronization2::prepare_compute() specialization_map_entries.clear(); specialization_map_entries.push_back(vkb::initializers::specialization_map_entry(0, 0, sizeof(uint32_t))); - specialization_info = - vkb::initializers::specialization_info(1, specialization_map_entries.data(), sizeof(work_group_size), &work_group_size); + specialization_info = vkb::initializers::specialization_info(1, specialization_map_entries.data(), sizeof(work_group_size), &work_group_size); compute_pipeline_create_info.stage.pSpecializationInfo = &specialization_info; VK_CHECK(vkCreateComputePipelines(get_device().get_handle(), pipeline_cache, 1, &compute_pipeline_create_info, nullptr, &compute.pipeline_integrate)); @@ -634,10 +564,7 @@ void Synchronization2::prepare_compute() // Create a command buffer for compute operations VkCommandBufferAllocateInfo command_buffer_allocate_info = - vkb::initializers::command_buffer_allocate_info( - compute.command_pool, - VK_COMMAND_BUFFER_LEVEL_PRIMARY, - 1); + vkb::initializers::command_buffer_allocate_info(compute.command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK(vkAllocateCommandBuffers(get_device().get_handle(), &command_buffer_allocate_info, &compute.command_buffer)); @@ -668,10 +595,7 @@ void Synchronization2::prepare_compute() // Create a transient command buffer for setting up the initial buffer transfer state VkCommandBufferAllocateInfo command_buffer_allocate_info = - vkb::initializers::command_buffer_allocate_info( - compute.command_pool, - VK_COMMAND_BUFFER_LEVEL_PRIMARY, - 1); + vkb::initializers::command_buffer_allocate_info(compute.command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK(vkAllocateCommandBuffers(get_device().get_handle(), &command_buffer_allocate_info, &transfer_command)); @@ -736,16 +660,12 @@ void Synchronization2::prepare_compute() void Synchronization2::prepare_uniform_buffers() { // Compute shader uniform buffer block - compute.uniform_buffer = std::make_unique(get_device(), - sizeof(compute.ubo), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + compute.uniform_buffer = + std::make_unique(get_device(), sizeof(compute.ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); // Vertex shader uniform buffer block - graphics.uniform_buffer = std::make_unique(get_device(), - sizeof(graphics.ubo), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + graphics.uniform_buffer = + std::make_unique(get_device(), sizeof(graphics.ubo), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_compute_uniform_buffers(1.0f); update_graphics_uniform_buffers(); @@ -836,7 +756,8 @@ bool Synchronization2::prepare(const vkb::ApplicationOptions &options) // Not all implementations support a work group size of 256, so we need to check with the device limits work_group_size = std::min(static_cast(256), get_device().get_gpu().get_properties().limits.maxComputeWorkGroupSize[0]); // Same for shared data size for passing data between shader invocations - shared_data_size = std::min(static_cast(1024), static_cast(get_device().get_gpu().get_properties().limits.maxComputeSharedMemorySize / sizeof(glm::vec4))); + shared_data_size = std::min(static_cast(1024), + static_cast(get_device().get_gpu().get_properties().limits.maxComputeSharedMemorySize / sizeof(glm::vec4))); load_assets(); setup_descriptor_pool(); diff --git a/samples/extensions/synchronization_2/synchronization_2.h b/samples/extensions/synchronization_2/synchronization_2.h index e94f9ee3e1..d6e48de986 100644 --- a/samples/extensions/synchronization_2/synchronization_2.h +++ b/samples/extensions/synchronization_2/synchronization_2.h @@ -65,10 +65,10 @@ class Synchronization2 : public ApiVulkanSample // Resources for the compute part of the example struct { - std::unique_ptr storage_buffer; // (Shader) storage buffer object containing the particles - std::unique_ptr uniform_buffer; // Uniform buffer object containing particle system parameters - VkQueue queue; // Separate queue for compute commands (queue family may differ from the one used for graphics) - VkCommandPool command_pool; // Use a separate command pool (queue family may differ from the one used for graphics) + std::unique_ptr storage_buffer; // (Shader) storage buffer object containing the particles + std::unique_ptr uniform_buffer; // Uniform buffer object containing particle system parameters + VkQueue queue; // Separate queue for compute commands (queue family may differ from the one used for graphics) + VkCommandPool command_pool; // Use a separate command pool (queue family may differ from the one used for graphics) VkCommandBuffer command_buffer; // Command buffer storing the dispatch commands and barriers VkFence fence; // Fence to wait for compute dispatch completion before UBO update VkSemaphore semaphore; // Execution dependency between compute & graphic submission diff --git a/samples/extensions/tensor_and_data_graph/compute_shaders_with_tensors/compute_shaders_with_tensors.cpp b/samples/extensions/tensor_and_data_graph/compute_shaders_with_tensors/compute_shaders_with_tensors.cpp index 97c0423d34..89ae8c7cf2 100644 --- a/samples/extensions/tensor_and_data_graph/compute_shaders_with_tensors/compute_shaders_with_tensors.cpp +++ b/samples/extensions/tensor_and_data_graph/compute_shaders_with_tensors/compute_shaders_with_tensors.cpp @@ -155,12 +155,11 @@ void ComputeShadersWithTensors::prepare_input_tensor() std::vector dimensions = {1, 100, 100, 3}; // Create tensor and back it with memory. Set linear tiling flags and host-visible VMA flags so the backing memory can updated from the CPU. // This tensor will be populated in the preprocessing.comp shader. - input_tensor = std::make_unique(get_device(), - TensorBuilder(dimensions) - .with_tiling(VK_TENSOR_TILING_LINEAR_ARM) - .with_usage(VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM | VK_TENSOR_USAGE_SHADER_BIT_ARM) - .with_format(VK_FORMAT_R32_SFLOAT) - .with_vma_required_flags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)); + input_tensor = std::make_unique(get_device(), TensorBuilder(dimensions) + .with_tiling(VK_TENSOR_TILING_LINEAR_ARM) + .with_usage(VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM | VK_TENSOR_USAGE_SHADER_BIT_ARM) + .with_format(VK_FORMAT_R32_SFLOAT) + .with_vma_required_flags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)); input_tensor_view = std::make_unique(*input_tensor); } @@ -184,8 +183,7 @@ void ComputeShadersWithTensors::prepare_weights_tensor() // Set the constant data for the weights. // This is the kernel that will be multiplied against the input to produce the output. weights_constant_tensor->constant_data.resize(3 * 3 * 3 * 3); - MultidimensionalArrayView array_view( - weights_constant_tensor->constant_data.data(), weights_constant_tensor->dimensions); + MultidimensionalArrayView array_view(weights_constant_tensor->constant_data.data(), weights_constant_tensor->dimensions); for (int i = 0; i < 3; ++i) { // First row of the 3x3 kernel @@ -205,26 +203,22 @@ void ComputeShadersWithTensors::prepare_weights_tensor() } // Set up the VkTensorDescriptionARM and pass the dimensions. - weights_constant_tensor->tensor_description = - { - VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM, - nullptr, - VK_TENSOR_TILING_LINEAR_ARM, - VK_FORMAT_R32_SFLOAT, - 4, // dimensions - weights_constant_tensor->dimensions.data(), - nullptr, // pStrides - VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM}; + weights_constant_tensor->tensor_description = {VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM, + nullptr, + VK_TENSOR_TILING_LINEAR_ARM, + VK_FORMAT_R32_SFLOAT, + 4, // dimensions + weights_constant_tensor->dimensions.data(), + nullptr, // pStrides + VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM}; // Set up the VkDataGraphPipelineConstantARM and pass the VkTensorDescriptionARM and constant data. // Also set the id, which should match the SPIR-V module. - weights_constant_tensor->pipeline_constant = - { - VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_CONSTANT_ARM, - &weights_constant_tensor->tensor_description, - 0, // Matches the unique identifier encoded in OpGraphConstantARM in the SPIR-V module - weights_constant_tensor->constant_data.data() // Host pointer to raw data - }; + weights_constant_tensor->pipeline_constant = { + VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_CONSTANT_ARM, &weights_constant_tensor->tensor_description, + 0, // Matches the unique identifier encoded in OpGraphConstantARM in the SPIR-V module + weights_constant_tensor->constant_data.data() // Host pointer to raw data + }; } /* @@ -245,26 +239,22 @@ void ComputeShadersWithTensors::prepare_bias_tensor() bias_constant_tensor->constant_data = {0, 0, 0}; // Set up the VkTensorDescriptionARM and pass the dimensions. - bias_constant_tensor->tensor_description = - { - VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM, - nullptr, - VK_TENSOR_TILING_LINEAR_ARM, - VK_FORMAT_R32_SFLOAT, - 1, // dimensions - bias_constant_tensor->dimensions.data(), - nullptr, // pStrides - VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM}; + bias_constant_tensor->tensor_description = {VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM, + nullptr, + VK_TENSOR_TILING_LINEAR_ARM, + VK_FORMAT_R32_SFLOAT, + 1, // dimensions + bias_constant_tensor->dimensions.data(), + nullptr, // pStrides + VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM}; // Set up the VkDataGraphPipelineConstantARM and pass the VkTensorDescriptionARM and constant data. // Also set the id, which should match the SPIR-V module. - bias_constant_tensor->pipeline_constant = - { - VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_CONSTANT_ARM, - &bias_constant_tensor->tensor_description, - 1, // Matches the unique identifier encoded in OpGraphConstantARM in the SPIR-V module - bias_constant_tensor->constant_data.data() // Host pointer to raw data - }; + bias_constant_tensor->pipeline_constant = { + VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_CONSTANT_ARM, &bias_constant_tensor->tensor_description, + 1, // Matches the unique identifier encoded in OpGraphConstantARM in the SPIR-V module + bias_constant_tensor->constant_data.data() // Host pointer to raw data + }; } /* @@ -276,19 +266,16 @@ void ComputeShadersWithTensors::prepare_output_tensors() // The output of the network is determined by the kernel size (2 x 2), // strides (1, 1), dilation (1, 1) and padding (0, 0, 0, 0). std::vector dimensions = {1, 100, 100, 3}; - output_tensor = std::make_unique(get_device(), - TensorBuilder(dimensions) - .with_usage(VK_TENSOR_USAGE_SHADER_BIT_ARM | VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM) - .with_format(VK_FORMAT_R32_SFLOAT)); + output_tensor = std::make_unique( + get_device(), + TensorBuilder(dimensions).with_usage(VK_TENSOR_USAGE_SHADER_BIT_ARM | VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM).with_format(VK_FORMAT_R32_SFLOAT)); output_tensor_view = std::make_unique(*output_tensor); // Also create second output tensor which is used by the visualization pipeline. // It contains a copy of output_tensor, which is copied in the postprocessing compute shader. - postprocessed_tensor = std::make_unique(get_device(), - TensorBuilder(dimensions) - .with_usage(VK_TENSOR_USAGE_SHADER_BIT_ARM) - .with_format(VK_FORMAT_R32_SFLOAT)); + postprocessed_tensor = + std::make_unique(get_device(), TensorBuilder(dimensions).with_usage(VK_TENSOR_USAGE_SHADER_BIT_ARM).with_format(VK_FORMAT_R32_SFLOAT)); postprocessed_tensor_view = std::make_unique(*postprocessed_tensor); } @@ -299,10 +286,9 @@ void ComputeShadersWithTensors::prepare_output_tensors() */ void ComputeShadersWithTensors::prepare_output_image(uint32_t width, uint32_t height) { - output_image = std::make_unique(get_device(), - vkb::core::ImageBuilder(VkExtent3D{width, height, 1}) - .with_format(VK_FORMAT_R8G8B8A8_UNORM) - .with_usage(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)); + output_image = std::make_unique(get_device(), vkb::core::ImageBuilder(VkExtent3D{width, height, 1}) + .with_format(VK_FORMAT_R8G8B8A8_UNORM) + .with_usage(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)); output_image_view = std::make_unique(*output_image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM); } @@ -323,12 +309,10 @@ void ComputeShadersWithTensors::prepare_data_graph_pipeline() // be bound to the pipeline. std::map> tensor_descriptions; // All bindings are in set 0 - tensor_descriptions[0] = - { - // Binding 0 is the input tensor - {0, &input_tensor->get_description()}, - // Binding 1 is the output tensor - {1, &output_tensor->get_description()}}; + tensor_descriptions[0] = {// Binding 0 is the input tensor + {0, &input_tensor->get_description()}, + // Binding 1 is the output tensor + {1, &output_tensor->get_description()}}; // Add weights and bias constant tensors, which were prepared and stored earlier. std::vector data_graph_pipeline_constants; @@ -337,12 +321,8 @@ void ComputeShadersWithTensors::prepare_data_graph_pipeline() VkShaderModule shader_module = vkb::load_shader("tensor_and_data_graph/spirv/conv2d.spvasm.spv", get_device().get_handle(), VK_SHADER_STAGE_ALL); - data_graph_pipeline = std::make_unique(get_device(), - data_graph_pipeline_layout->get_handle(), - shader_module, - "main", - tensor_descriptions, - data_graph_pipeline_constants); + data_graph_pipeline = std::make_unique(get_device(), data_graph_pipeline_layout->get_handle(), shader_module, "main", + tensor_descriptions, data_graph_pipeline_constants); // Create a Pipeline Session for the Pipeline. Unlike compute and graphics pipelines, data graph pipelines require // additional state to be stored (e.g. for intermediate results). This is stored separately to the pipeline itself in @@ -365,23 +345,23 @@ void ComputeShadersWithTensors::prepare_data_graph_pipeline_descriptor_set() VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &data_graph_pipeline_descriptor_set)); // Write bindings to it, telling it which tensors to use as input and output - std::map tensor_bindings = - { - // Binding 0 is the input tensor - {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, - // Binding 1 is the output tensor - {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; + std::map tensor_bindings = { + // Binding 0 is the input tensor + {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, + // Binding 1 is the output tensor + {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; write_descriptor_set(get_device().get_handle(), data_graph_pipeline_descriptor_set, {}, tensor_bindings); } /* - * Creates the Pipeline Layout and a Compute Pipeline used to run the compute shader, which generates a pattern and is written to a tensor to be consumed by the data graph pipeline. + * Creates the Pipeline Layout and a Compute Pipeline used to run the compute shader, which generates a pattern and is written to a tensor to be consumed by the + * data graph pipeline. */ void ComputeShadersWithTensors::prepare_preprocessing_pipeline() { // Load the compute shader - vkb::ShaderModule &input_comp = - get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/compute_shaders_with_tensors/glsl/preprocessing.comp.spv"}); + vkb::ShaderModule &input_comp = get_device().get_resource_cache().request_shader_module( + VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/compute_shaders_with_tensors/glsl/preprocessing.comp.spv"}); // Create pipeline layout from the reflected shader code. Note that this will include bindings to Tensor resources, so we use our own // class to do this, rather than the sample framework's vkb::PipelineLayout. @@ -396,7 +376,8 @@ void ComputeShadersWithTensors::prepare_preprocessing_pipeline() */ void ComputeShadersWithTensors::prepare_preprocessing_pipeline_descriptor_set() { - // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than allocating a new one) + // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than + // allocating a new one) if (preprocessing_pipeline_descriptor_set == VK_NULL_HANDLE) { VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; @@ -407,21 +388,21 @@ void ComputeShadersWithTensors::prepare_preprocessing_pipeline_descriptor_set() } // Write binding 0, which is the input tensor. - std::map tensor_bindings = - { - {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}}; + std::map tensor_bindings = { + {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}}; write_descriptor_set(get_device().get_handle(), preprocessing_pipeline_descriptor_set, {}, tensor_bindings); } /* - * Creates the Pipeline Layout and a Compute Pipeline used to run the compute shader which copies the data graph pipeline output to another tensor to be consumed by the visualization pipeline. + * Creates the Pipeline Layout and a Compute Pipeline used to run the compute shader which copies the data graph pipeline output to another tensor to be + * consumed by the visualization pipeline. */ void ComputeShadersWithTensors::prepare_postprocessing_pipeline() { // Load the compute shader - vkb::ShaderModule &output_comp = - get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/compute_shaders_with_tensors/glsl/postprocessing.comp.spv"}); + vkb::ShaderModule &output_comp = get_device().get_resource_cache().request_shader_module( + VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/compute_shaders_with_tensors/glsl/postprocessing.comp.spv"}); // Create pipeline layout from the reflected shader code. Note that this will include bindings to Tensor resources, so we use our own // class to do this, rather than the sample framework's vkb::PipelineLayout. @@ -436,7 +417,8 @@ void ComputeShadersWithTensors::prepare_postprocessing_pipeline() */ void ComputeShadersWithTensors::prepare_postprocessing_pipeline_descriptor_set() { - // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than allocating a new one) + // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than + // allocating a new one) if (postprocessing_pipeline_descriptor_set == VK_NULL_HANDLE) { VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; @@ -447,12 +429,11 @@ void ComputeShadersWithTensors::prepare_postprocessing_pipeline_descriptor_set() } // Write bindings - std::map tensor_bindings = - { - // Binding 0 is the output tensor from the data graph pipeline - {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}, - // Binding 1 is the postprocessed tensor, which is written to. - {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &postprocessed_tensor_view->get_handle()}}}; + std::map tensor_bindings = { + // Binding 0 is the output tensor from the data graph pipeline + {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}, + // Binding 1 is the postprocessed tensor, which is written to. + {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &postprocessed_tensor_view->get_handle()}}}; write_descriptor_set(get_device().get_handle(), postprocessing_pipeline_descriptor_set, {}, tensor_bindings); } @@ -464,8 +445,8 @@ void ComputeShadersWithTensors::prepare_postprocessing_pipeline_descriptor_set() void ComputeShadersWithTensors::prepare_visualization_pipeline() { // Load the compute shader - vkb::ShaderModule &visualization_comp = - get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/compute_shaders_with_tensors/glsl/visualization_three_tensors.comp.spv"}); + vkb::ShaderModule &visualization_comp = get_device().get_resource_cache().request_shader_module( + VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/compute_shaders_with_tensors/glsl/visualization_three_tensors.comp.spv"}); // Create pipeline layout from the reflected shader code. Note that this will include bindings to Tensor resources, so we use our own // class to do this, rather than the sample framework's vkb::PipelineLayout. @@ -480,7 +461,8 @@ void ComputeShadersWithTensors::prepare_visualization_pipeline() */ void ComputeShadersWithTensors::prepare_visualization_pipeline_descriptor_set() { - // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than allocating a new one) + // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than + // allocating a new one) if (visualization_pipeline_descriptor_set == VK_NULL_HANDLE) { VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; @@ -491,19 +473,17 @@ void ComputeShadersWithTensors::prepare_visualization_pipeline_descriptor_set() } // Write bindings to it - std::map tensor_bindings = - { - // Binding 0 is the input tensor - {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, - // Binding 1 is the output tensor - {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}, - // Binding 2 is the postprocessed tensor - {2, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &postprocessed_tensor_view->get_handle()}}}; - - std::map image_bindings = - { - // Binding 3 is the output image - {3, VkDescriptorImageInfo{VK_NULL_HANDLE, output_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL}}}; + std::map tensor_bindings = { + // Binding 0 is the input tensor + {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, + // Binding 1 is the output tensor + {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}, + // Binding 2 is the postprocessed tensor + {2, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &postprocessed_tensor_view->get_handle()}}}; + + std::map image_bindings = { + // Binding 3 is the output image + {3, VkDescriptorImageInfo{VK_NULL_HANDLE, output_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL}}}; write_descriptor_set(get_device().get_handle(), visualization_pipeline_descriptor_set, image_bindings, tensor_bindings); } @@ -554,12 +534,12 @@ void ComputeShadersWithTensors::draw_renderpass(vkb::core::CommandBufferC &comma { // Bind preprocessing pipeline vkCmdBindPipeline(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, preprocessing_pipeline->get_handle()); - vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, preprocessing_pipeline_layout->get_handle(), - 0, 1, &preprocessing_pipeline_descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, preprocessing_pipeline_layout->get_handle(), 0, 1, + &preprocessing_pipeline_descriptor_set, 0, nullptr); // Pass seconds as a push constant and run/dispatch preprocessing shader - vkCmdPushConstants(command_buffer.get_handle(), preprocessing_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, - sizeof(glm::float32), &elapsed_seconds_num); + vkCmdPushConstants(command_buffer.get_handle(), preprocessing_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(glm::float32), + &elapsed_seconds_num); uint32_t group_count_x = input_tensor->get_description().pDimensions[2]; // The preprocessing shader has a group size of 1 uint32_t group_count_y = input_tensor->get_description().pDimensions[1]; vkCmdDispatch(command_buffer.get_handle(), group_count_x, group_count_y, 1); @@ -594,8 +574,8 @@ void ComputeShadersWithTensors::draw_renderpass(vkb::core::CommandBufferC &comma // Bind and run data graph pipeline. vkCmdBindPipeline(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline->get_handle()); - vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline_layout->get_handle(), - 0, 1, &data_graph_pipeline_descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline_layout->get_handle(), 0, 1, + &data_graph_pipeline_descriptor_set, 0, nullptr); vkCmdDispatchDataGraphARM(command_buffer.get_handle(), data_graph_pipeline_session->get_handle(), VK_NULL_HANDLE); // Barrier for `output_tensor` (written to by the data graph pipeline above, and read from by the postprocess compute shader below) @@ -627,10 +607,10 @@ void ComputeShadersWithTensors::draw_renderpass(vkb::core::CommandBufferC &comma // Run post-processing shader { vkCmdBindPipeline(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, postprocessing_pipeline->get_handle()); - vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, postprocessing_pipeline_layout->get_handle(), - 0, 1, &postprocessing_pipeline_descriptor_set, 0, nullptr); - vkCmdPushConstants(command_buffer.get_handle(), postprocessing_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, - sizeof(glm::float32), &elapsed_seconds_num); + vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, postprocessing_pipeline_layout->get_handle(), 0, 1, + &postprocessing_pipeline_descriptor_set, 0, nullptr); + vkCmdPushConstants(command_buffer.get_handle(), postprocessing_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(glm::float32), + &elapsed_seconds_num); uint32_t group_count_x = postprocessed_tensor->get_description().pDimensions[2]; // The postprocessing shader has a group size of 1 uint32_t group_count_y = postprocessed_tensor->get_description().pDimensions[1]; vkCmdDispatch(command_buffer.get_handle(), group_count_x, group_count_y, 1); @@ -689,12 +669,12 @@ void ComputeShadersWithTensors::draw_renderpass(vkb::core::CommandBufferC &comma // Run visualization compute pipeline { vkCmdBindPipeline(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline->get_handle()); - vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline_layout->get_handle(), - 0, 1, &visualization_pipeline_descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline_layout->get_handle(), 0, 1, + &visualization_pipeline_descriptor_set, 0, nullptr); // Pass the output_image size as a push constant - vkCmdPushConstants(command_buffer.get_handle(), visualization_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, - sizeof(glm::uvec2), &render_target.get_extent()); + vkCmdPushConstants(command_buffer.get_handle(), visualization_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(glm::uvec2), + &render_target.get_extent()); uint32_t group_count_x = (render_target.get_extent().width + 7) / 8; // The visualization shader has a group size of 8 uint32_t group_count_y = (render_target.get_extent().height + 7) / 8; vkCmdDispatch(command_buffer.get_handle(), group_count_x, group_count_y, 1); diff --git a/samples/extensions/tensor_and_data_graph/compute_shaders_with_tensors/compute_shaders_with_tensors.h b/samples/extensions/tensor_and_data_graph/compute_shaders_with_tensors/compute_shaders_with_tensors.h index d2737b6ace..5325b71e5c 100644 --- a/samples/extensions/tensor_and_data_graph/compute_shaders_with_tensors/compute_shaders_with_tensors.h +++ b/samples/extensions/tensor_and_data_graph/compute_shaders_with_tensors/compute_shaders_with_tensors.h @@ -30,11 +30,11 @@ * @details A `Tensor` resource (`input_tensor`) is created by the preprocessing compute shader. This is read as an input by a `Data Graph Pipeline` * (`data_graph_pipeline`). * The Data Graph Pipeline runs a neural network and produces an output which is written into the `output_tensor` Tensor. - * Two constant tensors (`constant_weights_tensor` & `constant_bias_tensor`) are also passed into the Convolution2d operator in the form of weights and bias. - * The `output_tensor` is then copied to `postprocessed_tensor` by another compute shader simply for demonstrative purposes. - * In reality this shader would be used for postprocessing, hence the shader name (`postprocessing.comp`). - * In order to visualize the results of this pipeline, there is a Compute Pipeline (`visualization_pipeline`) which copies the - * contents of the `input_tensor`, `output_tensor` and `postprocessed_tensor` into an Image (`output_image`) which is blitted to the Swapchain. + * Two constant tensors (`constant_weights_tensor` & `constant_bias_tensor`) are also passed into the Convolution2d operator in the form of weights and + *bias. The `output_tensor` is then copied to `postprocessed_tensor` by another compute shader simply for demonstrative purposes. In reality this shader would + *be used for postprocessing, hence the shader name (`postprocessing.comp`). In order to visualize the results of this pipeline, there is a Compute Pipeline + *(`visualization_pipeline`) which copies the contents of the `input_tensor`, `output_tensor` and `postprocessed_tensor` into an Image (`output_image`) which is + *blitted to the Swapchain. * * As a diagram, this looks like: * @@ -42,7 +42,8 @@ * \ / * preprocessing_pipeline -> input_tensor -> data_graph_pipeline -> output_tensor -> postprocessing_pipeline -> postprocessed_tensor * \ \ - * \--------------------------------------------------------------> visualization_pipeline -> output_image -> blit -> swapchain + * \--------------------------------------------------------------> visualization_pipeline -> output_image -> blit -> + *swapchain * * Because the common Vulkan Samples framework code is not aware of the Tensor resource type or Data Graph Pipelines, * generic functionality for these concepts has been added to a new tensor_and_data_graph_common.h/cpp file, which this sample diff --git a/samples/extensions/tensor_and_data_graph/graph_constants/graph_constants.cpp b/samples/extensions/tensor_and_data_graph/graph_constants/graph_constants.cpp index e6a81cd19f..84621c0cc3 100644 --- a/samples/extensions/tensor_and_data_graph/graph_constants/graph_constants.cpp +++ b/samples/extensions/tensor_and_data_graph/graph_constants/graph_constants.cpp @@ -146,12 +146,11 @@ void GraphConstants::prepare_input_tensor() // In this case we are going to represent a small RGB image, so have a batch size of 1, a width and height of 20 and 3 channels. std::vector dimensions = {1, 20, 20, 3}; // Create tensor and back it with memory. Set linear tiling flags and host-visible VMA flags so the backing memory can updated from the CPU. - input_tensor = std::make_unique(get_device(), - TensorBuilder(dimensions) - .with_tiling(VK_TENSOR_TILING_LINEAR_ARM) - .with_usage(VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM | VK_TENSOR_USAGE_SHADER_BIT_ARM) - .with_format(VK_FORMAT_R32_SFLOAT) - .with_vma_required_flags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)); + input_tensor = std::make_unique(get_device(), TensorBuilder(dimensions) + .with_tiling(VK_TENSOR_TILING_LINEAR_ARM) + .with_usage(VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM | VK_TENSOR_USAGE_SHADER_BIT_ARM) + .with_format(VK_FORMAT_R32_SFLOAT) + .with_vma_required_flags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)); // Upload fixed initial data - White square (12 x 12 pixels) with a blue background. std::vector input_tensor_data; @@ -163,7 +162,8 @@ void GraphConstants::prepare_input_tensor() for (int x = 0; x < dimensions[2]; ++x) { // Fill initially with blue color otherwise, overwrite with white color if position is within the square. - auto color = ((offset <= y) && (y < right_offset) && (offset <= x) && (x < right_offset)) ? glm::fvec3(1.0f, 1.0f, 1.0f) : glm::fvec3(0.0f, 0.0f, 1.0f); + auto color = + ((offset <= y) && (y < right_offset) && (offset <= x) && (x < right_offset)) ? glm::fvec3(1.0f, 1.0f, 1.0f) : glm::fvec3(0.0f, 0.0f, 1.0f); input_tensor_data.push_back(color); } } @@ -191,8 +191,7 @@ void GraphConstants::prepare_weights_tensor() // Set the constant data for the weights. // This is the kernel that will be multiplied against the input to produce the output. weights_constant_tensor->constant_data.resize(3 * 3 * 3 * 3); - MultidimensionalArrayView array_view( - weights_constant_tensor->constant_data.data(), weights_constant_tensor->dimensions); + MultidimensionalArrayView array_view(weights_constant_tensor->constant_data.data(), weights_constant_tensor->dimensions); for (int i = 0; i < 3; ++i) { // First row of the 3x3 kernel @@ -212,26 +211,22 @@ void GraphConstants::prepare_weights_tensor() } // Set up the VkTensorDescriptionARM and pass the dimensions. - weights_constant_tensor->tensor_description = - { - VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM, - nullptr, - VK_TENSOR_TILING_LINEAR_ARM, - VK_FORMAT_R32_SFLOAT, - 4, // dimensions - weights_constant_tensor->dimensions.data(), - nullptr, // pStrides - VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM}; + weights_constant_tensor->tensor_description = {VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM, + nullptr, + VK_TENSOR_TILING_LINEAR_ARM, + VK_FORMAT_R32_SFLOAT, + 4, // dimensions + weights_constant_tensor->dimensions.data(), + nullptr, // pStrides + VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM}; // Set up the VkDataGraphPipelineConstantARM and pass the VkTensorDescriptionARM and constant data. // Also set the id, which should match the SPIR-V module. - weights_constant_tensor->pipeline_constant = - { - VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_CONSTANT_ARM, - &weights_constant_tensor->tensor_description, - 0, // Matches the unique identifier encoded in OpGraphConstantARM in the SPIR-V module - weights_constant_tensor->constant_data.data() // Host pointer to raw data - }; + weights_constant_tensor->pipeline_constant = { + VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_CONSTANT_ARM, &weights_constant_tensor->tensor_description, + 0, // Matches the unique identifier encoded in OpGraphConstantARM in the SPIR-V module + weights_constant_tensor->constant_data.data() // Host pointer to raw data + }; } /* @@ -252,26 +247,22 @@ void GraphConstants::prepare_bias_tensor() bias_constant_tensor->constant_data = {0, 0, 0}; // Set up the VkTensorDescriptionARM and pass the dimensions. - bias_constant_tensor->tensor_description = - { - VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM, - nullptr, - VK_TENSOR_TILING_LINEAR_ARM, - VK_FORMAT_R32_SFLOAT, - 1, // dimensions - bias_constant_tensor->dimensions.data(), - nullptr, // pStrides - VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM}; + bias_constant_tensor->tensor_description = {VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM, + nullptr, + VK_TENSOR_TILING_LINEAR_ARM, + VK_FORMAT_R32_SFLOAT, + 1, // dimensions + bias_constant_tensor->dimensions.data(), + nullptr, // pStrides + VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM}; // Set up the VkDataGraphPipelineConstantARM and pass the VkTensorDescriptionARM and constant data. // Also set the id, which should match the SPIR-V module. - bias_constant_tensor->pipeline_constant = - { - VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_CONSTANT_ARM, - &bias_constant_tensor->tensor_description, - 1, // Matches the unique identifier encoded in OpGraphConstantARM in the SPIR-V module - bias_constant_tensor->constant_data.data() // Host pointer to raw data - }; + bias_constant_tensor->pipeline_constant = { + VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_CONSTANT_ARM, &bias_constant_tensor->tensor_description, + 1, // Matches the unique identifier encoded in OpGraphConstantARM in the SPIR-V module + bias_constant_tensor->constant_data.data() // Host pointer to raw data + }; } /* @@ -283,10 +274,9 @@ void GraphConstants::prepare_output_tensor() // The output shape of the network is determined by the kernel size (3 x 3), // strides (2, 2), dilation (1, 1) and padding (0, 0, 0, 0). std::vector dimensions = {1, 20, 20, 3}; - output_tensor = std::make_unique(get_device(), - TensorBuilder(dimensions) - .with_usage(VK_TENSOR_USAGE_SHADER_BIT_ARM | VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM) - .with_format(VK_FORMAT_R32_SFLOAT)); + output_tensor = std::make_unique( + get_device(), + TensorBuilder(dimensions).with_usage(VK_TENSOR_USAGE_SHADER_BIT_ARM | VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM).with_format(VK_FORMAT_R32_SFLOAT)); output_tensor_view = std::make_unique(*output_tensor); } @@ -297,10 +287,9 @@ void GraphConstants::prepare_output_tensor() */ void GraphConstants::prepare_output_image(uint32_t width, uint32_t height) { - output_image = std::make_unique(get_device(), - vkb::core::ImageBuilder(VkExtent3D{width, height, 1}) - .with_format(VK_FORMAT_R8G8B8A8_UNORM) - .with_usage(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)); + output_image = std::make_unique(get_device(), vkb::core::ImageBuilder(VkExtent3D{width, height, 1}) + .with_format(VK_FORMAT_R8G8B8A8_UNORM) + .with_usage(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)); output_image_view = std::make_unique(*output_image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM); } @@ -321,12 +310,10 @@ void GraphConstants::prepare_data_graph_pipeline() // be bound to the pipeline. std::map> tensor_descriptions; // All bindings are in set 0 - tensor_descriptions[0] = - { - // Binding 0 is the input tensor - {0, &input_tensor->get_description()}, - // Binding 1 is the output tensor - {1, &output_tensor->get_description()}}; + tensor_descriptions[0] = {// Binding 0 is the input tensor + {0, &input_tensor->get_description()}, + // Binding 1 is the output tensor + {1, &output_tensor->get_description()}}; // Add weights and bias constant tensors, which were prepared and stored earlier. std::vector data_graph_pipeline_constants; @@ -335,12 +322,8 @@ void GraphConstants::prepare_data_graph_pipeline() VkShaderModule shader_module = vkb::load_shader("tensor_and_data_graph/spirv/conv2d.spvasm.spv", get_device().get_handle(), VK_SHADER_STAGE_ALL); - data_graph_pipeline = std::make_unique(get_device(), - data_graph_pipeline_layout->get_handle(), - shader_module, - "main", - tensor_descriptions, - data_graph_pipeline_constants); + data_graph_pipeline = std::make_unique(get_device(), data_graph_pipeline_layout->get_handle(), shader_module, "main", + tensor_descriptions, data_graph_pipeline_constants); // Create a Pipeline Session for the Pipeline. Unlike compute and graphics pipelines, data graph pipelines require // additional state to be stored (e.g. for intermediate results). This is stored separately to the pipeline itself in @@ -363,12 +346,11 @@ void GraphConstants::prepare_data_graph_pipeline_descriptor_set() VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &data_graph_pipeline_descriptor_set)); // Write bindings to it, telling it which tensors to use as input and output - std::map tensor_bindings = - { - // Binding 0 is the input tensor - {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, - // Binding 1 is the output tensor - {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; + std::map tensor_bindings = { + // Binding 0 is the input tensor + {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, + // Binding 1 is the output tensor + {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; write_descriptor_set(get_device().get_handle(), data_graph_pipeline_descriptor_set, {}, tensor_bindings); } @@ -379,8 +361,8 @@ void GraphConstants::prepare_data_graph_pipeline_descriptor_set() void GraphConstants::prepare_visualization_pipeline() { // Load the compute shader - vkb::ShaderModule &visualization_comp = - get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/glsl/visualization_two_tensors.comp.spv"}); + vkb::ShaderModule &visualization_comp = get_device().get_resource_cache().request_shader_module( + VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/glsl/visualization_two_tensors.comp.spv"}); // Create pipeline layout from the reflected shader code. Note that this will include bindings to Tensor resources, so we use our own // class to do this, rather than the sample framework's vkb::PipelineLayout. @@ -395,7 +377,8 @@ void GraphConstants::prepare_visualization_pipeline() */ void GraphConstants::prepare_visualization_pipeline_descriptor_set() { - // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than allocating a new one) + // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than + // allocating a new one) if (visualization_pipeline_descriptor_set == VK_NULL_HANDLE) { VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; @@ -406,17 +389,15 @@ void GraphConstants::prepare_visualization_pipeline_descriptor_set() } // Write bindings to it - std::map tensor_bindings = - { - // Binding 0 is the input tensor - {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, - // Binding 1 is the output tensor - {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; - - std::map image_bindings = - { - // Binding 2 is the output image - {2, VkDescriptorImageInfo{VK_NULL_HANDLE, output_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL}}}; + std::map tensor_bindings = { + // Binding 0 is the input tensor + {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, + // Binding 1 is the output tensor + {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; + + std::map image_bindings = { + // Binding 2 is the output image + {2, VkDescriptorImageInfo{VK_NULL_HANDLE, output_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL}}}; write_descriptor_set(get_device().get_handle(), visualization_pipeline_descriptor_set, image_bindings, tensor_bindings); } @@ -445,8 +426,8 @@ void GraphConstants::draw_renderpass(vkb::core::CommandBufferC &command_buffer, { // Bind and run data graph pipeline. vkCmdBindPipeline(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline->get_handle()); - vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline_layout->get_handle(), - 0, 1, &data_graph_pipeline_descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline_layout->get_handle(), 0, 1, + &data_graph_pipeline_descriptor_set, 0, nullptr); vkCmdDispatchDataGraphARM(command_buffer.get_handle(), data_graph_pipeline_session->get_handle(), VK_NULL_HANDLE); // Barrier for `output_tensor` (written to by the data graph pipeline above, and read from by the visualization compute shader below) @@ -473,12 +454,12 @@ void GraphConstants::draw_renderpass(vkb::core::CommandBufferC &command_buffer, // Bind and run visualization compute pipeline vkCmdBindPipeline(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline->get_handle()); - vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline_layout->get_handle(), - 0, 1, &visualization_pipeline_descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline_layout->get_handle(), 0, 1, + &visualization_pipeline_descriptor_set, 0, nullptr); // Pass the output_image size as a push constant - vkCmdPushConstants(command_buffer.get_handle(), visualization_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, - sizeof(glm::uvec2), &render_target.get_extent()); + vkCmdPushConstants(command_buffer.get_handle(), visualization_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(glm::uvec2), + &render_target.get_extent()); uint32_t group_count_x = (render_target.get_extent().width + 7) / 8; // The visualization shader has a group size of 8 uint32_t group_count_y = (render_target.get_extent().height + 7) / 8; vkCmdDispatch(command_buffer.get_handle(), group_count_x, group_count_y, 1); @@ -545,8 +526,7 @@ void GraphConstants::draw_gui() // Draw arrow between input and output. draw_list->AddLine(ImVec2(cx - 60, cy), ImVec2(cx + 30, cy), IM_COL32_WHITE, 5.0f); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(cx + 60.0f, cy), - ImVec2(30.0f, 10.0f), ImGuiDir_Right, IM_COL32_WHITE); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(cx + 60.0f, cy), ImVec2(30.0f, 10.0f), ImGuiDir_Right, IM_COL32_WHITE); ImVec2 text_size = ImGui::CalcTextSize("Conv2d"); draw_list->AddText(ImVec2(cx - text_size.x / 2, cy + 20), IM_COL32_WHITE, "Conv2d"); @@ -581,8 +561,7 @@ void GraphConstants::draw_gui() // Draw line and arrow draw_list->AddLine(ImVec2(cx, cy - 110), ImVec2(cx, cy - 80), IM_COL32_WHITE, 5.0f); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(cx, cy - 50), - ImVec2(10.0f, 30.0f), ImGuiDir_Down, IM_COL32_WHITE); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(cx, cy - 50), ImVec2(10.0f, 30.0f), ImGuiDir_Down, IM_COL32_WHITE); // Draw table for Bias ImVec2 bias_size = ImGui::CalcTextSize("Biases"); @@ -598,8 +577,7 @@ void GraphConstants::draw_gui() // Draw line and arrow draw_list->AddLine(ImVec2(cx, cy + 140), ImVec2(cx, cy + 110), IM_COL32_WHITE, 5.0f); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(cx, cy + 80), - ImVec2(10.0f, 30.0f), ImGuiDir_Up, IM_COL32_WHITE); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(cx, cy + 80), ImVec2(10.0f, 30.0f), ImGuiDir_Up, IM_COL32_WHITE); } std::unique_ptr create_graph_constants() diff --git a/samples/extensions/tensor_and_data_graph/graph_constants/graph_constants.h b/samples/extensions/tensor_and_data_graph/graph_constants/graph_constants.h index 1838ba1fdc..89ae1fa0a6 100644 --- a/samples/extensions/tensor_and_data_graph/graph_constants/graph_constants.h +++ b/samples/extensions/tensor_and_data_graph/graph_constants/graph_constants.h @@ -30,10 +30,10 @@ * @details A `Tensor` resource (`input_tensor`) is created and initial contents are uploaded. This is a new resource type analogous * to Images and Buffers. This is read as an input by a `Data Graph Pipeline` (`data_graph_pipeline`). * The Data Graph Pipeline runs a neural network and produces an output which is written into the `output_tensor` Tensor. - * Two constant tensors (`constant_weights_tensor` & `constant_bias_tensor`) are also passed into the Convolution2d operator in the form of weights and bias. - * The weights/filter/kernel is used to generate the output. The specified bias is applied to the output for each channel. - * In order to visualize the results of this pipeline, there is a Compute Pipeline (`visualization_pipeline`) which copies the - * contents of `input_tensor` and `output_tensor` into an Image (`output_image`) which is blitted to the Swapchain. + * Two constant tensors (`constant_weights_tensor` & `constant_bias_tensor`) are also passed into the Convolution2d operator in the form of weights and + *bias. The weights/filter/kernel is used to generate the output. The specified bias is applied to the output for each channel. In order to visualize the + *results of this pipeline, there is a Compute Pipeline (`visualization_pipeline`) which copies the contents of `input_tensor` and `output_tensor` into an Image + *(`output_image`) which is blitted to the Swapchain. * * As a diagram, this looks like: * diff --git a/samples/extensions/tensor_and_data_graph/simple_tensor_and_data_graph/simple_tensor_and_data_graph.cpp b/samples/extensions/tensor_and_data_graph/simple_tensor_and_data_graph/simple_tensor_and_data_graph.cpp index 505955f368..72e59122d6 100644 --- a/samples/extensions/tensor_and_data_graph/simple_tensor_and_data_graph/simple_tensor_and_data_graph.cpp +++ b/samples/extensions/tensor_and_data_graph/simple_tensor_and_data_graph/simple_tensor_and_data_graph.cpp @@ -141,12 +141,11 @@ void SimpleTensorAndDataGraph::prepare_input_tensor() // In this case we are going to represent a small RGB image, so have a batch size of 1, a width and height of 10 and 3 channels. std::vector dimensions = {1, 10, 10, 3}; // Create tensor and back it with memory. Set linear tiling flags and host-visible VMA flags so the backing memory can updated from the CPU. - input_tensor = std::make_unique(get_device(), - TensorBuilder(dimensions) - .with_tiling(VK_TENSOR_TILING_LINEAR_ARM) - .with_usage(VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM | VK_TENSOR_USAGE_SHADER_BIT_ARM) - .with_format(VK_FORMAT_R32_SFLOAT) - .with_vma_required_flags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)); + input_tensor = std::make_unique(get_device(), TensorBuilder(dimensions) + .with_tiling(VK_TENSOR_TILING_LINEAR_ARM) + .with_usage(VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM | VK_TENSOR_USAGE_SHADER_BIT_ARM) + .with_format(VK_FORMAT_R32_SFLOAT) + .with_vma_required_flags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)); // Upload fixed initial data - smoothly varying colors over the square std::vector input_tensor_data; for (int y = 0; y < dimensions[1]; ++y) @@ -172,10 +171,9 @@ void SimpleTensorAndDataGraph::prepare_output_tensor() // The output of the network is half the width and height of the input, but still RGB. std::vector dimensions = {1, 5, 5, 3}; // Create tensor and back it with memory - output_tensor = std::make_unique(get_device(), - TensorBuilder(dimensions) - .with_usage(VK_TENSOR_USAGE_SHADER_BIT_ARM | VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM) - .with_format(VK_FORMAT_R32_SFLOAT)); + output_tensor = std::make_unique( + get_device(), + TensorBuilder(dimensions).with_usage(VK_TENSOR_USAGE_SHADER_BIT_ARM | VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM).with_format(VK_FORMAT_R32_SFLOAT)); output_tensor_view = std::make_unique(*output_tensor); } @@ -185,10 +183,9 @@ void SimpleTensorAndDataGraph::prepare_output_tensor() */ void SimpleTensorAndDataGraph::prepare_output_image(uint32_t width, uint32_t height) { - output_image = std::make_unique(get_device(), - vkb::core::ImageBuilder(VkExtent3D{width, height, 1}) - .with_format(VK_FORMAT_R8G8B8A8_UNORM) - .with_usage(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)); + output_image = std::make_unique(get_device(), vkb::core::ImageBuilder(VkExtent3D{width, height, 1}) + .with_format(VK_FORMAT_R8G8B8A8_UNORM) + .with_usage(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT)); output_image_view = std::make_unique(*output_image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM); } @@ -209,20 +206,16 @@ void SimpleTensorAndDataGraph::prepare_data_graph_pipeline() // be bound to the pipeline. std::map> tensor_descriptions; // All bindings are in set 0 - tensor_descriptions[0] = - { - // Binding 0 is the input tensor - {0, &input_tensor->get_description()}, - // Binding 1 is the output tensor - {1, &output_tensor->get_description()}}; + tensor_descriptions[0] = {// Binding 0 is the input tensor + {0, &input_tensor->get_description()}, + // Binding 1 is the output tensor + {1, &output_tensor->get_description()}}; - VkShaderModule shader_module = vkb::load_shader("tensor_and_data_graph/simple_tensor_and_data_graph/spirv/pooling.spvasm.spv", get_device().get_handle(), VK_SHADER_STAGE_ALL); + VkShaderModule shader_module = + vkb::load_shader("tensor_and_data_graph/simple_tensor_and_data_graph/spirv/pooling.spvasm.spv", get_device().get_handle(), VK_SHADER_STAGE_ALL); - data_graph_pipeline = std::make_unique(get_device(), - data_graph_pipeline_layout->get_handle(), - shader_module, - "main", - tensor_descriptions); + data_graph_pipeline = + std::make_unique(get_device(), data_graph_pipeline_layout->get_handle(), shader_module, "main", tensor_descriptions); // Create a Pipeline Session for the Pipeline. Unlike compute and graphics pipelines, data graph pipelines require // additional state to be stored (e.g. for intermediate results). This is stored separately to the pipeline itself in @@ -245,12 +238,11 @@ void SimpleTensorAndDataGraph::prepare_data_graph_pipeline_descriptor_set() VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &data_graph_pipeline_descriptor_set)); // Write bindings to it, telling it which tensors to use as input and output - std::map tensor_bindings = - { - // Binding 0 is the input tensor - {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, - // Binding 1 is the output tensor - {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; + std::map tensor_bindings = { + // Binding 0 is the input tensor + {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, + // Binding 1 is the output tensor + {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; write_descriptor_set(get_device().get_handle(), data_graph_pipeline_descriptor_set, {}, tensor_bindings); } @@ -261,8 +253,8 @@ void SimpleTensorAndDataGraph::prepare_data_graph_pipeline_descriptor_set() void SimpleTensorAndDataGraph::prepare_visualization_pipeline() { // Load the compute shader - vkb::ShaderModule &visualization_comp = - get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/glsl/visualization_two_tensors.comp.spv"}); + vkb::ShaderModule &visualization_comp = get_device().get_resource_cache().request_shader_module( + VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"tensor_and_data_graph/glsl/visualization_two_tensors.comp.spv"}); // Create pipeline layout from the reflected shader code. Note that this will include bindings to Tensor resources, so we use our own // class to do this, rather than the sample framework's vkb::PipelineLayout. @@ -277,7 +269,8 @@ void SimpleTensorAndDataGraph::prepare_visualization_pipeline() */ void SimpleTensorAndDataGraph::prepare_visualization_pipeline_descriptor_set() { - // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than allocating a new one) + // Allocate descriptor set (if not already allocated; when this function is called due to window resize we just update the existing set rather than + // allocating a new one) if (visualization_pipeline_descriptor_set == VK_NULL_HANDLE) { VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; @@ -288,17 +281,15 @@ void SimpleTensorAndDataGraph::prepare_visualization_pipeline_descriptor_set() } // Write bindings to it - std::map tensor_bindings = - { - // Binding 0 is the input tensor - {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, - // Binding 1 is the output tensor - {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; - - std::map image_bindings = - { - // Binding 2 is the output image - {2, VkDescriptorImageInfo{VK_NULL_HANDLE, output_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL}}}; + std::map tensor_bindings = { + // Binding 0 is the input tensor + {0, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &input_tensor_view->get_handle()}}, + // Binding 1 is the output tensor + {1, VkWriteDescriptorSetTensorARM{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_TENSOR_ARM, nullptr, 1, &output_tensor_view->get_handle()}}}; + + std::map image_bindings = { + // Binding 2 is the output image + {2, VkDescriptorImageInfo{VK_NULL_HANDLE, output_image_view->get_handle(), VK_IMAGE_LAYOUT_GENERAL}}}; write_descriptor_set(get_device().get_handle(), visualization_pipeline_descriptor_set, image_bindings, tensor_bindings); } @@ -327,8 +318,8 @@ void SimpleTensorAndDataGraph::draw_renderpass(vkb::core::CommandBufferC &comman { // Bind and run data graph pipeline. vkCmdBindPipeline(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline->get_handle()); - vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline_layout->get_handle(), - 0, 1, &data_graph_pipeline_descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_DATA_GRAPH_ARM, data_graph_pipeline_layout->get_handle(), 0, 1, + &data_graph_pipeline_descriptor_set, 0, nullptr); vkCmdDispatchDataGraphARM(command_buffer.get_handle(), data_graph_pipeline_session->get_handle(), VK_NULL_HANDLE); // Barrier for `output_tensor` (written to by the graph pipeline above, and read from by the visualization compute shader below) @@ -355,12 +346,12 @@ void SimpleTensorAndDataGraph::draw_renderpass(vkb::core::CommandBufferC &comman // Bind and run visualization compute pipeline vkCmdBindPipeline(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline->get_handle()); - vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline_layout->get_handle(), - 0, 1, &visualization_pipeline_descriptor_set, 0, nullptr); + vkCmdBindDescriptorSets(command_buffer.get_handle(), VK_PIPELINE_BIND_POINT_COMPUTE, visualization_pipeline_layout->get_handle(), 0, 1, + &visualization_pipeline_descriptor_set, 0, nullptr); // Pass the output_image size as a push constant - vkCmdPushConstants(command_buffer.get_handle(), visualization_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, - sizeof(glm::uvec2), &render_target.get_extent()); + vkCmdPushConstants(command_buffer.get_handle(), visualization_pipeline_layout->get_handle(), VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(glm::uvec2), + &render_target.get_extent()); uint32_t group_count_x = (render_target.get_extent().width + 7) / 8; // The visualization shader has a group size of 8 uint32_t group_count_y = (render_target.get_extent().height + 7) / 8; vkCmdDispatch(command_buffer.get_handle(), group_count_x, group_count_y, 1); @@ -394,8 +385,7 @@ void SimpleTensorAndDataGraph::draw_gui() draw_list->AddText(ImVec2(cx + 100, cy + 100), IM_COL32_WHITE, "Output tensor"); draw_list->AddLine(ImVec2(cx - 25, cy), ImVec2(cx - 5, cy), IM_COL32_WHITE, 5.0f); - ImGui::RenderArrowPointingAt(draw_list, ImVec2(cx + 25.0f, cy), - ImVec2(30.0f, 10.0f), ImGuiDir_Right, IM_COL32_WHITE); + ImGui::RenderArrowPointingAt(draw_list, ImVec2(cx + 25.0f, cy), ImVec2(30.0f, 10.0f), ImGuiDir_Right, IM_COL32_WHITE); ImVec2 text_size = ImGui::CalcTextSize("Pooling"); draw_list->AddText(ImVec2(cx - text_size.x / 2, cy + 20), IM_COL32_WHITE, "Pooling"); } diff --git a/samples/extensions/tensor_and_data_graph/tensor_and_data_graph_common.cpp b/samples/extensions/tensor_and_data_graph/tensor_and_data_graph_common.cpp index b63877c938..cb03833a59 100644 --- a/samples/extensions/tensor_and_data_graph/tensor_and_data_graph_common.cpp +++ b/samples/extensions/tensor_and_data_graph/tensor_and_data_graph_common.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2024-2025, Arm Limited and Contributors +/* Copyright (c) 2024-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -63,10 +63,7 @@ VkResult vmaCreateTensor(VkDevice device, // Note that this implementation has some slight differences to the equivalent vmaCreateImage/Buffer functions because we are outside // the VMA implementation so can't use any of its internal functions and have to use the public APIs instead. - if (pTensorCreateInfo == nullptr || - pTensorCreateInfo->pDescription == nullptr || - pTensor == nullptr || - pAllocation == nullptr) + if (pTensorCreateInfo == nullptr || pTensorCreateInfo->pDescription == nullptr || pTensor == nullptr || pAllocation == nullptr) { return VK_ERROR_INITIALIZATION_FAILED; } @@ -75,11 +72,7 @@ VkResult vmaCreateTensor(VkDevice device, *pAllocation = VK_NULL_HANDLE; // 1. Create VkTensor. - VkResult res = vkCreateTensorARM( - device, - pTensorCreateInfo, - nullptr, - pTensor); + VkResult res = vkCreateTensorARM(device, pTensorCreateInfo, nullptr, pTensor); if (res >= 0) { // 2. vkGetTensorMemoryRequirements. @@ -91,11 +84,7 @@ VkResult vmaCreateTensor(VkDevice device, // 3. Allocate memory using allocator. VmaAllocationInfo allocation_info; - res = vmaAllocateMemory(allocator, - &vkMemReq.memoryRequirements, - pAllocationCreateInfo, - pAllocation, - &allocation_info); + res = vmaAllocateMemory(allocator, &vkMemReq.memoryRequirements, pAllocationCreateInfo, pAllocation, &allocation_info); if (res >= 0) { @@ -129,10 +118,7 @@ VkResult vmaCreateTensor(VkDevice device, return res; } -void vmaDestroyTensor(VkDevice device, - VmaAllocator allocator, - VkTensorARM tensor, - VmaAllocation allocation) +void vmaDestroyTensor(VkDevice device, VmaAllocator allocator, VkTensorARM tensor, VmaAllocation allocation) { if (tensor != VK_NULL_HANDLE) { @@ -156,9 +142,7 @@ VkResult vmaCreateDataGraphPipelineSession(VkDevice // Note that this implementation has some slight differences to the equivalent vmaCreateImage/Buffer functions because we are outside // the VMA implementation so can't use any of its internal functions and have to use the public APIs instead. - if (pDataGraphPipelineSessionCreateInfo == nullptr || - pDataGraphPipelineSession == nullptr || - pAllocation == nullptr) + if (pDataGraphPipelineSessionCreateInfo == nullptr || pDataGraphPipelineSession == nullptr || pAllocation == nullptr) { return VK_ERROR_INITIALIZATION_FAILED; } @@ -167,17 +151,14 @@ VkResult vmaCreateDataGraphPipelineSession(VkDevice *pAllocation = VK_NULL_HANDLE; // 1. Create DataGraphPipelineSession. - VkResult res = vkCreateDataGraphPipelineSessionARM( - device, - pDataGraphPipelineSessionCreateInfo, - nullptr, - pDataGraphPipelineSession); + VkResult res = vkCreateDataGraphPipelineSessionARM(device, pDataGraphPipelineSessionCreateInfo, nullptr, pDataGraphPipelineSession); if (res >= 0) { // 2. Query valid bind points for the session - VkDataGraphPipelineSessionBindPointRequirementsInfoARM bind_point_req_info = {VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_SESSION_BIND_POINT_REQUIREMENTS_INFO_ARM}; - bind_point_req_info.session = *pDataGraphPipelineSession; - uint32_t requirement_count = 0; + VkDataGraphPipelineSessionBindPointRequirementsInfoARM bind_point_req_info = { + VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_SESSION_BIND_POINT_REQUIREMENTS_INFO_ARM}; + bind_point_req_info.session = *pDataGraphPipelineSession; + uint32_t requirement_count = 0; res = vkGetDataGraphPipelineSessionBindPointRequirementsARM(device, &bind_point_req_info, &requirement_count, nullptr); if (res != VK_SUCCESS) @@ -212,21 +193,18 @@ VkResult vmaCreateDataGraphPipelineSession(VkDevice // 3. vkGetDataGraphPipelineSessionMemoryRequirements. VkDataGraphPipelineSessionBindPointARM memory_bind_point = VK_DATA_GRAPH_PIPELINE_SESSION_BIND_POINT_TRANSIENT_ARM; VkMemoryRequirements2 vkMemReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; - VkDataGraphPipelineSessionMemoryRequirementsInfoARM memory_requirements_info = {VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_SESSION_MEMORY_REQUIREMENTS_INFO_ARM}; - memory_requirements_info.session = *pDataGraphPipelineSession; - memory_requirements_info.bindPoint = memory_bind_point; - memory_requirements_info.objectIndex = 0; + VkDataGraphPipelineSessionMemoryRequirementsInfoARM memory_requirements_info = { + VK_STRUCTURE_TYPE_DATA_GRAPH_PIPELINE_SESSION_MEMORY_REQUIREMENTS_INFO_ARM}; + memory_requirements_info.session = *pDataGraphPipelineSession; + memory_requirements_info.bindPoint = memory_bind_point; + memory_requirements_info.objectIndex = 0; vkGetDataGraphPipelineSessionMemoryRequirementsARM(device, &memory_requirements_info, &vkMemReq); if (vkMemReq.memoryRequirements.size > 0) { // 4. Allocate memory using allocator. VmaAllocationInfo allocation_info; - res = vmaAllocateMemory(allocator, - &vkMemReq.memoryRequirements, - pAllocationCreateInfo, - pAllocation, - &allocation_info); + res = vmaAllocateMemory(allocator, &vkMemReq.memoryRequirements, pAllocationCreateInfo, pAllocation, &allocation_info); if (res >= 0) { @@ -268,10 +246,7 @@ VkResult vmaCreateDataGraphPipelineSession(VkDevice return res; } -void vmaDestroyDataGraphPipelineSession(VkDevice device, - VmaAllocator allocator, - VkDataGraphPipelineSessionARM tensor, - VmaAllocation allocation) +void vmaDestroyDataGraphPipelineSession(VkDevice device, VmaAllocator allocator, VkDataGraphPipelineSessionARM tensor, VmaAllocation allocation) { if (tensor != VK_NULL_HANDLE) { @@ -289,8 +264,9 @@ TensorBuilder::TensorBuilder(std::vector in_dimensions) : dimensions(std::move(in_dimensions)), description{VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM} { - description.dimensionCount = dimensions.size(); - description.pDimensions = dimensions.data(); // Note we point to the dimensions array stored in this object, not the one passed in (which is already empty!) + description.dimensionCount = dimensions.size(); + description.pDimensions = + dimensions.data(); // Note we point to the dimensions array stored in this object, not the one passed in (which is already empty!) get_create_info().pDescription = &description; alloc_create_info.usage = VMA_MEMORY_USAGE_UNKNOWN; // The default value set by the base class of 'VMA_MEMORY_USAGE_AUTO' won't work for tensors @@ -337,20 +313,13 @@ const VkTensorDescriptionARM &TensorDescriptor::get_description() const } Tensor::Tensor(vkb::core::DeviceC &device, TensorBuilder const &builder) : - vkb::allocated::AllocatedC(builder.get_allocation_create_info(), nullptr, &device), - descriptor(builder) + vkb::allocated::AllocatedC(builder.get_allocation_create_info(), nullptr, &device), descriptor(builder) { VkTensorARM tensor = VK_NULL_HANDLE; VmaAllocationInfo allocation_info{}; VmaAllocation allocation = VK_NULL_HANDLE; - VK_CHECK(vmaCreateTensor( - device.get_handle(), - vkb::allocated::get_memory_allocator(), - &descriptor.get_create_info(), - &builder.get_allocation_create_info(), - &tensor, - &allocation, - &allocation_info)); + VK_CHECK(vmaCreateTensor(device.get_handle(), vkb::allocated::get_memory_allocator(), &descriptor.get_create_info(), &builder.get_allocation_create_info(), + &tensor, &allocation, &allocation_info)); set_allocation(allocation); post_create(allocation_info); @@ -381,8 +350,10 @@ VkFormat Tensor::get_format() const return descriptor.get_create_info().pDescription->format; }; -ExternallyAllocatedTensor::ExternallyAllocatedTensor(vkb::core::DeviceC &device, TensorBuilder const &builder, VkDeviceMemory existing_memory, - VkDeviceSize existing_memory_offset) : +ExternallyAllocatedTensor::ExternallyAllocatedTensor(vkb::core::DeviceC &device, + TensorBuilder const &builder, + VkDeviceMemory existing_memory, + VkDeviceSize existing_memory_offset) : vkb::core::VulkanResourceC(VK_NULL_HANDLE, &device), // Handle will be set later in the constructor descriptor(builder) { @@ -391,8 +362,7 @@ ExternallyAllocatedTensor::ExternallyAllocatedTensor(vkb::core::DeviceC &device, VkResult res = vkCreateTensorARM(device.get_handle(), &descriptor.get_create_info(), nullptr, &tensor); // Bind it to existing memory - VkBindTensorMemoryInfoARM bind_info = {VK_STRUCTURE_TYPE_BIND_TENSOR_MEMORY_INFO_ARM, - nullptr, tensor, existing_memory, existing_memory_offset}; + VkBindTensorMemoryInfoARM bind_info = {VK_STRUCTURE_TYPE_BIND_TENSOR_MEMORY_INFO_ARM, nullptr, tensor, existing_memory, existing_memory_offset}; vkBindTensorMemoryARM(device.get_handle(), 1, &bind_info); set_handle(tensor); @@ -420,14 +390,12 @@ VkFormat ExternallyAllocatedTensor::get_format() const return descriptor.get_create_info().pDescription->format; }; -TensorView::TensorView(Tensor &tensor, VkFormat format) : - vkb::core::VulkanResourceC(VK_NULL_HANDLE, &tensor.get_device()) +TensorView::TensorView(Tensor &tensor, VkFormat format) : vkb::core::VulkanResourceC(VK_NULL_HANDLE, &tensor.get_device()) { Init(tensor, format); } -TensorView::TensorView(ExternallyAllocatedTensor &tensor, VkFormat format) : - vkb::core::VulkanResourceC(VK_NULL_HANDLE, &tensor.get_device()) +TensorView::TensorView(ExternallyAllocatedTensor &tensor, VkFormat format) : vkb::core::VulkanResourceC(VK_NULL_HANDLE, &tensor.get_device()) { Init(tensor, format); } @@ -551,9 +519,7 @@ DataGraphPipeline::~DataGraphPipeline() vkDestroyPipeline(get_device().get_handle(), get_handle(), nullptr); } -DataGraphPipelineSession::DataGraphPipelineSession(vkb::core::DeviceC &device, - VkPipeline data_graph_pipeline, - VmaAllocationCreateInfo alloc_create_info) : +DataGraphPipelineSession::DataGraphPipelineSession(vkb::core::DeviceC &device, VkPipeline data_graph_pipeline, VmaAllocationCreateInfo alloc_create_info) : vkb::allocated::AllocatedC(alloc_create_info, nullptr, &device) { VkDataGraphPipelineSessionCreateInfoARM pipeline_session_create_info = {}; @@ -563,14 +529,8 @@ DataGraphPipelineSession::DataGraphPipelineSession(vkb::core::DeviceC &devic VkDataGraphPipelineSessionARM data_graph_pipeline_session = VK_NULL_HANDLE; VmaAllocationInfo allocation_info{}; VmaAllocation allocation = VK_NULL_HANDLE; - VK_CHECK(vmaCreateDataGraphPipelineSession( - device.get_handle(), - vkb::allocated::get_memory_allocator(), - &pipeline_session_create_info, - &alloc_create_info, - &data_graph_pipeline_session, - &allocation, - &allocation_info)); + VK_CHECK(vmaCreateDataGraphPipelineSession(device.get_handle(), vkb::allocated::get_memory_allocator(), &pipeline_session_create_info, &alloc_create_info, + &data_graph_pipeline_session, &allocation, &allocation_info)); set_allocation(allocation); if (allocation_info.size > 0) // Sometimes no memory is needed, which is fine. @@ -593,7 +553,8 @@ ComputePipelineLayoutWithTensors::ComputePipelineLayoutWithTensors(vkb::core::De vkb::core::VulkanResourceC(nullptr, &device) { // Create a regular vkb::PipelineLayout to reflect all the regular shader resources except tensors - std::unique_ptr layout_without_tensors = std::make_unique(device, std::vector{&shader_module}); + std::unique_ptr layout_without_tensors = + std::make_unique(device, std::vector{&shader_module}); // Gather all the binding info that was found std::map> all_bindings; @@ -626,7 +587,8 @@ ComputePipelineLayoutWithTensors::ComputePipelineLayoutWithTensors(vkb::core::De } // Create set layouts now that we have the full set of bindings - std::vector descriptor_set_layouts_array; // As well as storing a std::map of descriptor set layouts, we need a linear array for use in VkPipelineLayoutCreateInfo + std::vector descriptor_set_layouts_array; // As well as storing a std::map of descriptor set layouts, we need a linear array + // for use in VkPipelineLayoutCreateInfo for (const std::pair> &set_idx_and_bindings : all_bindings) { uint32_t set_idx = set_idx_and_bindings.first; @@ -705,17 +667,17 @@ ComputePipelineWithTensors::~ComputePipelineWithTensors() } BlitSubpass::BlitSubpass(vkb::rendering::RenderContextC &renderContext, vkb::core::ImageView *source) : - vkb::rendering::SubpassC(renderContext, vkb::ShaderSource{"tensor_and_data_graph/glsl/fullscreen.vert.spv"}, vkb::ShaderSource{"tensor_and_data_graph/glsl/blit.frag.spv"}), + vkb::rendering::SubpassC( + renderContext, vkb::ShaderSource{"tensor_and_data_graph/glsl/fullscreen.vert.spv"}, vkb::ShaderSource{"tensor_and_data_graph/glsl/blit.frag.spv"}), source(source) -{ -} +{} void BlitSubpass::prepare() { - vkb::ShaderModule &fullscreen_vert = - get_render_context().get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_VERTEX_BIT, vkb::ShaderSource{"tensor_and_data_graph/glsl/fullscreen.vert.spv"}); - vkb::ShaderModule &blit_frag = - get_render_context().get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_FRAGMENT_BIT, vkb::ShaderSource{"tensor_and_data_graph/glsl/blit.frag.spv"}); + vkb::ShaderModule &fullscreen_vert = get_render_context().get_device().get_resource_cache().request_shader_module( + VK_SHADER_STAGE_VERTEX_BIT, vkb::ShaderSource{"tensor_and_data_graph/glsl/fullscreen.vert.spv"}); + vkb::ShaderModule &blit_frag = get_render_context().get_device().get_resource_cache().request_shader_module( + VK_SHADER_STAGE_FRAGMENT_BIT, vkb::ShaderSource{"tensor_and_data_graph/glsl/blit.frag.spv"}); pipeline_layout = &get_render_context().get_device().get_resource_cache().request_pipeline_layout({&fullscreen_vert, &blit_frag}); VkSamplerCreateInfo sampler_create_info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; diff --git a/samples/extensions/tensor_and_data_graph/tensor_and_data_graph_common.h b/samples/extensions/tensor_and_data_graph/tensor_and_data_graph_common.h index e339347fa0..fb8dbf1fa3 100644 --- a/samples/extensions/tensor_and_data_graph/tensor_and_data_graph_common.h +++ b/samples/extensions/tensor_and_data_graph/tensor_and_data_graph_common.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2024-2025, Arm Limited and Contributors +/* Copyright (c) 2024-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -38,10 +38,8 @@ struct MultidimensionalArrayView T *data; std::vector dimensions; - MultidimensionalArrayView(T *data, const std::vector &dimensions) : - data(data), dimensions(dimensions) - { - } + MultidimensionalArrayView(T *data, const std::vector &dimensions) : data(data), dimensions(dimensions) + {} T &operator[](std::initializer_list indices) { @@ -84,10 +82,7 @@ VkResult vmaCreateTensor(VkDevice device, /* ** @brief Destroys a Tensor resource and its backing memory, which were created from vmaCreateTensor. Analogous to vmaDestroyImage/Buffer. */ -void vmaDestroyTensor(VkDevice device, - VmaAllocator allocator, - VkTensorARM tensor, - VmaAllocation allocation); +void vmaDestroyTensor(VkDevice device, VmaAllocator allocator, VkTensorARM tensor, VmaAllocation allocation); /* * @brief Creates a VkDataGraphPipelineSessionARM resource and backs it with memory. Analogous to vmaCreateImage/Buffer. @@ -102,12 +97,10 @@ VkResult vmaCreateDataGraphPipelineSession(VkDevice VmaAllocationInfo *pAllocationInfo); /* - ** @brief Destroys a DataGraphPipelineSession resource and its backing memory, which were created from vmaCreateDataGraphPipelineSession. Analogous to vmaDestroyImage/Buffer. + ** @brief Destroys a DataGraphPipelineSession resource and its backing memory, which were created from vmaCreateDataGraphPipelineSession. Analogous to + *vmaDestroyImage/Buffer. */ -void vmaDestroyDataGraphPipelineSession(VkDevice device, - VmaAllocator allocator, - VkDataGraphPipelineSessionARM session, - VmaAllocation allocation); +void vmaDestroyDataGraphPipelineSession(VkDevice device, VmaAllocator allocator, VkDataGraphPipelineSessionARM session, VmaAllocation allocation); /* * @brief Helper class to describe a Tensor resource that is to be created (see Tensor constructor below). Analogous to vkb::ImageBuilder/BufferBuilder. @@ -174,8 +167,7 @@ class Tensor : public vkb::allocated::AllocatedC class ExternallyAllocatedTensor : public vkb::core::VulkanResourceC { public: - ExternallyAllocatedTensor(vkb::core::DeviceC &device, TensorBuilder const &builder, VkDeviceMemory existing_memory, - VkDeviceSize existing_memory_offset); + ExternallyAllocatedTensor(vkb::core::DeviceC &device, TensorBuilder const &builder, VkDeviceMemory existing_memory, VkDeviceSize existing_memory_offset); ~ExternallyAllocatedTensor(); const VkTensorDescriptionARM &get_description() const; @@ -192,8 +184,9 @@ class ExternallyAllocatedTensor : public vkb::core::VulkanResourceC class TensorView : public vkb::core::VulkanResourceC { public: - TensorView(Tensor &tensor, VkFormat format = VK_FORMAT_UNDEFINED); // VK_FORMAT_UNDEFINED means to use the same format as the provided tensor. - TensorView(ExternallyAllocatedTensor &tensor, VkFormat format = VK_FORMAT_UNDEFINED); // VK_FORMAT_UNDEFINED means to use the same format as the provided tensor. + TensorView(Tensor &tensor, VkFormat format = VK_FORMAT_UNDEFINED); // VK_FORMAT_UNDEFINED means to use the same format as the provided tensor. + TensorView(ExternallyAllocatedTensor &tensor, + VkFormat format = VK_FORMAT_UNDEFINED); // VK_FORMAT_UNDEFINED means to use the same format as the provided tensor. ~TensorView(); private: @@ -253,7 +246,7 @@ class DataGraphPipeline : public vkb::core::VulkanResourceC VkShaderModule shader_module, const char *entry_point, const std::map> &tensor_descriptions, - const std::vector &data_graph_pipeline_constants = std::vector()); + const std::vector &data_graph_pipeline_constants = std::vector()); ~DataGraphPipeline(); private: @@ -273,7 +266,8 @@ class DataGraphPipelineSession : public vkb::allocated::AllocatedC { diff --git a/samples/extensions/timeline_semaphore/timeline_semaphore.cpp b/samples/extensions/timeline_semaphore/timeline_semaphore.cpp index 121c277813..fdb73a1d7e 100644 --- a/samples/extensions/timeline_semaphore/timeline_semaphore.cpp +++ b/samples/extensions/timeline_semaphore/timeline_semaphore.cpp @@ -118,16 +118,17 @@ void TimelineSemaphore::setup_shared_resources() for (int i = 0; i < NumAsyncFrames; ++i) { // Need CONCURRENT usage here since we will sample from the image in both graphics and compute queues. - shared.images[i] = std::make_unique(get_device(), vkb::core::ImageBuilder(VkExtent3D{grid_width, grid_height, 1}) - .with_format(VK_FORMAT_R8G8B8A8_UNORM) - .with_usage(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) - .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY) - .with_sample_count(VK_SAMPLE_COUNT_1_BIT) - .with_mip_levels(1) - .with_array_layers(1) - .with_tiling(VK_IMAGE_TILING_OPTIMAL) - .with_queue_families(static_cast(queue_families.size()), queue_families.data()) - .with_sharing_mode(sharing_mode)); + shared.images[i] = + std::make_unique(get_device(), vkb::core::ImageBuilder(VkExtent3D{grid_width, grid_height, 1}) + .with_format(VK_FORMAT_R8G8B8A8_UNORM) + .with_usage(VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT) + .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY) + .with_sample_count(VK_SAMPLE_COUNT_1_BIT) + .with_mip_levels(1) + .with_array_layers(1) + .with_tiling(VK_IMAGE_TILING_OPTIMAL) + .with_queue_families(static_cast(queue_families.size()), queue_families.data()) + .with_sharing_mode(sharing_mode)); shared.image_views[i] = std::make_unique(*shared.images[i], VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM); } @@ -135,8 +136,10 @@ void TimelineSemaphore::setup_shared_resources() // Descriptor layouts { - VkDescriptorSetLayoutBinding storage_binding = vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 0); - VkDescriptorSetLayoutBinding sampled_binding = vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_ALL, 0); + VkDescriptorSetLayoutBinding storage_binding = + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 0); + VkDescriptorSetLayoutBinding sampled_binding = + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_ALL, 0); VkSampler vk_immutable_sampler = shared.immutable_sampler->get_handle(); sampled_binding.pImmutableSamplers = &vk_immutable_sampler; @@ -158,8 +161,9 @@ void TimelineSemaphore::setup_shared_resources() VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &storage_alloc_info, &shared.storage_descriptor_sets[i])); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &sampled_alloc_info, &shared.sampled_descriptor_sets[i])); - auto general_info = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, shared.image_views[i]->get_handle(), VK_IMAGE_LAYOUT_GENERAL); - auto readonly_info = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, shared.image_views[i]->get_handle(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + auto general_info = vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, shared.image_views[i]->get_handle(), VK_IMAGE_LAYOUT_GENERAL); + auto readonly_info = + vkb::initializers::descriptor_image_info(VK_NULL_HANDLE, shared.image_views[i]->get_handle(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); const VkWriteDescriptorSet writes[2] = { vkb::initializers::write_descriptor_set(shared.storage_descriptor_sets[i], VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, &general_info), @@ -345,10 +349,10 @@ void TimelineSemaphore::setup_compute_resources() compute.queue_family_index = vkb::get_queue_family_index(get_device().get_gpu().get_queue_family_properties(), VK_QUEUE_COMPUTE_BIT); vkGetDeviceQueue(get_device().get_handle(), compute.queue_family_index, 0, &compute.queue); - compute.command_pool = get_device().create_command_pool(compute.queue_family_index, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); + compute.command_pool = + get_device().create_command_pool(compute.queue_family_index, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); - VkCommandBufferAllocateInfo alloc_info = - vkb::initializers::command_buffer_allocate_info(compute.command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); + VkCommandBufferAllocateInfo alloc_info = vkb::initializers::command_buffer_allocate_info(compute.command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK(vkAllocateCommandBuffers(get_device().get_handle(), &alloc_info, &compute.command_buffer)); } @@ -362,7 +366,8 @@ void TimelineSemaphore::setup_game_of_life() for (int i = 0; i < NumAsyncFrames; ++i) { - vkCmdBindDescriptorSets(compute.command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline_layout, 0, 1, &shared.storage_descriptor_sets[i], 0, nullptr); + vkCmdBindDescriptorSets(compute.command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline_layout, 0, 1, &shared.storage_descriptor_sets[i], 0, + nullptr); // On the first iteration, we initialize the game of life. vkCmdBindPipeline(compute.command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.init_pipeline); @@ -376,7 +381,8 @@ void TimelineSemaphore::setup_game_of_life() image_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; // The semaphore takes care of srcStageMask. - vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_barrier); + vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, + &image_barrier); vkCmdDispatch(compute.command_buffer, grid_width / 8, grid_height / 8, 1); @@ -386,7 +392,8 @@ void TimelineSemaphore::setup_game_of_life() image_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // The semaphore takes care of dstStageMask. - vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_barrier); + vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, + &image_barrier); } VK_CHECK(vkEndCommandBuffer(compute.command_buffer)); @@ -410,7 +417,8 @@ void TimelineSemaphore::build_compute_command_buffers(const float elapsed) auto frame_index = timeline.frame % NumAsyncFrames; auto prev_index = (timeline.frame - 1) % NumAsyncFrames; - vkCmdBindDescriptorSets(compute.command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline_layout, 0, 1, &shared.storage_descriptor_sets[frame_index], 0, nullptr); + vkCmdBindDescriptorSets(compute.command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline_layout, 0, 1, &shared.storage_descriptor_sets[frame_index], + 0, nullptr); if (elapsed > 1.0f) { @@ -420,12 +428,12 @@ void TimelineSemaphore::build_compute_command_buffers(const float elapsed) else { vkCmdBindPipeline(compute.command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.mutate_pipeline); - vkCmdPushConstants(compute.command_buffer, compute.pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, - 0, sizeof(elapsed), &elapsed); + vkCmdPushConstants(compute.command_buffer, compute.pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(elapsed), &elapsed); } // Bind previous iteration's texture. - vkCmdBindDescriptorSets(compute.command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline_layout, 1, 1, &shared.sampled_descriptor_sets[prev_index], 0, nullptr); + vkCmdBindDescriptorSets(compute.command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipeline_layout, 1, 1, &shared.sampled_descriptor_sets[prev_index], + 0, nullptr); VkImageMemoryBarrier image_barrier = vkb::initializers::image_memory_barrier(); image_barrier.srcAccessMask = 0; @@ -436,7 +444,8 @@ void TimelineSemaphore::build_compute_command_buffers(const float elapsed) image_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; // The semaphore takes care of srcStageMask. - vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_barrier); + vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, + &image_barrier); vkCmdDispatch(compute.command_buffer, grid_width / 8, grid_height / 8, 1); @@ -446,7 +455,8 @@ void TimelineSemaphore::build_compute_command_buffers(const float elapsed) image_barrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // The semaphore takes care of dstStageMask. - vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_barrier); + vkCmdPipelineBarrier(compute.command_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, + &image_barrier); VK_CHECK(vkEndCommandBuffer(compute.command_buffer)); } @@ -500,10 +510,10 @@ void TimelineSemaphore::setup_graphics_resources() graphics.queue_family_index = vkb::get_queue_family_index(get_device().get_gpu().get_queue_family_properties(), VK_QUEUE_GRAPHICS_BIT); graphics.queue = queue; - graphics.command_pool = get_device().create_command_pool(graphics.queue_family_index, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); + graphics.command_pool = + get_device().create_command_pool(graphics.queue_family_index, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); - VkCommandBufferAllocateInfo alloc_info = - vkb::initializers::command_buffer_allocate_info(graphics.command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); + VkCommandBufferAllocateInfo alloc_info = vkb::initializers::command_buffer_allocate_info(graphics.command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK(vkAllocateCommandBuffers(get_device().get_handle(), &alloc_info, &graphics.command_buffer)); } @@ -522,19 +532,14 @@ void TimelineSemaphore::setup_graphics_pipeline() VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + VkPipelineDynamicStateCreateInfo dynamic_state = vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables); info.pVertexInputState = &vertex_input_state; info.pInputAssemblyState = &input_assembly_state; @@ -596,7 +601,8 @@ void TimelineSemaphore::build_graphics_command_buffer() vkCmdSetViewport(graphics.command_buffer, 0, 1, &viewport); vkCmdSetScissor(graphics.command_buffer, 0, 1, &scissor); - vkCmdBindDescriptorSets(graphics.command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics.pipeline_layout, 0, 1, &shared.sampled_descriptor_sets[frame_index], 0, nullptr); + vkCmdBindDescriptorSets(graphics.command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics.pipeline_layout, 0, 1, + &shared.sampled_descriptor_sets[frame_index], 0, nullptr); vkCmdDraw(graphics.command_buffer, 3, 1, 0, 0); draw_ui(graphics.command_buffer); diff --git a/samples/extensions/vertex_dynamic_state/vertex_dynamic_state.cpp b/samples/extensions/vertex_dynamic_state/vertex_dynamic_state.cpp index 4406775bce..e78e7e78af 100644 --- a/samples/extensions/vertex_dynamic_state/vertex_dynamic_state.cpp +++ b/samples/extensions/vertex_dynamic_state/vertex_dynamic_state.cpp @@ -162,56 +162,30 @@ void VertexDynamicState::update_uniform_buffers() void VertexDynamicState::create_pipeline() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_BACK_BIT, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); const auto color_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); - color_blend_state.attachmentCount = 1; - color_blend_state.pAttachments = &color_attachment_state; + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); + color_blend_state.attachmentCount = 1; + color_blend_state.pAttachments = &color_attachment_state; /* Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept */ VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_FALSE, - VK_FALSE, - VK_COMPARE_OP_GREATER); - - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); - - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_VERTEX_INPUT_EXT}; + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_FALSE, VK_FALSE, VK_COMPARE_OP_GREATER); + + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); + + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_VERTEX_INPUT_EXT}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); std::array shader_stages{}; shader_stages[0] = load_shader("vertex_dynamic_state", "gbuffer.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); @@ -230,23 +204,11 @@ void VertexDynamicState::create_pipeline() /* Initialize vertex input binding and attributes structures */ - vertex_bindings_description_ext[0] = vkb::initializers::vertex_input_binding_description2ext( - 0, - sizeof(Vertex), - VK_VERTEX_INPUT_RATE_VERTEX, - 1); + vertex_bindings_description_ext[0] = vkb::initializers::vertex_input_binding_description2ext(0, sizeof(Vertex), VK_VERTEX_INPUT_RATE_VERTEX, 1); - vertex_attribute_description_ext[0] = vkb::initializers::vertex_input_attribute_description2ext( - 0, - 0, - VK_FORMAT_R32G32B32_SFLOAT, - offsetof(Vertex, pos)); + vertex_attribute_description_ext[0] = vkb::initializers::vertex_input_attribute_description2ext(0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, pos)); - vertex_attribute_description_ext[1] = vkb::initializers::vertex_input_attribute_description2ext( - 0, - 1, - VK_FORMAT_R32G32B32_SFLOAT, - offsetof(Vertex, normal)); + vertex_attribute_description_ext[1] = vkb::initializers::vertex_input_attribute_description2ext(0, 1, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, normal)); /* Use the pNext to point to the rendering create struct */ VkGraphicsPipelineCreateInfo graphics_create{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; @@ -347,11 +309,8 @@ void VertexDynamicState::build_command_buffers() /* First set of vertex input dynamic data (Vertex structure) */ vertex_bindings_description_ext[0].stride = sizeof(Vertex); vertex_attribute_description_ext[1].offset = offsetof(Vertex, normal); - vkCmdSetVertexInputEXT(draw_cmd_buffer, - static_cast(vertex_bindings_description_ext.size()), - vertex_bindings_description_ext.data(), - static_cast(vertex_attribute_description_ext.size()), - vertex_attribute_description_ext.data()); + vkCmdSetVertexInputEXT(draw_cmd_buffer, static_cast(vertex_bindings_description_ext.size()), vertex_bindings_description_ext.data(), + static_cast(vertex_attribute_description_ext.size()), vertex_attribute_description_ext.data()); vkCmdBindPipeline(draw_cmd_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, skybox_pipeline); draw_model(skybox, draw_cmd_buffer); @@ -363,11 +322,8 @@ void VertexDynamicState::build_command_buffers() /* Second set of vertex input dynamic data (SampleVertex structure) */ vertex_bindings_description_ext[0].stride = sizeof(SampleVertex); vertex_attribute_description_ext[1].offset = offsetof(SampleVertex, normal); - vkCmdSetVertexInputEXT(draw_cmd_buffer, - static_cast(vertex_bindings_description_ext.size()), - vertex_bindings_description_ext.data(), - static_cast(vertex_attribute_description_ext.size()), - vertex_attribute_description_ext.data()); + vkCmdSetVertexInputEXT(draw_cmd_buffer, static_cast(vertex_bindings_description_ext.size()), vertex_bindings_description_ext.data(), + static_cast(vertex_attribute_description_ext.size()), vertex_attribute_description_ext.data()); draw_created_model(draw_cmd_buffer); @@ -386,11 +342,10 @@ void VertexDynamicState::build_command_buffers() */ void VertexDynamicState::create_descriptor_pool() { - std::vector pool_sizes = { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; - uint32_t num_descriptor_sets = 4; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2)}; + uint32_t num_descriptor_sets = 4; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), num_descriptor_sets); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -411,10 +366,7 @@ void VertexDynamicState::setup_descriptor_set_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout_create_info, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } @@ -427,11 +379,7 @@ void VertexDynamicState::setup_descriptor_set_layout() */ void VertexDynamicState::create_descriptor_sets() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -517,30 +465,15 @@ void VertexDynamicState::model_data_creation() cube.index_count = index_count; /* Array with vertices indexes for corresponding triangles */ - std::array indices{0, 4, 3, - 4, 7, 3, - 0, 3, 2, - 0, 2, 1, - 1, 2, 6, - 6, 5, 1, - 5, 6, 7, - 7, 4, 5, - 0, 1, 5, - 5, 4, 0, - 3, 7, 6, - 6, 2, 3}; + std::array indices{0, 4, 3, 4, 7, 3, 0, 3, 2, 0, 2, 1, 1, 2, 6, 6, 5, 1, 5, 6, 7, 7, 4, 5, 0, 1, 5, 5, 4, 0, 3, 7, 6, 6, 2, 3}; vkb::core::BufferC vertex_staging = vkb::core::BufferC::create_staging_buffer(get_device(), vertices); vkb::core::BufferC index_staging = vkb::core::BufferC::create_staging_buffer(get_device(), indices); - cube.vertices = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + cube.vertices = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); - cube.indices = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + cube.indices = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); /* Copy from staging buffers */ @@ -549,20 +482,10 @@ void VertexDynamicState::model_data_creation() VkBufferCopy copy_region = {}; copy_region.size = vertex_buffer_size; - vkCmdCopyBuffer( - copy_command, - vertex_staging.get_handle(), - cube.vertices->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, vertex_staging.get_handle(), cube.vertices->get_handle(), 1, ©_region); copy_region.size = index_buffer_size; - vkCmdCopyBuffer( - copy_command, - index_staging.get_handle(), - cube.indices->get_handle(), - 1, - ©_region); + vkCmdCopyBuffer(copy_command, index_staging.get_handle(), cube.indices->get_handle(), 1, ©_region); get_device().flush_command_buffer(copy_command, queue, true); } diff --git a/samples/general/mobile_nerf/mobile_nerf.cpp b/samples/general/mobile_nerf/mobile_nerf.cpp index a1691db5d0..1ffe6cc590 100644 --- a/samples/general/mobile_nerf/mobile_nerf.cpp +++ b/samples/general/mobile_nerf/mobile_nerf.cpp @@ -334,7 +334,8 @@ void MobileNerf::read_json_map() if (instacing_map["interval"].is_array() && instacing_map["interval"].size() == 3) { - instancing_info.interval = glm::vec3(instacing_map["interval"][0].get(), instacing_map["interval"][1].get(), instacing_map["interval"][2].get()); + instancing_info.interval = + glm::vec3(instacing_map["interval"][0].get(), instacing_map["interval"][1].get(), instacing_map["interval"][2].get()); } else { @@ -342,7 +343,8 @@ void MobileNerf::read_json_map() exit(1); } - if (instancing_info.dim.x <= 0 || instancing_info.dim.y <= 0 || instancing_info.dim.z <= 0 || instancing_info.interval.x <= 0.f || instancing_info.interval.y <= 0.f || instancing_info.interval.z <= 0.f) + if (instancing_info.dim.x <= 0 || instancing_info.dim.y <= 0 || instancing_info.dim.z <= 0 || instancing_info.interval.x <= 0.f || + instancing_info.interval.y <= 0.f || instancing_info.interval.z <= 0.f) { LOGE("Instancing settings must be positive. Terminating..."); exit(1); @@ -356,27 +358,24 @@ void MobileNerf::load_shaders() { // Loading first pass shaders shader_stages_first_pass[0] = load_shader("mobile_nerf/raster.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); - shader_stages_first_pass[1] = load_shader( - combo_mode ? - (using_original_nerf_models[0] ? "mobile_nerf/raster_combo.frag.spv" : "mobile_nerf/raster_morpheus_combo.frag.spv") : - (using_original_nerf_models[0] ? "mobile_nerf/raster.frag.spv" : "mobile_nerf/raster_morpheus.frag.spv"), - VK_SHADER_STAGE_FRAGMENT_BIT); + shader_stages_first_pass[1] = + load_shader(combo_mode ? (using_original_nerf_models[0] ? "mobile_nerf/raster_combo.frag.spv" : "mobile_nerf/raster_morpheus_combo.frag.spv") : + (using_original_nerf_models[0] ? "mobile_nerf/raster.frag.spv" : "mobile_nerf/raster_morpheus.frag.spv"), + VK_SHADER_STAGE_FRAGMENT_BIT); // Loading second pass shaders shader_stages_second_pass[0] = load_shader("mobile_nerf/quad.vert", VK_SHADER_STAGE_VERTEX_BIT); - shader_stages_second_pass[1] = load_shader( - combo_mode ? - (using_original_nerf_models[0] ? "mobile_nerf/mlp_combo.frag.spv" : "mobile_nerf/mlp_morpheus_combo.frag.spv") : - (using_original_nerf_models[0] ? "mobile_nerf/mlp.frag.spv" : "mobile_nerf/mlp_morpheus.frag.spv"), - VK_SHADER_STAGE_FRAGMENT_BIT); + shader_stages_second_pass[1] = + load_shader(combo_mode ? (using_original_nerf_models[0] ? "mobile_nerf/mlp_combo.frag.spv" : "mobile_nerf/mlp_morpheus_combo.frag.spv") : + (using_original_nerf_models[0] ? "mobile_nerf/mlp.frag.spv" : "mobile_nerf/mlp_morpheus.frag.spv"), + VK_SHADER_STAGE_FRAGMENT_BIT); } else { // Loading one pass shaders shader_stages_first_pass[0] = load_shader("mobile_nerf/raster.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); - shader_stages_first_pass[1] = load_shader( - using_original_nerf_models[0] ? "mobile_nerf/merged.frag.spv" : "mobile_nerf/merged_morpheus.frag.spv", - VK_SHADER_STAGE_FRAGMENT_BIT); + shader_stages_first_pass[1] = + load_shader(using_original_nerf_models[0] ? "mobile_nerf/merged.frag.spv" : "mobile_nerf/merged_morpheus.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); } } @@ -520,22 +519,12 @@ void MobileNerf::setup_attachment(VkFormat format, VkImageUsageFlags usage, Fram } auto surfaceExtent = get_render_context().get_surface_extent(); - attachment.image = std::make_unique( - get_device(), - VkExtent3D{surfaceExtent.width, surfaceExtent.height, 1}, - format, - usage, - VMA_MEMORY_USAGE_GPU_ONLY); + attachment.image = + std::make_unique(get_device(), VkExtent3D{surfaceExtent.width, surfaceExtent.height, 1}, format, usage, VMA_MEMORY_USAGE_GPU_ONLY); with_command_buffer([&](VkCommandBuffer command_buffer) { - vkb::image_layout_transition(command_buffer, attachment.image->get_handle(), - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - {}, - {}, - VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_GENERAL, - {aspectMask, 0, 1, 0, 1}); + vkb::image_layout_transition(command_buffer, attachment.image->get_handle(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, {}, + {}, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, {aspectMask, 0, 1, 0, 1}); }); VkImageViewCreateInfo color_image_view = vkb::initializers::image_view_create_info(); @@ -560,7 +549,8 @@ void MobileNerf::setup_nerf_framebuffer_baseline() { setup_attachment(feature_map_format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, frameAttachments[i].feature_0); setup_attachment(feature_map_format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, frameAttachments[i].feature_1); - setup_attachment(VK_FORMAT_R16G16B16A16_SFLOAT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, frameAttachments[i].feature_2); + setup_attachment(VK_FORMAT_R16G16B16A16_SFLOAT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, + frameAttachments[i].feature_2); if (combo_mode) setup_attachment(VK_FORMAT_R8_UINT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, frameAttachments[i].weights_idx); } @@ -651,30 +641,30 @@ void MobileNerf::update_descriptor_sets_baseline() attachment_input_descriptors[3].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } - VkWriteDescriptorSet texture_input_write_0 = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 0, &attachment_input_descriptors[0]); - VkWriteDescriptorSet texture_input_write_1 = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1, &attachment_input_descriptors[1]); - VkWriteDescriptorSet texture_input_write_2 = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 2, &attachment_input_descriptors[2]); + VkWriteDescriptorSet texture_input_write_0 = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 0, &attachment_input_descriptors[0]); + VkWriteDescriptorSet texture_input_write_1 = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1, &attachment_input_descriptors[1]); + VkWriteDescriptorSet texture_input_write_2 = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 2, &attachment_input_descriptors[2]); if (combo_mode) { - VkWriteDescriptorSet texture_input_write_3 = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 3, &attachment_input_descriptors[3]); + VkWriteDescriptorSet texture_input_write_3 = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 3, &attachment_input_descriptors[3]); - std::vector write_descriptor_sets = { - texture_input_write_0, - texture_input_write_1, - texture_input_write_2, - texture_input_write_3}; + std::vector write_descriptor_sets = {texture_input_write_0, texture_input_write_1, texture_input_write_2, + texture_input_write_3}; - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, + VK_NULL_HANDLE); } else { - std::vector write_descriptor_sets = { - texture_input_write_0, - texture_input_write_1, - texture_input_write_2}; + std::vector write_descriptor_sets = {texture_input_write_0, texture_input_write_1, texture_input_write_2}; - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, + VK_NULL_HANDLE); } } } @@ -782,8 +772,8 @@ void MobileNerf::build_command_buffers_baseline() // If deferred, only use the first descriptor bounded with the model // If forward, each model has the swapchan number of descriptor int descriptorIndex = use_deferred ? 0 : static_cast(i); - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_first_pass_layout, - 0, 1, &model.descriptor_set_first_pass[descriptorIndex], 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_first_pass_layout, 0, 1, + &model.descriptor_set_first_pass[descriptorIndex], 0, nullptr); VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(draw_cmd_buffers[i], 0, 1, model.vertex_buffer->get(), offsets); vkCmdBindVertexBuffers(draw_cmd_buffers[i], 1, 1, instance_buffer->get(), offsets); @@ -791,13 +781,7 @@ void MobileNerf::build_command_buffers_baseline() if (use_deferred && combo_mode) { PushConstants constants = {static_cast(model.model_index)}; - vkCmdPushConstants( - draw_cmd_buffers[i], - pipeline_first_pass_layout, - VK_SHADER_STAGE_FRAGMENT_BIT, - 0, - sizeof(PushConstants), - &constants); + vkCmdPushConstants(draw_cmd_buffers[i], pipeline_first_pass_layout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushConstants), &constants); } vkCmdDrawIndexed(draw_cmd_buffers[i], static_cast(model.indices.size()) * 3, ii.dim.x * ii.dim.y * ii.dim.z, 0, 0, 0); } @@ -913,7 +897,8 @@ void MobileNerf::create_descriptor_pool() if (combo_mode) { pool_sizes.push_back({VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 4 * static_cast(framebuffers.size())}); - pool_sizes.push_back({VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 * static_cast(framebuffers.size()) * static_cast(model_path.size())}); + pool_sizes.push_back( + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 * static_cast(framebuffers.size()) * static_cast(model_path.size())}); } else { @@ -921,7 +906,8 @@ void MobileNerf::create_descriptor_pool() pool_sizes.push_back({VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 * static_cast(framebuffers.size())}); } - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, static_cast(models.size() + framebuffers.size())); + VkDescriptorPoolCreateInfo descriptor_pool_create_info = + vkb::initializers::descriptor_pool_create_info(pool_sizes, static_cast(models.size() + framebuffers.size())); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } else @@ -932,7 +918,8 @@ void MobileNerf::create_descriptor_pool() {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 * static_cast(models.size()) * static_cast(framebuffers.size())}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 * static_cast(models.size()) * static_cast(framebuffers.size())}}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, static_cast(models.size() * framebuffers.size())); + VkDescriptorPoolCreateInfo descriptor_pool_create_info = + vkb::initializers::descriptor_pool_create_info(pool_sizes, static_cast(models.size() * framebuffers.size())); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } } @@ -949,17 +936,14 @@ void MobileNerf::create_pipeline_layout_fist_pass() // If use forward, add uniform buffer descriptor for the weights if (!use_deferred) { - set_layout_bindings.push_back(vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 3)); + set_layout_bindings.push_back(vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 3)); } - VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + VkDescriptorSetLayoutCreateInfo descriptor_layout = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_first_pass_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_first_pass_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_first_pass_layout, 1); if (use_deferred && combo_mode) { @@ -989,7 +973,8 @@ void MobileNerf::create_pipeline_layout_baseline() { set_layout_bindings.push_back(vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, VK_SHADER_STAGE_FRAGMENT_BIT, 3)); // MLP weights array, using descriptor indexing - set_layout_bindings.push_back(vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 4, static_cast(model_path.size()))); + set_layout_bindings.push_back(vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 4, + static_cast(model_path.size()))); } else { @@ -997,7 +982,8 @@ void MobileNerf::create_pipeline_layout_baseline() set_layout_bindings.push_back(vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 3)); } - VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + VkDescriptorSetLayoutCreateInfo descriptor_layout = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); if (combo_mode) { VkDescriptorBindingFlagsEXT flags[5] = {0, 0, 0, 0, VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT}; @@ -1013,10 +999,7 @@ void MobileNerf::create_pipeline_layout_baseline() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout_baseline)); } - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout_baseline, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout_baseline, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout_baseline)); } @@ -1044,17 +1027,14 @@ void MobileNerf::create_descriptor_sets_first_pass(Model &model) VkDescriptorBufferInfo buffer_descriptor = create_descriptor(*uniform_buffers[model.model_index]); - VkWriteDescriptorSet texture_input_write_0 = vkb::initializers::write_descriptor_set(model.descriptor_set_first_pass[i], - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &texture_input_descriptors[0]); - VkWriteDescriptorSet texture_input_write_1 = vkb::initializers::write_descriptor_set(model.descriptor_set_first_pass[i], - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &texture_input_descriptors[1]); - VkWriteDescriptorSet uniform_buffer_write = vkb::initializers::write_descriptor_set(model.descriptor_set_first_pass[i], - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); + VkWriteDescriptorSet texture_input_write_0 = vkb::initializers::write_descriptor_set( + model.descriptor_set_first_pass[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &texture_input_descriptors[0]); + VkWriteDescriptorSet texture_input_write_1 = vkb::initializers::write_descriptor_set( + model.descriptor_set_first_pass[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &texture_input_descriptors[1]); + VkWriteDescriptorSet uniform_buffer_write = + vkb::initializers::write_descriptor_set(model.descriptor_set_first_pass[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &buffer_descriptor); - std::vector write_descriptor_sets = { - texture_input_write_0, - texture_input_write_1, - uniform_buffer_write}; + std::vector write_descriptor_sets = {texture_input_write_0, texture_input_write_1, uniform_buffer_write}; VkDescriptorBufferInfo weights_buffer_descriptor; @@ -1063,8 +1043,8 @@ void MobileNerf::create_descriptor_sets_first_pass(Model &model) // Add in descriptor sets for MLP weights weights_buffer_descriptor = create_descriptor(*weights_buffers[model.model_index]); // Add in descriptor sets for MLP weights - VkWriteDescriptorSet weights_buffer_write = vkb::initializers::write_descriptor_set(model.descriptor_set_first_pass[i], - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3, &weights_buffer_descriptor); + VkWriteDescriptorSet weights_buffer_write = + vkb::initializers::write_descriptor_set(model.descriptor_set_first_pass[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3, &weights_buffer_descriptor); write_descriptor_sets.push_back(weights_buffer_write); } @@ -1078,7 +1058,8 @@ void MobileNerf::create_descriptor_sets_baseline() for (int i = 0; i < nerf_framebuffers.size(); i++) { - VkDescriptorSetAllocateInfo descriptor_set_allocate_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout_baseline, 1); + VkDescriptorSetAllocateInfo descriptor_set_allocate_info = + vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout_baseline, 1); if (combo_mode) { uint32_t counts[1]; @@ -1113,16 +1094,20 @@ void MobileNerf::create_descriptor_sets_baseline() attachment_input_descriptors[2].imageView = frameAttachments[i].feature_2.view; attachment_input_descriptors[2].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - VkWriteDescriptorSet texture_input_write_0 = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 0, &attachment_input_descriptors[0]); - VkWriteDescriptorSet texture_input_write_1 = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1, &attachment_input_descriptors[1]); - VkWriteDescriptorSet texture_input_write_2 = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 2, &attachment_input_descriptors[2]); + VkWriteDescriptorSet texture_input_write_0 = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 0, &attachment_input_descriptors[0]); + VkWriteDescriptorSet texture_input_write_1 = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1, &attachment_input_descriptors[1]); + VkWriteDescriptorSet texture_input_write_2 = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 2, &attachment_input_descriptors[2]); if (combo_mode) { attachment_input_descriptors[3].sampler = VK_NULL_HANDLE; attachment_input_descriptors[3].imageView = frameAttachments[i].weights_idx.view; attachment_input_descriptors[3].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - VkWriteDescriptorSet texture_input_write_3 = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 3, &attachment_input_descriptors[3]); + VkWriteDescriptorSet texture_input_write_3 = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 3, &attachment_input_descriptors[3]); std::vector weights_buffer_descriptors; weights_buffer_descriptors.reserve(mlp_weight_vector.size()); @@ -1130,39 +1115,38 @@ void MobileNerf::create_descriptor_sets_baseline() { weights_buffer_descriptors.emplace_back(create_descriptor(*weight_buffer)); } - VkWriteDescriptorSet weights_buffer_write = vkb::initializers::write_descriptor_set( - descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4, weights_buffer_descriptors.data(), static_cast(weights_buffer_descriptors.size())); + VkWriteDescriptorSet weights_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 4, weights_buffer_descriptors.data(), + static_cast(weights_buffer_descriptors.size())); - std::vector write_descriptor_sets = { - texture_input_write_0, - texture_input_write_1, - texture_input_write_2, - texture_input_write_3, - weights_buffer_write}; + std::vector write_descriptor_sets = {texture_input_write_0, texture_input_write_1, texture_input_write_2, + texture_input_write_3, weights_buffer_write}; - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, + VK_NULL_HANDLE); } else { VkDescriptorBufferInfo weights_buffer_descriptor = create_descriptor(*weights_buffers[models[0].model_index]); - VkWriteDescriptorSet weights_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3, &weights_buffer_descriptor); // UBO + VkWriteDescriptorSet weights_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set_baseline[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 3, &weights_buffer_descriptor); // UBO - std::vector write_descriptor_sets = { - texture_input_write_0, - texture_input_write_1, - texture_input_write_2, - weights_buffer_write}; + std::vector write_descriptor_sets = {texture_input_write_0, texture_input_write_1, texture_input_write_2, + weights_buffer_write}; - vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); + vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, + VK_NULL_HANDLE); } } } void MobileNerf::prepare_pipelines() { - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, /*VK_CULL_MODE_BACK_BIT*/ VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE /*VK_FRONT_FACE_CLOCKWISE*/, 0); + VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info( + VK_POLYGON_MODE_FILL, /*VK_CULL_MODE_BACK_BIT*/ VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE /*VK_FRONT_FACE_CLOCKWISE*/, 0); std::vector blend_attachment_states; blend_attachment_states.push_back(vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)); @@ -1175,24 +1159,21 @@ void MobileNerf::prepare_pipelines() blend_attachment_states.push_back(vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)); } - VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(static_cast(blend_attachment_states.size()), blend_attachment_states.data()); + VkPipelineColorBlendStateCreateInfo color_blend_state = + vkb::initializers::pipeline_color_blend_state_create_info(static_cast(blend_attachment_states.size()), blend_attachment_states.data()); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS); - depth_stencil_state.depthBoundsTestEnable = VK_FALSE; - depth_stencil_state.minDepthBounds = 0.f; - depth_stencil_state.maxDepthBounds = 1.f; + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS); + depth_stencil_state.depthBoundsTestEnable = VK_FALSE; + depth_stencil_state.minDepthBounds = 0.f; + depth_stencil_state.maxDepthBounds = 1.f; VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); @@ -1262,40 +1243,27 @@ void MobileNerf::create_static_object_buffers(int model_index, int sub_model_ind auto index_buffer_size = model.indices.size() * sizeof(model.indices[0]); // Create destination buffers - model.vertex_buffer = std::make_unique( - get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + model.vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); model.vertex_buffer->set_debug_name(fmt::format("Model #{} Sub-Model #{} vertices", model_index, sub_model_index)); - model.index_buffer = std::make_unique( - get_device(), - index_buffer_size, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + model.index_buffer = std::make_unique(get_device(), index_buffer_size, + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); model.index_buffer->set_debug_name(fmt::format("Model #{} Sub-Model #{} indices", model_index, sub_model_index)); // Create staging buffers - std::unique_ptr staging_vertex_buffer = std::make_unique( - get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr staging_vertex_buffer = + std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); staging_vertex_buffer->update(model.vertices); - std::unique_ptr staging_index_buffer = std::make_unique( - get_device(), - index_buffer_size, - VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr staging_index_buffer = + std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); staging_index_buffer->update(model.indices); // Copy over the data for each of the models - with_vkb_command_buffer( - [&](vkb::core::CommandBufferC &cmd) { - cmd.copy_buffer(*staging_vertex_buffer, *model.vertex_buffer, staging_vertex_buffer->get_size()); - cmd.copy_buffer(*staging_index_buffer, *model.index_buffer, staging_index_buffer->get_size()); - }); + with_vkb_command_buffer([&](vkb::core::CommandBufferC &cmd) { + cmd.copy_buffer(*staging_vertex_buffer, *model.vertex_buffer, staging_vertex_buffer->get_size()); + cmd.copy_buffer(*staging_index_buffer, *model.index_buffer, staging_index_buffer->get_size()); + }); LOGI("Done Creating static object buffers"); } @@ -1308,16 +1276,12 @@ void MobileNerf::create_uniforms() for (int i = 0; i < model_path.size(); i++) { LOGI("Creating camera view uniform buffer for model {}", i); - uniform_buffers[i] = std::make_unique(get_device(), - sizeof(global_uniform), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffers[i] = + std::make_unique(get_device(), sizeof(global_uniform), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); LOGI("Creating mlp weights uniform buffer for model {}", i); - weights_buffers[i] = std::make_unique(get_device(), - sizeof(MLP_Weights), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + weights_buffers[i] = + std::make_unique(get_device(), sizeof(MLP_Weights), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } update_uniform_buffers(); @@ -1453,8 +1417,7 @@ void MobileNerf::initialize_mlp_uniform_buffers(int model_index) for (int ii = 0; ii < BIAS_1_COUNT; ii++) { - model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + - BIAS_0_COUNT + ii] = bias_1_array[ii]; + model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + BIAS_0_COUNT + ii] = bias_1_array[ii]; } // We need to pad the layer 2's bias with zeros for every 3 weights to make it 16 bytes aligned @@ -1462,13 +1425,11 @@ void MobileNerf::initialize_mlp_uniform_buffers(int model_index) { if ((ii + 1) % 4 == 0) { - model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + - BIAS_0_COUNT + BIAS_1_COUNT + ii] = 0.0f; + model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + BIAS_0_COUNT + BIAS_1_COUNT + ii] = 0.0f; } else { - model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + - BIAS_0_COUNT + BIAS_1_COUNT + ii] = bias_2_array[ii]; + model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + BIAS_0_COUNT + BIAS_1_COUNT + ii] = bias_2_array[ii]; } } @@ -1537,22 +1498,17 @@ void MobileNerf::prepare_instance_data() auto instance_buffer_size = instance_data.size() * sizeof(InstanceData); - instance_buffer = std::make_unique( - get_device(), - instance_buffer_size, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + instance_buffer = std::make_unique(get_device(), instance_buffer_size, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); // Copy over the data for each of the models - auto staging_instance_buffer = std::make_unique( - get_device(), - instance_buffer_size, - VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + auto staging_instance_buffer = + std::make_unique(get_device(), instance_buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); staging_instance_buffer->update(instance_data); // now transfer over to the end buffer - with_vkb_command_buffer([&](vkb::core::CommandBufferC &cmd) { cmd.copy_buffer(*staging_instance_buffer, *instance_buffer, staging_instance_buffer->get_size()); }); + with_vkb_command_buffer( + [&](vkb::core::CommandBufferC &cmd) { cmd.copy_buffer(*staging_instance_buffer, *instance_buffer, staging_instance_buffer->get_size()); }); } void MobileNerf::draw() diff --git a/samples/general/mobile_nerf/mobile_nerf.h b/samples/general/mobile_nerf/mobile_nerf.h index b172d42a8d..7e51814e22 100644 --- a/samples/general/mobile_nerf/mobile_nerf.h +++ b/samples/general/mobile_nerf/mobile_nerf.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Qualcomm Innovation Center, Inc. All rights reserved. +/* Copyright (c) 2023-2026, Qualcomm Innovation Center, Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -76,8 +76,7 @@ class MobileNerf : public ApiVulkanSample struct MLP_Weights { - float data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + - BIAS_0_COUNT + BIAS_1_COUNT + BIAS_2_COUNT]; // Array of floats + float data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + BIAS_0_COUNT + BIAS_1_COUNT + BIAS_2_COUNT]; // Array of floats }; struct Vertex @@ -220,9 +219,8 @@ class MobileNerf : public ApiVulkanSample glm::vec3 camera_pos = glm::vec3(-2.2f, 2.2f, 2.2f); // Currently combo mode translation are hard-coded - glm::mat4x4 combo_model_transform[4] = { - glm::translate(glm::vec3(0.5, 0.75, 0)), glm::translate(glm::vec3(0.5, 0.25, 0)), - glm::translate(glm::vec3(0, -0.25, 0.5)), glm::translate(glm::vec3(0, -0.75, -0.5))}; + glm::mat4x4 combo_model_transform[4] = {glm::translate(glm::vec3(0.5, 0.75, 0)), glm::translate(glm::vec3(0.5, 0.25, 0)), + glm::translate(glm::vec3(0, -0.25, 0.5)), glm::translate(glm::vec3(0, -0.75, -0.5))}; // For instancing InstancingInfo instancing_info; diff --git a/samples/general/mobile_nerf_rayquery/mobile_nerf_rayquery.cpp b/samples/general/mobile_nerf_rayquery/mobile_nerf_rayquery.cpp index af265a6f16..57a2c895a0 100644 --- a/samples/general/mobile_nerf_rayquery/mobile_nerf_rayquery.cpp +++ b/samples/general/mobile_nerf_rayquery/mobile_nerf_rayquery.cpp @@ -391,7 +391,8 @@ void MobileNerfRayQuery::read_json_map() if (instacing_map["interval"].is_array() && instacing_map["interval"].size() == 3) { - instancing_info.interval = glm::vec3(instacing_map["interval"][0].get(), instacing_map["interval"][1].get(), instacing_map["interval"][2].get()); + instancing_info.interval = + glm::vec3(instacing_map["interval"][0].get(), instacing_map["interval"][1].get(), instacing_map["interval"][2].get()); } else { @@ -399,7 +400,8 @@ void MobileNerfRayQuery::read_json_map() exit(1); } - if (instancing_info.dim.x <= 0 || instancing_info.dim.y <= 0 || instancing_info.dim.z <= 0 || instancing_info.interval.x <= 0.f || instancing_info.interval.y <= 0.f || instancing_info.interval.z <= 0.f) + if (instancing_info.dim.x <= 0 || instancing_info.dim.y <= 0 || instancing_info.dim.z <= 0 || instancing_info.interval.x <= 0.f || + instancing_info.interval.y <= 0.f || instancing_info.interval.z <= 0.f) { LOGE("Instancing settings must be positive. Terminating..."); exit(1); @@ -532,8 +534,7 @@ void MobileNerfRayQuery::initialize_mlp_uniform_buffers(int model_index) for (int ii = 0; ii < BIAS_1_COUNT; ii++) { - model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + - BIAS_0_COUNT + ii] = bias_1_array[ii]; + model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + BIAS_0_COUNT + ii] = bias_1_array[ii]; } // We need to pad the layer 2's bias with zeros for every 3 weights to make it 16 bytes aligned @@ -541,13 +542,11 @@ void MobileNerfRayQuery::initialize_mlp_uniform_buffers(int model_index) { if ((ii + 1) % 4 == 0) { - model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + - BIAS_0_COUNT + BIAS_1_COUNT + ii] = 0.0f; + model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + BIAS_0_COUNT + BIAS_1_COUNT + ii] = 0.0f; } else { - model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + - BIAS_0_COUNT + BIAS_1_COUNT + ii] = bias_2_array[ii]; + model_mlp.data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + BIAS_0_COUNT + BIAS_1_COUNT + ii] = bias_2_array[ii]; } } @@ -561,11 +560,8 @@ void MobileNerfRayQuery::initialize_mlp_uniform_buffers(int model_index) void MobileNerfRayQuery::load_shaders() { shader_stages[0] = load_shader("mobile_nerf_rayquery/quad.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); - shader_stages[1] = load_shader( - combo_mode ? - "mobile_nerf_rayquery/rayquery_morpheus_combo.frag.spv" : - "mobile_nerf_rayquery/rayquery_morpheus.frag.spv", - VK_SHADER_STAGE_FRAGMENT_BIT); + shader_stages[1] = load_shader(combo_mode ? "mobile_nerf_rayquery/rayquery_morpheus_combo.frag.spv" : "mobile_nerf_rayquery/rayquery_morpheus.frag.spv", + VK_SHADER_STAGE_FRAGMENT_BIT); } void MobileNerfRayQuery::load_scene(int model_index, int sub_model_index, int models_entry) @@ -685,36 +681,25 @@ void MobileNerfRayQuery::create_static_object_buffers(int models_entry) // Note that in contrast to a typical pipeline, our vertex/index buffer requires the acceleration structure build flag in rayquery // Create a staging buffer - const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; - const VkBufferUsageFlags staging_flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + const VkBufferUsageFlags buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + const VkBufferUsageFlags staging_flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; // Create destination buffers - model.vertex_buffer = std::make_unique( - get_device(), - vertex_buffer_size, - buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + model.vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VMA_MEMORY_USAGE_GPU_ONLY); model.vertex_buffer->set_debug_name(fmt::format("Model #{} vertices", models_entry)); - model.index_buffer = std::make_unique( - get_device(), - index_buffer_size, - buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + model.index_buffer = + std::make_unique(get_device(), index_buffer_size, buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY); model.index_buffer->set_debug_name(fmt::format("Model #{} indices", models_entry)); // Create staging buffers - std::unique_ptr staging_vertex_buffer = std::make_unique( - get_device(), - vertex_buffer_size, - staging_flags, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr staging_vertex_buffer = + std::make_unique(get_device(), vertex_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); staging_vertex_buffer->update(model.vertices); - std::unique_ptr staging_index_buffer = std::make_unique( - get_device(), - index_buffer_size, - staging_flags, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr staging_index_buffer = + std::make_unique(get_device(), index_buffer_size, staging_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); staging_index_buffer->update(model.indices); // Copy over the data for each of the models @@ -731,18 +716,14 @@ void MobileNerfRayQuery::create_uniforms() weights_buffers.resize(num_models); LOGI("Creating camera view uniform buffer"); - uniform_buffer = std::make_unique(get_device(), - sizeof(global_uniform), - VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer = std::make_unique( + get_device(), sizeof(global_uniform), VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); for (int i = 0; i < num_models; i++) { LOGI("Creating mlp weights uniform buffer for model {}", i); - weights_buffers[i] = std::make_unique(get_device(), - sizeof(MLP_Weights), - VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + weights_buffers[i] = std::make_unique( + get_device(), sizeof(MLP_Weights), VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } update_uniform_buffer(); @@ -809,18 +790,7 @@ void MobileNerfRayQuery::create_top_level_acceleration_structure() { offset.z = corner_pos.z + ii.interval.z * z; VkTransformMatrixKHR transform_matrix = { - 1.0f, - 0.0f, - 0.0f, - offset.x, - 0.0f, - 1.0f, - 0.0f, - offset.y, - 0.0f, - 0.0f, - 1.0f, - offset.z, + 1.0f, 0.0f, 0.0f, offset.x, 0.0f, 1.0f, 0.0f, offset.y, 0.0f, 0.0f, 1.0f, offset.z, }; for (size_t i = 0; i < models.size(); ++i) { @@ -833,10 +803,9 @@ void MobileNerfRayQuery::create_top_level_acceleration_structure() LOGI("model num: {}", models.size()); const size_t instancesDataSize = sizeof(VkAccelerationStructureInstanceKHR) * acceleration_structure_instances.size(); - std::unique_ptr instances_buffer = std::make_unique(get_device(), - instancesDataSize, - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr instances_buffer = std::make_unique( + get_device(), instancesDataSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU); instances_buffer->update(acceleration_structure_instances.data(), instancesDataSize); top_level_acceleration_structure = std::make_unique(get_device(), VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR); @@ -851,42 +820,33 @@ void MobileNerfRayQuery::create_bottom_level_acceleration_structure(int model_en // Create buffers for the bottom level geometry // Note that the buffer usage flags for buffers consumed by the bottom level acceleration structure require special flags - const VkBufferUsageFlags buffer_usage_flags = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + const VkBufferUsageFlags buffer_usage_flags = + VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; // Set up a single transformation matrix that can be used to transform the whole geometry for a single bottom level acceleration structure - VkTransformMatrixKHR transform_matrix = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f}; + VkTransformMatrixKHR transform_matrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; if (combo_mode) { // Use hard-coded transformation under combo mode glm::mat4x4 &M = combo_model_transform[model_entry]; - transform_matrix = { - M[0][0], M[1][0], M[2][0], M[3][0], - M[0][1], M[1][1], M[2][1], -M[3][1], - M[0][2], M[1][2], M[2][2], M[3][2]}; + transform_matrix = {M[0][0], M[1][0], M[2][0], M[3][0], M[0][1], M[1][1], M[2][1], -M[3][1], M[0][2], M[1][2], M[2][2], M[3][2]}; } - std::unique_ptr transform_matrix_buffer = std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr transform_matrix_buffer = + std::make_unique(get_device(), sizeof(transform_matrix), buffer_usage_flags, VMA_MEMORY_USAGE_CPU_TO_GPU); transform_matrix_buffer->update(&transform_matrix, sizeof(transform_matrix)); if (model.bottom_level_acceleration_structure == nullptr) { - model.bottom_level_acceleration_structure = std::make_unique( - get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); + model.bottom_level_acceleration_structure = + std::make_unique(get_device(), VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR); model.bottom_level_acceleration_structure->add_triangle_geometry( - *model.vertex_buffer, - *model.index_buffer, - *transform_matrix_buffer, - model.indices.size(), - model.vertices.size(), - sizeof(Vertex), - 0, VK_FORMAT_R32G32B32_SFLOAT, VK_INDEX_TYPE_UINT32, VK_GEOMETRY_OPAQUE_BIT_KHR, - get_buffer_device_address(model.vertex_buffer->get_handle()), + *model.vertex_buffer, *model.index_buffer, *transform_matrix_buffer, model.indices.size(), model.vertices.size(), sizeof(Vertex), 0, + VK_FORMAT_R32G32B32_SFLOAT, VK_INDEX_TYPE_UINT32, VK_GEOMETRY_OPAQUE_BIT_KHR, get_buffer_device_address(model.vertex_buffer->get_handle()), get_buffer_device_address(model.index_buffer->get_handle())); } model.bottom_level_acceleration_structure->set_scrach_buffer_alignment(acceleration_structure_properties.minAccelerationStructureScratchOffsetAlignment); - model.bottom_level_acceleration_structure->build(queue, VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR, VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); + model.bottom_level_acceleration_structure->build(queue, VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR, + VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); } void MobileNerfRayQuery::create_pipeline_layout() @@ -902,15 +862,16 @@ void MobileNerfRayQuery::create_pipeline_layout() // Add an array of weights sets into shader if (combo_mode) { - set_layout_bindings_common.push_back(vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 2, num_models)); + set_layout_bindings_common.push_back( + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 2, num_models)); } else { - set_layout_bindings_common.push_back(vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 2)); + set_layout_bindings_common.push_back( + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 2)); } - VkDescriptorSetLayoutCreateInfo descriptor_layout_bounded = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings_common.data(), static_cast(set_layout_bindings_common.size())); + VkDescriptorSetLayoutCreateInfo descriptor_layout_bounded = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings_common.data(), static_cast(set_layout_bindings_common.size())); if (combo_mode) { VkDescriptorBindingFlagsEXT flags[3] = {0, 0, VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT}; @@ -937,29 +898,27 @@ void MobileNerfRayQuery::create_pipeline_layout() VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &layout_handle)); }; - VkDescriptorSetLayoutBinding set_layout_binding_vertices = vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, models.size()); + VkDescriptorSetLayoutBinding set_layout_binding_vertices = + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, models.size()); create_unbounded_descriptor_set_layout(descriptor_set_layout_vertices, set_layout_binding_vertices); - VkDescriptorSetLayoutBinding set_layout_binding_indices = vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, models.size()); + VkDescriptorSetLayoutBinding set_layout_binding_indices = + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, models.size()); create_unbounded_descriptor_set_layout(descriptor_set_layout_indices, set_layout_binding_indices); - VkDescriptorSetLayoutBinding set_layout_binding_feature1 = vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, models.size()); + VkDescriptorSetLayoutBinding set_layout_binding_feature1 = + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, models.size()); create_unbounded_descriptor_set_layout(descriptor_set_layout_feature1, set_layout_binding_feature1); - VkDescriptorSetLayoutBinding set_layout_binding_feature2 = vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, models.size()); + VkDescriptorSetLayoutBinding set_layout_binding_feature2 = + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, models.size()); create_unbounded_descriptor_set_layout(descriptor_set_layout_feature2, set_layout_binding_feature2); - std::vector descriptor_set_layouts = { - descriptor_set_layout_common, - descriptor_set_layout_vertices, - descriptor_set_layout_indices, - descriptor_set_layout_feature1, - descriptor_set_layout_feature2}; + std::vector descriptor_set_layouts = {descriptor_set_layout_common, descriptor_set_layout_vertices, descriptor_set_layout_indices, + descriptor_set_layout_feature1, descriptor_set_layout_feature2}; VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - descriptor_set_layouts.data(), - static_cast(descriptor_set_layouts.size())); + vkb::initializers::pipeline_layout_create_info(descriptor_set_layouts.data(), static_cast(descriptor_set_layouts.size())); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } @@ -972,7 +931,8 @@ void MobileNerfRayQuery::create_descriptor_pool() {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 * static_cast(framebuffers.size()) * static_cast(num_models)}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2 * static_cast(models.size()) * static_cast(framebuffers.size())}, {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2 * static_cast(models.size()) * static_cast(framebuffers.size())}}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 5 * static_cast(framebuffers.size())); + VkDescriptorPoolCreateInfo descriptor_pool_create_info = + vkb::initializers::descriptor_pool_create_info(pool_sizes, 5 * static_cast(framebuffers.size())); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -994,9 +954,8 @@ void MobileNerfRayQuery::create_descriptor_sets() set_counts.descriptorSetCount = 1; set_counts.pDescriptorCounts = counts; - VkDescriptorSetAllocateInfo descriptor_set_allocate_info = - vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); - descriptor_set_allocate_info.pNext = &set_counts; + VkDescriptorSetAllocateInfo descriptor_set_allocate_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); + descriptor_set_allocate_info.pNext = &set_counts; VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_set_allocate_info, &descriptor_set)); }; @@ -1049,16 +1008,20 @@ void MobileNerfRayQuery::create_descriptor_sets() texture_input_2_descriptors.emplace_back(texture_input_2_descriptor); } - VkWriteDescriptorSet uniform_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set_common[i], - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniform_buffer_descriptor); - VkWriteDescriptorSet vertex_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set_vertices[i], - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, vertex_buffer_descriptors.data(), static_cast(vertex_buffer_descriptors.size())); - VkWriteDescriptorSet index_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set_indices[i], - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, index_buffer_descriptors.data(), static_cast(index_buffer_descriptors.size())); - VkWriteDescriptorSet texture_input_write_0 = vkb::initializers::write_descriptor_set(descriptor_set_feature1[i], - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, texture_input_1_descriptors.data(), static_cast(texture_input_1_descriptors.size())); - VkWriteDescriptorSet texture_input_write_1 = vkb::initializers::write_descriptor_set(descriptor_set_feature2[i], - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, texture_input_2_descriptors.data(), static_cast(texture_input_2_descriptors.size())); + VkWriteDescriptorSet uniform_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set_common[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniform_buffer_descriptor); + VkWriteDescriptorSet vertex_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set_vertices[i], VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, vertex_buffer_descriptors.data(), + static_cast(vertex_buffer_descriptors.size())); + VkWriteDescriptorSet index_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set_indices[i], VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, index_buffer_descriptors.data(), + static_cast(index_buffer_descriptors.size())); + VkWriteDescriptorSet texture_input_write_0 = + vkb::initializers::write_descriptor_set(descriptor_set_feature1[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, + texture_input_1_descriptors.data(), static_cast(texture_input_1_descriptors.size())); + VkWriteDescriptorSet texture_input_write_1 = + vkb::initializers::write_descriptor_set(descriptor_set_feature2[i], VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, + texture_input_2_descriptors.data(), static_cast(texture_input_2_descriptors.size())); // Set up the descriptor for binding our top level acceleration structure to the ray tracing shaders VkWriteDescriptorSetAccelerationStructureKHR descriptor_acceleration_structure_info{}; @@ -1089,23 +1052,18 @@ void MobileNerfRayQuery::create_descriptor_sets() { weights_buffer_descriptors.emplace_back(create_descriptor(*weight_buffer)); } - weights_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set_common[i], - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, weights_buffer_descriptors.data(), static_cast(weights_buffer_descriptors.size())); + weights_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set_common[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, weights_buffer_descriptors.data(), + static_cast(weights_buffer_descriptors.size())); } else { weights_buffer_descriptor = create_descriptor(*weights_buffers[0]); - weights_buffer_write = vkb::initializers::write_descriptor_set(descriptor_set_common[i], - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &weights_buffer_descriptor); + weights_buffer_write = + vkb::initializers::write_descriptor_set(descriptor_set_common[i], VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &weights_buffer_descriptor); } - write_descriptor_sets = std::vector{ - uniform_buffer_write, - acceleration_structure_write, - weights_buffer_write, - vertex_buffer_write, - index_buffer_write, - texture_input_write_0, - texture_input_write_1}; + write_descriptor_sets = std::vector{uniform_buffer_write, acceleration_structure_write, weights_buffer_write, vertex_buffer_write, + index_buffer_write, texture_input_write_0, texture_input_write_1}; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, VK_NULL_HANDLE); } @@ -1113,30 +1071,29 @@ void MobileNerfRayQuery::create_descriptor_sets() void MobileNerfRayQuery::prepare_pipelines() { - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, /*VK_CULL_MODE_BACK_BIT*/ VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE /*VK_FRONT_FACE_CLOCKWISE*/, 0); + VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info( + VK_POLYGON_MODE_FILL, /*VK_CULL_MODE_BACK_BIT*/ VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE /*VK_FRONT_FACE_CLOCKWISE*/, 0); std::vector blend_attachment_states; blend_attachment_states.push_back(vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE)); - VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(static_cast(blend_attachment_states.size()), blend_attachment_states.data()); + VkPipelineColorBlendStateCreateInfo color_blend_state = + vkb::initializers::pipeline_color_blend_state_create_info(static_cast(blend_attachment_states.size()), blend_attachment_states.data()); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS); - depth_stencil_state.depthBoundsTestEnable = VK_FALSE; - depth_stencil_state.minDepthBounds = 0.f; - depth_stencil_state.maxDepthBounds = 1.f; + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS); + depth_stencil_state.depthBoundsTestEnable = VK_FALSE; + depth_stencil_state.minDepthBounds = 0.f; + depth_stencil_state.maxDepthBounds = 1.f; VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); @@ -1202,14 +1159,10 @@ void MobileNerfRayQuery::build_command_buffers() // see https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_EXT_descriptor_indexing.html vkCmdBindPipeline(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); std::vector descriptor_sets_first_pass = { - descriptor_set_common[i], - descriptor_set_vertices[i], - descriptor_set_indices[i], - descriptor_set_feature1[i], - descriptor_set_feature2[i], + descriptor_set_common[i], descriptor_set_vertices[i], descriptor_set_indices[i], descriptor_set_feature1[i], descriptor_set_feature2[i], }; - vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, - 0, static_cast(descriptor_sets_first_pass.size()), descriptor_sets_first_pass.data(), 0, nullptr); + vkCmdBindDescriptorSets(draw_cmd_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, + static_cast(descriptor_sets_first_pass.size()), descriptor_sets_first_pass.data(), 0, nullptr); VkDeviceSize offsets[1] = {0}; vkCmdDraw(draw_cmd_buffers[i], 3, 1, 0, 0); diff --git a/samples/general/mobile_nerf_rayquery/mobile_nerf_rayquery.h b/samples/general/mobile_nerf_rayquery/mobile_nerf_rayquery.h index a77419727c..e1b47e8622 100644 --- a/samples/general/mobile_nerf_rayquery/mobile_nerf_rayquery.h +++ b/samples/general/mobile_nerf_rayquery/mobile_nerf_rayquery.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2023-2025, Qualcomm Innovation Center, Inc. All rights reserved. +/* Copyright (c) 2023-2026, Qualcomm Innovation Center, Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * @@ -67,8 +67,7 @@ class MobileNerfRayQuery : public ApiVulkanSample // some typedef for each model struct MLP_Weights { - float data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + - BIAS_0_COUNT + BIAS_1_COUNT + BIAS_2_COUNT]; // Array of floats + float data[WEIGHTS_0_COUNT + WEIGHTS_1_COUNT + WEIGHTS_2_COUNT + BIAS_0_COUNT + BIAS_1_COUNT + BIAS_2_COUNT]; // Array of floats }; struct Vertex @@ -151,9 +150,8 @@ class MobileNerfRayQuery : public ApiVulkanSample glm::vec3 camera_pos = glm::vec3(-2.2f, 2.2f, 2.2f); // Currently combo mode translation are hard-coded - glm::mat4x4 combo_model_transform[4] = { - glm::translate(glm::vec3(0.5, 0.75, 0)), glm::translate(glm::vec3(0.5, 0.25, 0)), - glm::translate(glm::vec3(0, -0.25, 0.5)), glm::translate(glm::vec3(0, -0.75, -0.5))}; + glm::mat4x4 combo_model_transform[4] = {glm::translate(glm::vec3(0.5, 0.75, 0)), glm::translate(glm::vec3(0.5, 0.25, 0)), + glm::translate(glm::vec3(0, -0.25, 0.5)), glm::translate(glm::vec3(0, -0.75, -0.5))}; // For instancing InstancingInfo instancing_info; @@ -168,7 +166,8 @@ class MobileNerfRayQuery : public ApiVulkanSample VkFormat feature_map_format = VK_FORMAT_R16G16B16A16_SFLOAT; // Acceleration structure properties. - VkPhysicalDeviceAccelerationStructurePropertiesKHR acceleration_structure_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_PROPERTIES_KHR}; + VkPhysicalDeviceAccelerationStructurePropertiesKHR acceleration_structure_properties{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_PROPERTIES_KHR}; void read_json_map(); void load_shaders(); diff --git a/samples/performance/16bit_arithmetic/16bit_arithmetic.cpp b/samples/performance/16bit_arithmetic/16bit_arithmetic.cpp index 04d562057d..062aaf512c 100644 --- a/samples/performance/16bit_arithmetic/16bit_arithmetic.cpp +++ b/samples/performance/16bit_arithmetic/16bit_arithmetic.cpp @@ -100,9 +100,8 @@ bool KHR16BitArithmeticSample::prepare(const vkb::ApplicationOptions &options) // Upload the blob buffer. auto &device = get_render_context().get_device(); - blob_buffer = std::make_unique(device, sizeof(initial_data_fp16), - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + blob_buffer = std::make_unique(device, sizeof(initial_data_fp16), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VMA_MEMORY_USAGE_GPU_ONLY); auto staging_buffer = vkb::core::BufferC::create_staging_buffer(device, initial_data_fp16); auto cmd = device.get_command_pool().request_command_buffer(); @@ -122,13 +121,10 @@ bool KHR16BitArithmeticSample::prepare(const vkb::ApplicationOptions &options) device.get_fence_pool().wait(); // Create the target image we render into in the main compute shader. - image = std::make_unique(device, VkExtent3D{Width, Height, 1}, - VK_FORMAT_R16G16B16A16_SFLOAT, - VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, - VMA_MEMORY_USAGE_GPU_ONLY); + image = std::make_unique(device, VkExtent3D{Width, Height, 1}, VK_FORMAT_R16G16B16A16_SFLOAT, + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VMA_MEMORY_USAGE_GPU_ONLY); - image_view = std::make_unique(*image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R16G16B16A16_SFLOAT, - 0, 0, 1, 1); + image_view = std::make_unique(*image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R16G16B16A16_SFLOAT, 0, 0, 1, 1); // Calculate valid filter VkFilter filter = VK_FILTER_LINEAR; @@ -146,8 +142,7 @@ bool KHR16BitArithmeticSample::prepare(const vkb::ApplicationOptions &options) // Load shader modules. auto &module = - device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, - vkb::ShaderSource{"16bit_arithmetic/compute_buffer.comp.spv"}); + device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"16bit_arithmetic/compute_buffer.comp.spv"}); compute_layout = &device.get_resource_cache().request_pipeline_layout({&module}); if (supported_extensions) @@ -155,16 +150,14 @@ bool KHR16BitArithmeticSample::prepare(const vkb::ApplicationOptions &options) vkb::ShaderVariant variant; if (supports_push_constant16) { - auto &module_fp16 = - device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, - vkb::ShaderSource{"16bit_arithmetic/compute_buffer_fp16.comp.spv"}, variant); + auto &module_fp16 = device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, + vkb::ShaderSource{"16bit_arithmetic/compute_buffer_fp16.comp.spv"}, variant); compute_layout_fp16 = &device.get_resource_cache().request_pipeline_layout({&module_fp16}); } else { - auto &module_fp16 = - device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, - vkb::ShaderSource{"16bit_arithmetic/compute_buffer_fp16_fallback.comp.spv"}, variant); + auto &module_fp16 = device.get_resource_cache().request_shader_module( + VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource{"16bit_arithmetic/compute_buffer_fp16_fallback.comp.spv"}, variant); compute_layout_fp16 = &device.get_resource_cache().request_pipeline_layout({&module_fp16}); } } @@ -215,9 +208,9 @@ void KHR16BitArithmeticSample::VisualizationSubpass::draw(vkb::core::CommandBuff void KHR16BitArithmeticSample::VisualizationSubpass::prepare() { - auto &device = get_render_context().get_device(); - auto &vert_shader_module = device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_VERTEX_BIT, get_vertex_shader()); - auto &frag_shader_module = device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_FRAGMENT_BIT, get_fragment_shader()); + auto &device = get_render_context().get_device(); + auto &vert_shader_module = device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_VERTEX_BIT, get_vertex_shader()); + auto &frag_shader_module = device.get_resource_cache().request_shader_module(VK_SHADER_STAGE_FRAGMENT_BIT, get_fragment_shader()); std::vector shader_modules{&vert_shader_module, &frag_shader_module}; layout = &device.get_resource_cache().request_pipeline_layout(shader_modules); } @@ -231,8 +224,7 @@ void KHR16BitArithmeticSample::request_gpu_features(vkb::core::PhysicalDeviceC & // Optional features. supported_extensions = REQUEST_OPTIONAL_FEATURE(gpu, VkPhysicalDeviceFloat16Int8FeaturesKHR, shaderFloat16); - supports_push_constant16 = - REQUEST_OPTIONAL_FEATURE(gpu, VkPhysicalDevice16BitStorageFeatures, storagePushConstant16); + supports_push_constant16 = REQUEST_OPTIONAL_FEATURE(gpu, VkPhysicalDevice16BitStorageFeatures, storagePushConstant16); } void KHR16BitArithmeticSample::draw_renderpass(vkb::core::CommandBufferC &command_buffer, vkb::rendering::RenderTargetC &render_target) @@ -313,7 +305,8 @@ void KHR16BitArithmeticSample::draw_renderpass(vkb::core::CommandBufferC &comman // Blit result to screen and render UI. command_buffer.begin_render_pass(render_target, load_store_infos, clear_values, subpasses); - command_buffer.set_viewport(0, {{0.0f, 0.0f, static_cast(render_target.get_extent().width), static_cast(render_target.get_extent().height), 0.0f, 1.0f}}); + command_buffer.set_viewport( + 0, {{0.0f, 0.0f, static_cast(render_target.get_extent().width), static_cast(render_target.get_extent().height), 0.0f, 1.0f}}); command_buffer.set_scissor(0, {{{0, 0}, render_target.get_extent()}}); subpasses.front()->draw(command_buffer); @@ -334,7 +327,8 @@ void KHR16BitArithmeticSample::draw_gui() } get_gui().show_options_window( - /* body = */ [this, label]() { + /* body = */ + [this, label]() { if (!supported_extensions) { ImGui::Text("%s", label); diff --git a/samples/performance/16bit_storage_input_output/16bit_storage_input_output.cpp b/samples/performance/16bit_storage_input_output/16bit_storage_input_output.cpp index 66fb224e81..34fb8f6003 100644 --- a/samples/performance/16bit_storage_input_output/16bit_storage_input_output.cpp +++ b/samples/performance/16bit_storage_input_output/16bit_storage_input_output.cpp @@ -76,9 +76,7 @@ void KHR16BitStorageInputOutputSample::setup_scene() return axis; }; - const auto get_random_angular_freq = [&]() -> float { - return 1.0f + 0.2f * float_distribution(rng); - }; + const auto get_random_angular_freq = [&]() -> float { return 1.0f + 0.2f * float_distribution(rng); }; auto &root_node = get_scene().get_root_node(); for (auto *child : root_node.get_children()) @@ -156,7 +154,8 @@ void KHR16BitStorageInputOutputSample::update_pipeline() vkb::ShaderSource vert_shader(base_path + vertex_path); vkb::ShaderSource frag_shader(base_path + fragment_path); - auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); @@ -227,9 +226,7 @@ void KHR16BitStorageInputOutputSample::draw_gui() } get_gui().show_options_window( - /* body = */ [this, label]() { - ImGui::Checkbox(label, &khr_16bit_storage_input_output_enabled); - }, + /* body = */ [this, label]() { ImGui::Checkbox(label, &khr_16bit_storage_input_output_enabled); }, /* lines = */ 1); } diff --git a/samples/performance/afbc/afbc.cpp b/samples/performance/afbc/afbc.cpp index 1d0120c44e..3e7e0d95d3 100644 --- a/samples/performance/afbc/afbc.cpp +++ b/samples/performance/afbc/afbc.cpp @@ -62,7 +62,8 @@ bool AFBCSample::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); @@ -116,7 +117,8 @@ void AFBCSample::recreate_swapchain() void AFBCSample::draw_gui() { get_gui().show_options_window( - /* body = */ [this]() { + /* body = */ + [this]() { ImGui::Checkbox("Enable AFBC", &afbc_enabled); if (get_device().is_extension_enabled(VK_EXT_IMAGE_COMPRESSION_CONTROL_EXTENSION_NAME)) diff --git a/samples/performance/async_compute/async_compute.cpp b/samples/performance/async_compute/async_compute.cpp index a1a5173c50..df6fa897ae 100644 --- a/samples/performance/async_compute/async_compute.cpp +++ b/samples/performance/async_compute/async_compute.cpp @@ -49,7 +49,8 @@ void AsyncComputeSample::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) void AsyncComputeSample::draw_gui() { get_gui().show_options_window( - /* body = */ [this]() { + /* body = */ + [this]() { ImGui::Checkbox("Enable async queues", &async_enabled); ImGui::Checkbox("Double buffer HDR", &double_buffer_hdr_frames); ImGui::Checkbox("Rotate shadows", &rotate_shadows); @@ -59,10 +60,7 @@ void AsyncComputeSample::draw_gui() static VkExtent3D downsample_extent(const VkExtent3D &extent, uint32_t level) { - return { - std::max(1u, extent.width >> level), - std::max(1u, extent.height >> level), - std::max(1u, extent.depth >> level)}; + return {std::max(1u, extent.width >> level), std::max(1u, extent.height >> level), std::max(1u, extent.depth >> level)}; } void AsyncComputeSample::prepare_render_targets() @@ -74,23 +72,17 @@ void AsyncComputeSample::prepare_render_targets() // Support double-buffered HDR. vkb::core::Image color_targets[2]{ - {get_device(), size, VK_FORMAT_R16G16B16A16_SFLOAT, - VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, - VMA_MEMORY_USAGE_GPU_ONLY}, - {get_device(), size, VK_FORMAT_R16G16B16A16_SFLOAT, - VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, - VMA_MEMORY_USAGE_GPU_ONLY}, + {get_device(), size, VK_FORMAT_R16G16B16A16_SFLOAT, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}, + {get_device(), size, VK_FORMAT_R16G16B16A16_SFLOAT, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}, }; color_targets[0].set_debug_name("color_targets[0]"); color_targets[1].set_debug_name("color_targets[1]"); // Should only really need one depth target, but RenderTarget needs to own the resource. vkb::core::Image depth_targets[2]{ - {get_device(), size, VK_FORMAT_D32_SFLOAT, - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, + {get_device(), size, VK_FORMAT_D32_SFLOAT, VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}, - {get_device(), size, VK_FORMAT_D32_SFLOAT, - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, + {get_device(), size, VK_FORMAT_D32_SFLOAT, VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}, }; depth_targets[0].set_debug_name("depth_targets[0]"); @@ -100,17 +92,15 @@ void AsyncComputeSample::prepare_render_targets() // Min-spec is 4K however, so clamp to that if required. VkExtent3D shadow_resolution{8 * 1024, 8 * 1024, 1}; VkImageFormatProperties depth_properties{}; - vkGetPhysicalDeviceImageFormatProperties(get_device().get_gpu().get_handle(), VK_FORMAT_D16_UNORM, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, - 0, &depth_properties); + vkGetPhysicalDeviceImageFormatProperties(get_device().get_gpu().get_handle(), VK_FORMAT_D16_UNORM, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 0, &depth_properties); shadow_resolution.width = std::min(depth_properties.maxExtent.width, shadow_resolution.width); shadow_resolution.height = std::min(depth_properties.maxExtent.height, shadow_resolution.height); shadow_resolution.width = std::min(get_device().get_gpu().get_properties().limits.maxFramebufferWidth, shadow_resolution.width); shadow_resolution.height = std::min(get_device().get_gpu().get_properties().limits.maxFramebufferHeight, shadow_resolution.height); vkb::core::Image shadow_target{get_device(), shadow_resolution, VK_FORMAT_D16_UNORM, - VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, - VMA_MEMORY_USAGE_GPU_ONLY}; + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; shadow_target.set_debug_name("shadow_target"); // Create a simple mip-chain used for bloom blur. @@ -118,13 +108,9 @@ void AsyncComputeSample::prepare_render_targets() // but there's no real reason to do it like that. for (uint32_t level = 1; level < 7; level++) { - blur_chain.push_back(std::make_unique( - get_device(), downsample_extent(size, level), - VK_FORMAT_R16G16B16A16_SFLOAT, - VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, - VMA_MEMORY_USAGE_GPU_ONLY)); - blur_chain_views.push_back(std::make_unique( - *blur_chain.back(), VK_IMAGE_VIEW_TYPE_2D)); + blur_chain.push_back(std::make_unique(get_device(), downsample_extent(size, level), VK_FORMAT_R16G16B16A16_SFLOAT, + VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VMA_MEMORY_USAGE_GPU_ONLY)); + blur_chain_views.push_back(std::make_unique(*blur_chain.back(), VK_IMAGE_VIEW_TYPE_2D)); } // Calculate valid filter @@ -251,10 +237,7 @@ bool AsyncComputeSample::prepare(const vkb::ApplicationOptions &options) auto *node = light->get_node(); // Hardcoded to fit to the scene. - auto ortho_camera = std::make_unique("shadow_camera", - -2000.0f, 3000.0f, - -2500.0f, 1500.0f, - -2000.0f, 2000.0f); + auto ortho_camera = std::make_unique("shadow_camera", -2000.0f, 3000.0f, -2500.0f, 1500.0f, -2000.0f, 2000.0f); ortho_camera->set_node(*node); get_scene().add_component(std::move(ortho_camera), *node); @@ -279,41 +262,41 @@ bool AsyncComputeSample::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource composite_vert_shader("async_compute/composite.vert.spv"); vkb::ShaderSource composite_frag_shader("async_compute/composite.frag.spv"); - auto composite_scene_subpass = - std::make_unique(get_render_context(), std::move(composite_vert_shader), std::move(composite_frag_shader)); + auto composite_scene_subpass = std::make_unique(get_render_context(), std::move(composite_vert_shader), std::move(composite_frag_shader)); forward_render_pipeline.add_subpass(std::move(scene_subpass)); - forward_render_pipeline.set_load_store({{VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE}, - {VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE}}); + forward_render_pipeline.set_load_store( + {{VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE}, {VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE}}); auto blit_render_pipeline = std::make_unique(); blit_render_pipeline->add_subpass(std::move(composite_scene_subpass)); - blit_render_pipeline->set_load_store({{VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE}, - {VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE}}); + blit_render_pipeline->set_load_store( + {{VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE}, {VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE}}); set_render_pipeline(std::move(blit_render_pipeline)); vkb::CounterSamplingConfig config; config.mode = vkb::CounterSamplingMode::Continuous; - get_stats().request_stats({ - vkb::StatIndex::frame_times, - vkb::StatIndex::gpu_cycles, - vkb::StatIndex::gpu_vertex_cycles, - vkb::StatIndex::gpu_fragment_cycles, - }, - config); + get_stats().request_stats( + { + vkb::StatIndex::frame_times, + vkb::StatIndex::gpu_cycles, + vkb::StatIndex::gpu_vertex_cycles, + vkb::StatIndex::gpu_fragment_cycles, + }, + config); create_gui(*window, &get_stats()); - auto &threshold_module = get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, - vkb::ShaderSource("async_compute/threshold.comp.spv")); - auto &blur_up_module = get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, - vkb::ShaderSource("async_compute/blur_up.comp.spv")); - auto &blur_down_module = get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, - vkb::ShaderSource("async_compute/blur_down.comp.spv")); - threshold_pipeline = &get_device().get_resource_cache().request_pipeline_layout({&threshold_module}); - blur_up_pipeline = &get_device().get_resource_cache().request_pipeline_layout({&blur_up_module}); - blur_down_pipeline = &get_device().get_resource_cache().request_pipeline_layout({&blur_down_module}); + auto &threshold_module = + get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource("async_compute/threshold.comp.spv")); + auto &blur_up_module = + get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource("async_compute/blur_up.comp.spv")); + auto &blur_down_module = + get_device().get_resource_cache().request_shader_module(VK_SHADER_STAGE_COMPUTE_BIT, vkb::ShaderSource("async_compute/blur_down.comp.spv")); + threshold_pipeline = &get_device().get_resource_cache().request_pipeline_layout({&threshold_module}); + blur_up_pipeline = &get_device().get_resource_cache().request_pipeline_layout({&blur_up_module}); + blur_down_pipeline = &get_device().get_resource_cache().request_pipeline_layout({&blur_down_module}); setup_queues(); @@ -380,13 +363,13 @@ VkSemaphore AsyncComputeSample::render_forward_offscreen_pass(VkSemaphore hdr_wa assert(1 < views.size()); { - // If maintenance9 is not enabled, resources with VK_SHARING_MODE_EXCLUSIVE must only be accessed by queues in the queue family that has ownership of the resource. - // Upon creation resources with VK_SHARING_MODE_EXCLUSIVE are not owned by any queue, ownership is implicitly acquired upon first use. - // The application must perform a queue family ownership transfer if it wishes to make the memory contents of the resource accessible to a different queue family. - // A queue family can take ownership of a resource without an ownership transfer, in the same way as for a resource that was just created, but the content will be undefined. - // We do not need to acquire color_targets[0] from present_graphics to early_graphics - // A queue transfer barrier is not necessary for the resource first access. - // Moreover, in our sample we do not care about the content at this point so we can skip the queue transfer barrier. + // If maintenance9 is not enabled, resources with VK_SHARING_MODE_EXCLUSIVE must only be accessed by queues in the queue family that has ownership of + // the resource. Upon creation resources with VK_SHARING_MODE_EXCLUSIVE are not owned by any queue, ownership is implicitly acquired upon first use. The + // application must perform a queue family ownership transfer if it wishes to make the memory contents of the resource accessible to a different queue + // family. A queue family can take ownership of a resource without an ownership transfer, in the same way as for a resource that was just created, but + // the content will be undefined. We do not need to acquire color_targets[0] from present_graphics to early_graphics A queue transfer barrier is not + // necessary for the resource first access. Moreover, in our sample we do not care about the content at this point so we can skip the queue transfer + // barrier. vkb::ImageMemoryBarrier memory_barrier{}; memory_barrier.old_layout = VK_IMAGE_LAYOUT_UNDEFINED; memory_barrier.new_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; @@ -425,14 +408,15 @@ VkSemaphore AsyncComputeSample::render_forward_offscreen_pass(VkSemaphore hdr_wa vkb::ImageMemoryBarrier memory_barrier{ .src_stage_mask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, .dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, // Ignored for the release barrier. - // Release barriers ignore dst_access_mask unless using VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR - .src_access_mask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - .dst_access_mask = 0, // dst_access_mask is ignored for release barriers, without affecting its validity - .old_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // We want a layout transition, so the old_layout and new_layout values need to be replicated in the acquire barrier + // Release barriers ignore dst_access_mask unless using + // VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR + .src_access_mask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dst_access_mask = 0, // dst_access_mask is ignored for release barriers, without affecting its validity + .old_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // We want a layout transition, so the old_layout and new_layout values need to be + // replicated in the acquire barrier .new_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - .src_queue_family = queue_family_transfer ? - early_graphics_queue->get_family_index() : - VK_QUEUE_FAMILY_IGNORED, // Release barriers are executed from a queue of the source queue family + .src_queue_family = queue_family_transfer ? early_graphics_queue->get_family_index() : + VK_QUEUE_FAMILY_IGNORED, // Release barriers are executed from a queue of the source queue family .dst_queue_family = queue_family_transfer ? post_compute_queue->get_family_index() : VK_QUEUE_FAMILY_IGNORED, }; @@ -474,7 +458,8 @@ VkSemaphore AsyncComputeSample::render_swapchain(VkSemaphore post_semaphore) // The transfer ownership barriers are submitted twice (release and acquire) but they are only executed once. vkb::ImageMemoryBarrier memory_barrier{ .src_stage_mask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // Ignored for the acquire barrier. - // Acquire barriers ignore src_access_mask unless using VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR + // Acquire barriers ignore src_access_mask unless using + // VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR .dst_stage_mask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, .src_access_mask = 0, // src_access_mask is ignored for acquire barriers, without affecting its validity .dst_access_mask = VK_ACCESS_SHADER_READ_BIT, @@ -492,11 +477,13 @@ VkSemaphore AsyncComputeSample::render_swapchain(VkSemaphore post_semaphore) // The transfer ownership barriers are submitted twice (release and acquire) but they are only executed once. vkb::ImageMemoryBarrier memory_barrier_2{ .src_stage_mask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // Ignored for the acquire barrier. - // Acquire barriers ignore src_access_mask unless using VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR - .dst_stage_mask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, - .src_access_mask = 0, // src_access_mask is ignored for acquire barriers, without affecting its validity - .dst_access_mask = VK_ACCESS_SHADER_READ_BIT, - .old_layout = VK_IMAGE_LAYOUT_GENERAL, // We want a layout transition, so the old_layout and new_layout values need to be replicated in the acquire barrier + // Acquire barriers ignore src_access_mask unless using + // VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR + .dst_stage_mask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + .src_access_mask = 0, // src_access_mask is ignored for acquire barriers, without affecting its validity + .dst_access_mask = VK_ACCESS_SHADER_READ_BIT, + .old_layout = VK_IMAGE_LAYOUT_GENERAL, // We want a layout transition, so the old_layout and new_layout values need to be replicated in the + // acquire barrier .new_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, .src_queue_family = post_compute_queue->get_family_index(), .dst_queue_family = present_graphics_queue->get_family_index(), // Acquire barriers are executed from a queue of the destination queue family @@ -507,13 +494,13 @@ VkSemaphore AsyncComputeSample::render_swapchain(VkSemaphore post_semaphore) draw(*command_buffer, get_render_context().get_active_frame().get_render_target()); - // If maintenance9 is not enabled, resources with VK_SHARING_MODE_EXCLUSIVE must only be accessed by queues in the queue family that has ownership of the resource. - // Upon creation resources with VK_SHARING_MODE_EXCLUSIVE are not owned by any queue, ownership is implicitly acquired upon first use. - // The application must perform a queue family ownership transfer if it wishes to make the memory contents of the resource accessible to a different queue family. - // A queue family can take ownership of a resource without an ownership transfer, in the same way as for a resource that was just created, but the content will be undefined. - // We do not need to release blur_chain_views[1] and color_targets[0] from present_graphics - // A queue transfer barrier is not necessary for the resource first access. - // Moreover, in our sample we do not care about the content after presenting so we can skip the queue transfer barrier. + // If maintenance9 is not enabled, resources with VK_SHARING_MODE_EXCLUSIVE must only be accessed by queues in the queue family that has ownership of the + // resource. Upon creation resources with VK_SHARING_MODE_EXCLUSIVE are not owned by any queue, ownership is implicitly acquired upon first use. The + // application must perform a queue family ownership transfer if it wishes to make the memory contents of the resource accessible to a different queue + // family. A queue family can take ownership of a resource without an ownership transfer, in the same way as for a resource that was just created, but the + // content will be undefined. We do not need to release blur_chain_views[1] and color_targets[0] from present_graphics A queue transfer barrier is not + // necessary for the resource first access. Moreover, in our sample we do not care about the content after presenting so we can skip the queue transfer + // barrier. command_buffer->end(); @@ -573,11 +560,13 @@ VkSemaphore AsyncComputeSample::render_compute_post(VkSemaphore wait_graphics_se // The transfer ownership barriers are submitted twice (release and acquire) but they are only executed once. vkb::ImageMemoryBarrier memory_barrier{ .src_stage_mask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, // Ignored for the acquire barrier. - // Acquire barriers ignore src_access_mask unless using VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR - .dst_stage_mask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - .src_access_mask = 0, // src_access_mask is ignored for acquire barriers, without affecting its validity - .dst_access_mask = VK_ACCESS_SHADER_READ_BIT, - .old_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // We want a layout transition, so the old_layout and new_layout values need to be replicated in the release barrier + // Acquire barriers ignore src_access_mask unless using + // VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR + .dst_stage_mask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + .src_access_mask = 0, // src_access_mask is ignored for acquire barriers, without affecting its validity + .dst_access_mask = VK_ACCESS_SHADER_READ_BIT, + .old_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // We want a layout transition, so the old_layout and new_layout values need to be + // replicated in the release barrier .new_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, .src_queue_family = early_graphics_queue->get_family_index(), .dst_queue_family = post_compute_queue->get_family_index(), // Acquire barriers are executed from a queue of the destination queue family @@ -586,13 +575,13 @@ VkSemaphore AsyncComputeSample::render_compute_post(VkSemaphore wait_graphics_se } const auto discard_blur_view = [&](const vkb::core::ImageView &view) { - // If maintenance9 is not enabled, resources with VK_SHARING_MODE_EXCLUSIVE must only be accessed by queues in the queue family that has ownership of the resource. - // Upon creation resources with VK_SHARING_MODE_EXCLUSIVE are not owned by any queue, ownership is implicitly acquired upon first use. - // The application must perform a queue family ownership transfer if it wishes to make the memory contents of the resource accessible to a different queue family. - // A queue family can take ownership of a resource without an ownership transfer, in the same way as for a resource that was just created, but the content will be undefined. - // We do not need to acquire blur_chain_views[1] from present_graphics to post_compute - // A queue transfer barrier is not necessary for the resource first access. - // Moreover, in our sample we do not care about the content at this point so we can skip the queue transfer barrier. + // If maintenance9 is not enabled, resources with VK_SHARING_MODE_EXCLUSIVE must only be accessed by queues in the queue family that has ownership of + // the resource. Upon creation resources with VK_SHARING_MODE_EXCLUSIVE are not owned by any queue, ownership is implicitly acquired upon first use. The + // application must perform a queue family ownership transfer if it wishes to make the memory contents of the resource accessible to a different queue + // family. A queue family can take ownership of a resource without an ownership transfer, in the same way as for a resource that was just created, but + // the content will be undefined. We do not need to acquire blur_chain_views[1] from present_graphics to post_compute A queue transfer barrier is not + // necessary for the resource first access. Moreover, in our sample we do not care about the content at this point so we can skip the queue transfer + // barrier. vkb::ImageMemoryBarrier memory_barrier{}; memory_barrier.old_layout = VK_IMAGE_LAYOUT_UNDEFINED; @@ -614,14 +603,23 @@ VkSemaphore AsyncComputeSample::render_compute_post(VkSemaphore wait_graphics_se // The transfer ownership barriers are submitted twice (release and acquire) but they are only executed once. vkb::ImageMemoryBarrier memory_barrier{ .src_stage_mask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - .dst_stage_mask = is_final ? VkPipelineStageFlags(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT) : VkPipelineStageFlags(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT), // Ignored for the release barrier. - // Release barriers ignore dst_access_mask unless using VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR - .src_access_mask = VK_ACCESS_SHADER_WRITE_BIT, - .dst_access_mask = is_final ? VkAccessFlags(0) : VkAccessFlags(VK_ACCESS_SHADER_READ_BIT), // dst_access_mask is ignored for release barriers, without affecting its validity - .old_layout = VK_IMAGE_LAYOUT_GENERAL, // We want a layout transition, so the old_layout and new_layout values need to be replicated in the acquire barrier + .dst_stage_mask = + is_final ? + VkPipelineStageFlags(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT) : + VkPipelineStageFlags(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT), // Ignored for the release barrier. + // Release barriers ignore dst_access_mask unless using + // VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR + .src_access_mask = VK_ACCESS_SHADER_WRITE_BIT, + .dst_access_mask = + is_final ? VkAccessFlags(0) : + VkAccessFlags(VK_ACCESS_SHADER_READ_BIT), // dst_access_mask is ignored for release barriers, without affecting its validity + .old_layout = VK_IMAGE_LAYOUT_GENERAL, // We want a layout transition, so the old_layout and new_layout values need to be replicated in the + // acquire barrier .new_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, - .src_queue_family = queue_family_transfer ? post_compute_queue->get_family_index() : VK_QUEUE_FAMILY_IGNORED, // Release barriers are executed from a queue of the source queue family - .dst_queue_family = queue_family_transfer ? present_graphics_queue->get_family_index() : VK_QUEUE_FAMILY_IGNORED, // Release barriers are executed from a queue of the source queue family + .src_queue_family = queue_family_transfer ? post_compute_queue->get_family_index() : + VK_QUEUE_FAMILY_IGNORED, // Release barriers are executed from a queue of the source queue family + .dst_queue_family = queue_family_transfer ? present_graphics_queue->get_family_index() : + VK_QUEUE_FAMILY_IGNORED, // Release barriers are executed from a queue of the source queue family }; command_buffer->image_memory_barrier(view, memory_barrier); @@ -685,9 +683,10 @@ VkSemaphore AsyncComputeSample::render_compute_post(VkSemaphore wait_graphics_se vkb::ImageMemoryBarrier memory_barrier{ .src_stage_mask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, .dst_stage_mask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, // Ignored for the release barrier. - // Release barriers ignore dst_access_mask unless using VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR + // Release barriers ignore dst_access_mask unless using + // VK_DEPENDENCY_QUEUE_FAMILY_OWNERSHIP_TRANSFER_USE_ALL_STAGES_BIT_KHR .src_access_mask = VK_ACCESS_SHADER_READ_BIT, - .dst_access_mask = 0, // dst_access_mask is ignored for release barriers, without affecting its validity + .dst_access_mask = 0, // dst_access_mask is ignored for release barriers, without affecting its validity .old_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, // Purely ownership transfer. We do not need a layout transition. .new_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, .src_queue_family = post_compute_queue->get_family_index(), // Release barriers are executed from a queue of the source queue family @@ -747,7 +746,8 @@ void AsyncComputeSample::update(float delta_time) forward_subpass->set_shadow_map(&shadow_render_target->get_views()[0], comparison_sampler.get()); - composite_subpass->set_texture(&get_current_forward_render_target().get_views()[0], blur_chain_views[1].get(), linear_sampler.get()); // blur_chain[1] and color_targets[0] will be used by the present queue + composite_subpass->set_texture(&get_current_forward_render_target().get_views()[0], blur_chain_views[1].get(), + linear_sampler.get()); // blur_chain[1] and color_targets[0] will be used by the present queue elapsed_time += delta_time; float rotation_factor = elapsed_time; @@ -758,17 +758,15 @@ void AsyncComputeSample::update(float delta_time) if (rotate_shadows) { // Move shadows and directional light slightly. - orientation = glm::normalize( - glm::angleAxis(glm::pi(), glm::vec3(0.0f, -1.0f, 0.0f)) * - glm::angleAxis(-0.2f * glm::half_pi(), glm::vec3(1.0f, 0.0f, 0.0f)) * - glm::angleAxis(glm::two_pi() * glm::fract(rotation_factor * 0.05f), glm::vec3(0.0f, 0.0f, -1.0f)) * - glm::angleAxis(-0.05f * glm::half_pi(), glm::vec3(1.0f, 0.0f, 0.0f))); + orientation = glm::normalize(glm::angleAxis(glm::pi(), glm::vec3(0.0f, -1.0f, 0.0f)) * + glm::angleAxis(-0.2f * glm::half_pi(), glm::vec3(1.0f, 0.0f, 0.0f)) * + glm::angleAxis(glm::two_pi() * glm::fract(rotation_factor * 0.05f), glm::vec3(0.0f, 0.0f, -1.0f)) * + glm::angleAxis(-0.05f * glm::half_pi(), glm::vec3(1.0f, 0.0f, 0.0f))); } else { - orientation = glm::normalize( - glm::angleAxis(glm::pi(), glm::vec3(0.0f, -1.0f, 0.0f)) * - glm::angleAxis(-0.2f * glm::half_pi(), glm::vec3(1.0f, 0.0f, 0.0f))); + orientation = glm::normalize(glm::angleAxis(glm::pi(), glm::vec3(0.0f, -1.0f, 0.0f)) * + glm::angleAxis(-0.2f * glm::half_pi(), glm::vec3(1.0f, 0.0f, 0.0f))); } auto &shadow_camera_transform = shadow_camera->get_node()->get_component(); @@ -824,8 +822,10 @@ std::unique_ptr create_async_compute() } AsyncComputeSample::DepthMapSubpass::DepthMapSubpass(vkb::rendering::RenderContextC &render_context, - vkb::ShaderSource &&vertex_shader, vkb::ShaderSource &&fragment_shader, - vkb::sg::Scene &scene, vkb::sg::Camera &camera) : + vkb::ShaderSource &&vertex_shader, + vkb::ShaderSource &&fragment_shader, + vkb::sg::Scene &scene, + vkb::sg::Camera &camera) : vkb::rendering::subpasses::ForwardSubpassC(render_context, std::move(vertex_shader), std::move(fragment_shader), scene, camera) { // PCF, so need depth bias to avoid (most) shadow acne. @@ -842,12 +842,14 @@ void AsyncComputeSample::DepthMapSubpass::draw(vkb::core::CommandBufferC &comman } AsyncComputeSample::ShadowMapForwardSubpass::ShadowMapForwardSubpass(vkb::rendering::RenderContextC &render_context, - vkb::ShaderSource &&vertex_shader, vkb::ShaderSource &&fragment_shader, - vkb::sg::Scene &scene, vkb::sg::Camera &camera, vkb::sg::Camera &shadow_camera_) : + vkb::ShaderSource &&vertex_shader, + vkb::ShaderSource &&fragment_shader, + vkb::sg::Scene &scene, + vkb::sg::Camera &camera, + vkb::sg::Camera &shadow_camera_) : vkb::rendering::subpasses::ForwardSubpassC(render_context, std::move(vertex_shader), std::move(fragment_shader), scene, camera), shadow_camera(shadow_camera_) -{ -} +{} void AsyncComputeSample::ShadowMapForwardSubpass::set_shadow_map(const vkb::core::ImageView *view, const vkb::core::Sampler *sampler) { @@ -878,11 +880,11 @@ AsyncComputeSample::CompositeSubpass::CompositeSubpass(vkb::rendering::RenderCon vkb::ShaderSource &&vertex_shader, vkb::ShaderSource &&fragment_shader) : vkb::rendering::SubpassC(render_context, std::move(vertex_shader), std::move(fragment_shader)) -{ -} +{} -void AsyncComputeSample::CompositeSubpass::set_texture(const vkb::core::ImageView *hdr_view_, const vkb::core::ImageView *bloom_view_, - const vkb::core::Sampler *sampler_) +void AsyncComputeSample::CompositeSubpass::set_texture(const vkb::core::ImageView *hdr_view_, + const vkb::core::ImageView *bloom_view_, + const vkb::core::Sampler *sampler_) { hdr_view = hdr_view_; bloom_view = bloom_view_; diff --git a/samples/performance/async_compute/async_compute.h b/samples/performance/async_compute/async_compute.h index 5dd3b7fc46..4841d77182 100644 --- a/samples/performance/async_compute/async_compute.h +++ b/samples/performance/async_compute/async_compute.h @@ -110,8 +110,7 @@ class AsyncComputeSample : public vkb::VulkanSampleC struct CompositeSubpass : vkb::rendering::SubpassC { CompositeSubpass(vkb::rendering::RenderContextC &render_context, vkb::ShaderSource &&vertex_shader, vkb::ShaderSource &&fragment_shader); - void set_texture(const vkb::core::ImageView *hdr_view, const vkb::core::ImageView *bloom_view, - const vkb::core::Sampler *sampler); + void set_texture(const vkb::core::ImageView *hdr_view, const vkb::core::ImageView *bloom_view, const vkb::core::Sampler *sampler); virtual void draw(vkb::core::CommandBufferC &command_buffer) override; virtual void prepare() override; diff --git a/samples/performance/command_buffer_usage/command_buffer_usage.cpp b/samples/performance/command_buffer_usage/command_buffer_usage.cpp index 27b7cadd2b..f7219f637f 100644 --- a/samples/performance/command_buffer_usage/command_buffer_usage.cpp +++ b/samples/performance/command_buffer_usage/command_buffer_usage.cpp @@ -65,8 +65,7 @@ bool CommandBufferUsage::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = - std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); @@ -79,9 +78,7 @@ bool CommandBufferUsage::prepare(const vkb::ApplicationOptions &options) // Adjust the maximum number of secondary command buffers // In this sample, only the recording of opaque meshes will be multi-threaded - auto is_opaque = [](vkb::sg::SubMesh *sub_mesh) { - return sub_mesh->get_material()->alpha_mode != vkb::sg::AlphaMode::Blend; - }; + auto is_opaque = [](vkb::sg::SubMesh *sub_mesh) { return sub_mesh->get_material()->alpha_mode != vkb::sg::AlphaMode::Blend; }; auto count_opaque_submeshes = [is_opaque](uint32_t accumulated, const vkb::sg::Mesh *mesh) -> uint32_t { return accumulated + vkb::to_u32(mesh->get_nodes().size() * std::count_if(mesh->get_submeshes().begin(), mesh->get_submeshes().end(), is_opaque)); }; @@ -164,20 +161,17 @@ void CommandBufferUsage::draw_gui() ImGui::Text("(%d threads)", subpass->get_state().thread_count); // Buffer management options - ImGui::RadioButton( - "Allocate and free", &gui_command_buffer_reset_mode, static_cast(vkb::CommandBufferResetMode::AlwaysAllocate)); + ImGui::RadioButton("Allocate and free", &gui_command_buffer_reset_mode, static_cast(vkb::CommandBufferResetMode::AlwaysAllocate)); if (landscape) { ImGui::SameLine(); } - ImGui::RadioButton( - "Reset buffer", &gui_command_buffer_reset_mode, static_cast(vkb::CommandBufferResetMode::ResetIndividually)); + ImGui::RadioButton("Reset buffer", &gui_command_buffer_reset_mode, static_cast(vkb::CommandBufferResetMode::ResetIndividually)); if (landscape) { ImGui::SameLine(); } - ImGui::RadioButton( - "Reset pool", &gui_command_buffer_reset_mode, static_cast(vkb::CommandBufferResetMode::ResetPool)); + ImGui::RadioButton("Reset pool", &gui_command_buffer_reset_mode, static_cast(vkb::CommandBufferResetMode::ResetPool)); }, /* lines = */ lines); } @@ -190,8 +184,8 @@ void CommandBufferUsage::render(vkb::core::CommandBufferC &primary_command_buffe { // The user will set the number of secondary command buffers used for opaque meshes // There will be additional buffers for transparent meshes and for the GUI - get_render_pipeline().draw( - primary_command_buffer, get_render_context().get_active_frame().get_render_target(), VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); + get_render_pipeline().draw(primary_command_buffer, get_render_context().get_active_frame().get_render_target(), + VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); } else { @@ -232,7 +226,8 @@ void CommandBufferUsage::draw_renderpass(vkb::core::CommandBufferC &primary_comm .get_command_pool(queue, subpass->get_state().command_buffer_reset_mode) .request_command_buffer(VK_COMMAND_BUFFER_LEVEL_SECONDARY); - secondary_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, &primary_command_buffer); + secondary_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, + &primary_command_buffer); secondary_command_buffer->set_viewport(0, {viewport}); @@ -259,8 +254,7 @@ CommandBufferUsage::ForwardSubpassSecondary::ForwardSubpassSecondary(vkb::render vkb::sg::Scene &scene_, vkb::sg::Camera &camera) : vkb::rendering::subpasses::ForwardSubpassC{render_context, std::move(vertex_shader), std::move(fragment_shader), scene_, camera} -{ -} +{} void CommandBufferUsage::ForwardSubpassSecondary::record_draw(vkb::core::CommandBufferC &command_buffer, const std::vector> &nodes, @@ -284,12 +278,12 @@ void CommandBufferUsage::ForwardSubpassSecondary::record_draw(vkb::core::Command } std::shared_ptr - CommandBufferUsage::ForwardSubpassSecondary::record_draw_secondary(vkb::core::CommandBufferC &primary_command_buffer, + CommandBufferUsage::ForwardSubpassSecondary::record_draw_secondary(vkb::core::CommandBufferC &primary_command_buffer, const std::vector> &nodes, uint32_t mesh_start, uint32_t mesh_end, - uint32_t subpass_index, - size_t thread_index) + uint32_t subpass_index, + size_t thread_index) { const auto &queue = get_render_context().get_device().get_queue_by_flags(VK_QUEUE_GRAPHICS_BIT, 0); @@ -301,7 +295,8 @@ std::shared_ptr secondary_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, &primary_command_buffer); { - vkb::ScopedDebugLabel subpass_debug_label{*secondary_command_buffer, fmt::format("Record secondary command buffer, subpass #{}", subpass_index).c_str()}; + vkb::ScopedDebugLabel subpass_debug_label{*secondary_command_buffer, + fmt::format("Record secondary command buffer, subpass #{}", subpass_index).c_str()}; secondary_command_buffer->set_viewport(0, {viewport}); @@ -378,14 +373,9 @@ void CommandBufferUsage::ForwardSubpassSecondary::draw(vkb::core::CommandBufferC if (state.multi_threading) { - auto fut = thread_pool.push(std::bind(&CommandBufferUsage::ForwardSubpassSecondary::record_draw_secondary, - this, - std::ref(primary_command_buffer), - std::cref(sorted_opaque_nodes), - mesh_start, - mesh_end, - cb_count, - std::placeholders::_1)); + auto fut = + thread_pool.push(std::bind(&CommandBufferUsage::ForwardSubpassSecondary::record_draw_secondary, this, std::ref(primary_command_buffer), + std::cref(sorted_opaque_nodes), mesh_start, mesh_end, cb_count, std::placeholders::_1)); secondary_cmd_buf_futures.push_back(std::move(fut)); } diff --git a/samples/performance/command_buffer_usage/command_buffer_usage.h b/samples/performance/command_buffer_usage/command_buffer_usage.h index 1ba7875d62..c37c099866 100644 --- a/samples/performance/command_buffer_usage/command_buffer_usage.h +++ b/samples/performance/command_buffer_usage/command_buffer_usage.h @@ -29,8 +29,7 @@ class ThreadPool { public: - explicit ThreadPool() : - stop_flag(false) + explicit ThreadPool() : stop_flag(false) {} ~ThreadPool() @@ -41,9 +40,10 @@ class ThreadPool template auto push(F &&f, Args &&...args) -> std::future> { - using return_type = std::invoke_result_t; - auto task_ptr = std::make_shared>(std::bind(std::forward(f), std::forward(args)..., std::placeholders::_1)); - std::future res = task_ptr->get_future(); + using return_type = std::invoke_result_t; + auto task_ptr = + std::make_shared>(std::bind(std::forward(f), std::forward(args)..., std::placeholders::_1)); + std::future res = task_ptr->get_future(); { std::unique_lock lock(queue_mutex); tasks.emplace([task_ptr](size_t thread_index) { (*task_ptr)(thread_index); }); @@ -187,12 +187,12 @@ class CommandBufferUsage : public vkb::VulkanSampleC * @param thread_index Identifies the resources allocated for this thread * @return a pointer to the recorded secondary command buffer */ - std::shared_ptr record_draw_secondary(vkb::core::CommandBufferC &primary_command_buffer, + std::shared_ptr record_draw_secondary(vkb::core::CommandBufferC &primary_command_buffer, const std::vector> &nodes, - uint32_t mesh_start, - uint32_t mesh_end, - uint32_t subpass_index, - size_t thread_index = 0); + uint32_t mesh_start, + uint32_t mesh_end, + uint32_t subpass_index, + size_t thread_index = 0); VkViewport viewport{}; diff --git a/samples/performance/constant_data/constant_data.cpp b/samples/performance/constant_data/constant_data.cpp index 6c11df7500..5407d8d300 100644 --- a/samples/performance/constant_data/constant_data.cpp +++ b/samples/performance/constant_data/constant_data.cpp @@ -89,8 +89,7 @@ bool ConstantData::prepare(const vkb::ApplicationOptions &options) // If descriptor indexing and its dependencies were enabled, then we can mark the update after bind method as supported if (get_instance().is_extension_enabled(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) && - get_device().is_extension_enabled(VK_KHR_MAINTENANCE3_EXTENSION_NAME) && - get_device().is_extension_enabled(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME)) + get_device().is_extension_enabled(VK_KHR_MAINTENANCE3_EXTENSION_NAME) && get_device().is_extension_enabled(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME)) { methods[Method::UpdateAfterBindDescriptorSets].supported = true; } @@ -111,9 +110,12 @@ bool ConstantData::prepare(const vkb::ApplicationOptions &options) // Shader data passing depends on max. push constant size of the implementation auto push_constant_limit = get_device().get_gpu().get_properties().limits.maxPushConstantsSize; - push_constant_render_pipeline = create_render_pipeline(push_constant_limit >= 256 ? "constant_data/push_constant_large.vert.spv" : "constant_data/push_constant_small.vert.spv", "constant_data/push_constant.frag.spv"); - descriptor_set_render_pipeline = create_render_pipeline(push_constant_limit >= 256 ? "constant_data/ubo_large.vert.spv" : "constant_data/ubo_small.vert.spv", "constant_data/ubo.frag.spv"); - buffer_array_render_pipeline = create_render_pipeline("constant_data/buffer_array.vert.spv", "constant_data/buffer_array.frag.spv"); + push_constant_render_pipeline = create_render_pipeline(push_constant_limit >= 256 ? "constant_data/push_constant_large.vert.spv" : + "constant_data/push_constant_small.vert.spv", + "constant_data/push_constant.frag.spv"); + descriptor_set_render_pipeline = create_render_pipeline( + push_constant_limit >= 256 ? "constant_data/ubo_large.vert.spv" : "constant_data/ubo_small.vert.spv", "constant_data/ubo.frag.spv"); + buffer_array_render_pipeline = create_render_pipeline("constant_data/buffer_array.vert.spv", "constant_data/buffer_array.frag.spv"); // Add a GUI with the stats you want to monitor get_stats().request_stats(std::set{vkb::StatIndex::frame_times, vkb::StatIndex::gpu_load_store_cycles}); @@ -243,7 +245,8 @@ void ConstantData::draw_gui() } get_gui().show_options_window( - /* body = */ [this]() { + /* body = */ + [this]() { // Create a line for every config ImGui::Text("Method of pushing MVP to shader:"); @@ -302,9 +305,7 @@ void ConstantData::ConstantDataSubpass::prepare() } } -void ConstantData::PushConstantSubpass::update_uniform(vkb::core::CommandBufferC &command_buffer, - vkb::scene_graph::NodeC &node, - size_t thread_index) +void ConstantData::PushConstantSubpass::update_uniform(vkb::core::CommandBufferC &command_buffer, vkb::scene_graph::NodeC &node, size_t thread_index) { mvp_uniform = fill_mvp(node, get_camera()); } @@ -339,9 +340,7 @@ void ConstantData::PushConstantSubpass::prepare_push_constants(vkb::core::Comman } } -void ConstantData::DescriptorSetSubpass::update_uniform(vkb::core::CommandBufferC &command_buffer, - vkb::scene_graph::NodeC &node, - size_t thread_index) +void ConstantData::DescriptorSetSubpass::update_uniform(vkb::core::CommandBufferC &command_buffer, vkb::scene_graph::NodeC &node, size_t thread_index) { MVPUniform mvp; @@ -439,9 +438,7 @@ void ConstantData::BufferArraySubpass::draw(vkb::core::CommandBufferC &command_b GeometrySubpass::draw(command_buffer); } -void ConstantData::BufferArraySubpass::update_uniform(vkb::core::CommandBufferC &command_buffer, - vkb::scene_graph::NodeC &node, - size_t thread_index) +void ConstantData::BufferArraySubpass::update_uniform(vkb::core::CommandBufferC &command_buffer, vkb::scene_graph::NodeC &node, size_t thread_index) { /** * POI diff --git a/samples/performance/constant_data/constant_data.h b/samples/performance/constant_data/constant_data.h index 2bf3270492..f9e888ca9d 100644 --- a/samples/performance/constant_data/constant_data.h +++ b/samples/performance/constant_data/constant_data.h @@ -283,12 +283,11 @@ class ConstantData : public vkb::VulkanSampleC uint32_t max_push_constant_size{128}; // The samples constant data methods and their properties - std::unordered_map methods = { - {Method::PushConstants, {"Push Constants"}}, - {Method::DescriptorSets, {"Descriptor Sets"}}, - {Method::DynamicDescriptorSets, {"Dynamic Descriptor Sets"}}, - {Method::UpdateAfterBindDescriptorSets, {"Update-after-bind Descriptor Sets", false}}, - {Method::BufferArray, {"Single Pre-allocated Buffer Array"}}}; + std::unordered_map methods = {{Method::PushConstants, {"Push Constants"}}, + {Method::DescriptorSets, {"Descriptor Sets"}}, + {Method::DynamicDescriptorSets, {"Dynamic Descriptor Sets"}}, + {Method::UpdateAfterBindDescriptorSets, {"Update-after-bind Descriptor Sets", false}}, + {Method::BufferArray, {"Single Pre-allocated Buffer Array"}}}; int gui_method_value{static_cast(Method::PushConstants)}; diff --git a/samples/performance/descriptor_management/descriptor_management.cpp b/samples/performance/descriptor_management/descriptor_management.cpp index cab68f1c7f..5d350819e9 100644 --- a/samples/performance/descriptor_management/descriptor_management.cpp +++ b/samples/performance/descriptor_management/descriptor_management.cpp @@ -52,8 +52,9 @@ bool DescriptorManagement::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); - auto render_pipeline = std::make_unique(); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); + auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); set_render_pipeline(std::move(render_pipeline)); @@ -80,15 +81,13 @@ void DescriptorManagement::update(float delta_time) update_stats(delta_time); // Process GUI input - auto buffer_alloc_strategy = (buffer_allocation.value == 0) ? - vkb::rendering::BufferAllocationStrategy::OneAllocationPerBuffer : - vkb::rendering::BufferAllocationStrategy::MultipleAllocationsPerBuffer; + auto buffer_alloc_strategy = (buffer_allocation.value == 0) ? vkb::rendering::BufferAllocationStrategy::OneAllocationPerBuffer : + vkb::rendering::BufferAllocationStrategy::MultipleAllocationsPerBuffer; render_context.get_active_frame().set_buffer_allocation_strategy(buffer_alloc_strategy); - auto descriptor_management_strategy = (descriptor_caching.value == 0) ? - vkb::rendering::DescriptorManagementStrategy::CreateDirectly : - vkb::rendering::DescriptorManagementStrategy::StoreInCache; + auto descriptor_management_strategy = (descriptor_caching.value == 0) ? vkb::rendering::DescriptorManagementStrategy::CreateDirectly : + vkb::rendering::DescriptorManagementStrategy::StoreInCache; render_context.get_active_frame().set_descriptor_management_strategy(descriptor_management_strategy); @@ -113,7 +112,8 @@ void DescriptorManagement::draw_gui() } get_gui().show_options_window( - /* body = */ [this, lines]() { + /* body = */ + [this, lines]() { // For every option set for (size_t i = 0; i < radio_buttons.size(); ++i) { diff --git a/samples/performance/descriptor_management/descriptor_management.h b/samples/performance/descriptor_management/descriptor_management.h index bb7314575b..22051df4fd 100644 --- a/samples/performance/descriptor_management/descriptor_management.h +++ b/samples/performance/descriptor_management/descriptor_management.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2019-2024, Arm Limited and Contributors +/* Copyright (c) 2019-2026, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * @@ -44,15 +44,9 @@ class DescriptorManagement : public vkb::VulkanSampleC int value; }; - RadioButtonGroup descriptor_caching{ - "Descriptor set caching", - {"Disabled", "Enabled"}, - 0}; + RadioButtonGroup descriptor_caching{"Descriptor set caching", {"Disabled", "Enabled"}, 0}; - RadioButtonGroup buffer_allocation{ - "Single large VkBuffer", - {"Disabled", "Enabled"}, - 0}; + RadioButtonGroup buffer_allocation{"Single large VkBuffer", {"Disabled", "Enabled"}, 0}; std::vector radio_buttons = {&descriptor_caching, &buffer_allocation}; diff --git a/samples/performance/hpp_pipeline_cache/hpp_pipeline_cache.cpp b/samples/performance/hpp_pipeline_cache/hpp_pipeline_cache.cpp index 3392d8ff95..fc63e63991 100644 --- a/samples/performance/hpp_pipeline_cache/hpp_pipeline_cache.cpp +++ b/samples/performance/hpp_pipeline_cache/hpp_pipeline_cache.cpp @@ -103,8 +103,8 @@ bool HPPPipelineCache::prepare(const vkb::ApplicationOptions &options) vkb::core::HPPShaderSource vert_shader("base.vert.spv"); vkb::core::HPPShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique( - get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); @@ -117,7 +117,8 @@ bool HPPPipelineCache::prepare(const vkb::ApplicationOptions &options) void HPPPipelineCache::draw_gui() { get_gui().show_options_window( - /* body = */ [this]() { + /* body = */ + [this]() { if (ImGui::Checkbox("Pipeline cache", &enable_pipeline_cache)) { get_device().get_resource_cache().set_pipeline_cache(enable_pipeline_cache ? pipeline_cache : nullptr); diff --git a/samples/performance/hpp_swapchain_images/hpp_swapchain_images.cpp b/samples/performance/hpp_swapchain_images/hpp_swapchain_images.cpp index 50f4856d71..fe3d21efb7 100644 --- a/samples/performance/hpp_swapchain_images/hpp_swapchain_images.cpp +++ b/samples/performance/hpp_swapchain_images/hpp_swapchain_images.cpp @@ -41,8 +41,8 @@ bool HPPSwapchainImages::prepare(const vkb::ApplicationOptions &options) vkb::core::HPPShaderSource vert_shader("base.vert.spv"); vkb::core::HPPShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique( - get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); diff --git a/samples/performance/hpp_texture_compression_comparison/hpp_texture_compression_comparison.cpp b/samples/performance/hpp_texture_compression_comparison/hpp_texture_compression_comparison.cpp index 435e6dd5ef..0467c21d0a 100644 --- a/samples/performance/hpp_texture_compression_comparison/hpp_texture_compression_comparison.cpp +++ b/samples/performance/hpp_texture_compression_comparison/hpp_texture_compression_comparison.cpp @@ -82,39 +82,37 @@ HPPTextureCompressionComparison::HPPTextureCompressionComparison() {nullptr, "", vk::Format::eR8G8B8A8Srgb, KTX_TTF_RGBA32, "KTX_TTF_RGBA32", "RGBA 32", true}, {&vk::PhysicalDeviceFeatures::textureCompressionBC, "", vk::Format::eBc7SrgbBlock, KTX_TTF_BC7_RGBA, "KTX_TTF_BC7_RGBA", "BC7"}, {&vk::PhysicalDeviceFeatures::textureCompressionBC, "", vk::Format::eBc3SrgbBlock, KTX_TTF_BC3_RGBA, "KTX_TTF_BC3_RGBA", "BC3"}, - {&vk::PhysicalDeviceFeatures::textureCompressionASTC_LDR, "", vk::Format::eAstc4x4SrgbBlock, KTX_TTF_ASTC_4x4_RGBA, "KTX_TTF_ASTC_4x4_RGBA", "ASTC 4x4"}, + {&vk::PhysicalDeviceFeatures::textureCompressionASTC_LDR, "", vk::Format::eAstc4x4SrgbBlock, KTX_TTF_ASTC_4x4_RGBA, "KTX_TTF_ASTC_4x4_RGBA", + "ASTC 4x4"}, {&vk::PhysicalDeviceFeatures::textureCompressionETC2, "", vk::Format::eEtc2R8G8B8A8SrgbBlock, KTX_TTF_ETC2_RGBA, "KTX_TTF_ETC2_RGBA", "ETC2"}}; } void HPPTextureCompressionComparison::draw_gui() { - get_gui().show_options_window( - [this]() { - if (ImGui::Combo( - "Compressed Format", - ¤t_gui_format, - [](void *user_data, int idx) -> char const * { return reinterpret_cast(user_data)[idx].gui_name.c_str(); }, - texture_compression_data.data(), - static_cast(texture_compression_data.size()))) - { - require_redraw = true; - if (texture_compression_data[current_gui_format].is_supported) - { - current_format = current_gui_format; - } - } - const auto ¤t_gui_tc = texture_compression_data[current_gui_format]; - if (current_gui_tc.is_supported) - { - ImGui::Text("Format name: %s", current_gui_tc.format_name.c_str()); - ImGui::Text("Bytes: %f MB", static_cast(current_benchmark.total_bytes) / 1024.f / 1024.f); - ImGui::Text("Compression Time: %f (ms)", current_benchmark.compress_time_ms); - } - else - { - ImGui::Text("%s not supported on this GPU.", current_gui_tc.short_name.c_str()); - } - }); + get_gui().show_options_window([this]() { + if (ImGui::Combo( + "Compressed Format", ¤t_gui_format, + [](void *user_data, int idx) -> char const * { return reinterpret_cast(user_data)[idx].gui_name.c_str(); }, + texture_compression_data.data(), static_cast(texture_compression_data.size()))) + { + require_redraw = true; + if (texture_compression_data[current_gui_format].is_supported) + { + current_format = current_gui_format; + } + } + const auto ¤t_gui_tc = texture_compression_data[current_gui_format]; + if (current_gui_tc.is_supported) + { + ImGui::Text("Format name: %s", current_gui_tc.format_name.c_str()); + ImGui::Text("Bytes: %f MB", static_cast(current_benchmark.total_bytes) / 1024.f / 1024.f); + ImGui::Text("Compression Time: %f (ms)", current_benchmark.compress_time_ms); + } + else + { + ImGui::Text("%s not supported on this GPU.", current_gui_tc.short_name.c_str()); + } + }); } bool HPPTextureCompressionComparison::prepare(const vkb::ApplicationOptions &options) @@ -220,8 +218,8 @@ std::unique_ptr HPPTextureCompressionCom command_buffer.copyBufferToImage(staging_buffer->get_handle(), image, vk::ImageLayout::eTransferDstOptimal, buffer_copies); - vkb::common::image_layout_transition( - command_buffer, image, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, subresource_range); + vkb::common::image_layout_transition(command_buffer, image, vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal, + subresource_range); get_device().flush_command_buffer(command_buffer, get_device().get_queue_by_flags(vk::QueueFlagBits::eGraphics, 0).get_handle(), true); @@ -232,8 +230,8 @@ void HPPTextureCompressionComparison::create_subpass() { vkb::core::HPPShaderSource vert_shader("base.vert.spv"); vkb::core::HPPShaderSource frag_shader("base.frag.spv"); - auto scene_sub_pass = std::make_unique( - get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_sub_pass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_sub_pass)); diff --git a/samples/performance/hpp_texture_compression_comparison/hpp_texture_compression_comparison.h b/samples/performance/hpp_texture_compression_comparison/hpp_texture_compression_comparison.h index d996df0732..16bc664071 100644 --- a/samples/performance/hpp_texture_compression_comparison/hpp_texture_compression_comparison.h +++ b/samples/performance/hpp_texture_compression_comparison/hpp_texture_compression_comparison.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2024, Holochip +/* Copyright (c) 2021-2026, Holochip * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 @@ -68,14 +68,14 @@ class HPPTextureCompressionComparison : public vkb::VulkanSample, HPPTextureBenchmark> compress( - const std::string &filename, HPPTextureCompressionData texture_format, const std::string &name); + std::pair, HPPTextureBenchmark> + compress(const std::string &filename, HPPTextureCompressionData texture_format, const std::string &name); std::unique_ptr create_image(ktxTexture2 *ktx_texture, const std::string &name); void create_subpass(); - bool is_texture_format_supported(const HPPTextureCompressionData &tcd, vk::PhysicalDeviceFeatures const &device_features); - void load_assets(); - void prepare_gui(); - HPPTextureBenchmark update_textures(const HPPTextureCompressionData &new_format); + bool is_texture_format_supported(const HPPTextureCompressionData &tcd, vk::PhysicalDeviceFeatures const &device_features); + void load_assets(); + void prepare_gui(); + HPPTextureBenchmark update_textures(const HPPTextureCompressionData &new_format); private: vkb::sg::Camera *camera = nullptr; diff --git a/samples/performance/image_compression_control/image_compression_control.cpp b/samples/performance/image_compression_control/image_compression_control.cpp index 0bfcae08ca..2775c208cd 100644 --- a/samples/performance/image_compression_control/image_compression_control.cpp +++ b/samples/performance/image_compression_control/image_compression_control.cpp @@ -72,7 +72,8 @@ bool ImageCompressionControlSample::prepare(const vkb::ApplicationOptions &optio vkb::ShaderSource scene_vs("base.vert.spv"); vkb::ShaderSource scene_fs("base.frag.spv"); - auto scene_subpass = std::make_unique(get_render_context(), std::move(scene_vs), std::move(scene_fs), get_scene(), *camera); + auto scene_subpass = + std::make_unique(get_render_context(), std::move(scene_vs), std::move(scene_fs), get_scene(), *camera); scene_subpass->set_output_attachments({static_cast(Attachments::Color)}); // Forward rendering pass @@ -89,8 +90,7 @@ bool ImageCompressionControlSample::prepare(const vkb::ApplicationOptions &optio // Trigger recreation of Swapchain and render targets, with initial compression parameters update_render_targets(); - get_stats().request_stats({vkb::StatIndex::frame_times, - vkb::StatIndex::gpu_ext_write_bytes}); + get_stats().request_stats({vkb::StatIndex::frame_times, vkb::StatIndex::gpu_ext_write_bytes}); create_gui(*window, &get_stats()); @@ -133,8 +133,7 @@ void ImageCompressionControlSample::create_render_context() VkSurfaceFormatKHR surface_format = {surface_compression_properties.surface_format.surfaceFormat.format, surface_compression_properties.surface_format.surfaceFormat.colorSpace}; - LOGI(" \t{}:\t{}", - vkb::to_string(surface_format), + LOGI(" \t{}:\t{}", vkb::to_string(surface_format), vkb::image_compression_fixed_rate_flags_to_string(surface_compression_properties.compression_properties.imageCompressionFixedRateFlags)); surface_formats_that_support_compression.push_back(surface_format); @@ -154,9 +153,9 @@ void ImageCompressionControlSample::create_render_context() std::vector new_surface_priority_list; for (auto const &surface_priority : get_surface_priority_list()) { - auto it = std::ranges::find_if(surface_formats_that_support_compression, - [&](VkSurfaceFormatKHR &sf) { return surface_priority.format == sf.format && - surface_priority.colorSpace == sf.colorSpace; }); + auto it = std::ranges::find_if(surface_formats_that_support_compression, [&](VkSurfaceFormatKHR &sf) { + return surface_priority.format == sf.format && surface_priority.colorSpace == sf.colorSpace; + }); if (it != surface_formats_that_support_compression.end()) { new_surface_priority_list.push_back(*it); @@ -184,8 +183,8 @@ void ImageCompressionControlSample::create_render_context() if (selected_surface_format.format == surface_compression_properties_list[i].surface_format.surfaceFormat.format && selected_surface_format.colorSpace == surface_compression_properties_list[i].surface_format.surfaceFormat.colorSpace) { - supported_fixed_rate_flags_swapchain = vkb::fixed_rate_compression_flags_to_vector( - surface_compression_properties_list[i].compression_properties.imageCompressionFixedRateFlags); + supported_fixed_rate_flags_swapchain = + vkb::fixed_rate_compression_flags_to_vector(surface_compression_properties_list[i].compression_properties.imageCompressionFixedRateFlags); break; } } @@ -212,10 +211,9 @@ std::unique_ptr ImageCompressionControlSample::cr if (VK_FORMAT_UNDEFINED == color_image_info.format) { // Query fixed-rate compression support for a few candidate formats - std::vector format_list{VK_FORMAT_R8G8B8_UNORM, VK_FORMAT_R8G8B8_SNORM, VK_FORMAT_R8G8B8_SRGB, - VK_FORMAT_B8G8R8_UNORM, VK_FORMAT_B8G8R8_SNORM, VK_FORMAT_B8G8R8_SRGB, - VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SNORM, VK_FORMAT_R8G8B8A8_SRGB, - VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_SNORM, VK_FORMAT_B8G8R8A8_SRGB}; + std::vector format_list{VK_FORMAT_R8G8B8_UNORM, VK_FORMAT_R8G8B8_SNORM, VK_FORMAT_R8G8B8_SRGB, VK_FORMAT_B8G8R8_UNORM, + VK_FORMAT_B8G8R8_SNORM, VK_FORMAT_B8G8R8_SRGB, VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_SNORM, + VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_SNORM, VK_FORMAT_B8G8R8A8_SRGB}; VkFormat chosen_format{VK_FORMAT_UNDEFINED}; if (get_device().is_extension_enabled(VK_EXT_IMAGE_COMPRESSION_CONTROL_EXTENSION_NAME)) @@ -230,23 +228,20 @@ std::unique_ptr ImageCompressionControlSample::cr * calling vkGetPhysicalDeviceImageFormatProperties2KHR. * See the implementation of this helper function in vkb::core::Image. */ - VkImageCompressionPropertiesEXT supported_compression_properties = vkb::query_supported_fixed_rate_compression(get_device().get_gpu().get_handle(), color_image_info); + VkImageCompressionPropertiesEXT supported_compression_properties = + vkb::query_supported_fixed_rate_compression(get_device().get_gpu().get_handle(), color_image_info); auto fixed_rate_flags = vkb::fixed_rate_compression_flags_to_vector(supported_compression_properties.imageCompressionFixedRateFlags); VkImageFormatProperties format_properties; - auto result = vkGetPhysicalDeviceImageFormatProperties(get_device().get_gpu().get_handle(), - color_image_info.format, - color_image_info.imageType, - color_image_info.tiling, - color_image_info.usage, - 0, // no create flags - &format_properties); + auto result = vkGetPhysicalDeviceImageFormatProperties(get_device().get_gpu().get_handle(), color_image_info.format, color_image_info.imageType, + color_image_info.tiling, color_image_info.usage, + 0, // no create flags + &format_properties); // Pick the first format that supports at least 2 or more levels of fixed-rate compression, otherwise // pick the first format that supports at least 1 level - if (result != VK_ERROR_FORMAT_NOT_SUPPORTED && - fixed_rate_flags.size() > 0) + if (result != VK_ERROR_FORMAT_NOT_SUPPORTED && fixed_rate_flags.size() > 0) { if ((VK_FORMAT_UNDEFINED == chosen_format) || (fixed_rate_flags.size() > 1)) { @@ -284,11 +279,10 @@ std::unique_ptr ImageCompressionControlSample::cr } } - vkb::core::Image depth_image{get_device(), - vkb::core::ImageBuilder(color_image_info.extent) - .with_format(vkb::get_suitable_depth_format(get_device().get_gpu().get_handle())) - .with_usage(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) - .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY)}; + vkb::core::Image depth_image{get_device(), vkb::core::ImageBuilder(color_image_info.extent) + .with_format(vkb::get_suitable_depth_format(get_device().get_gpu().get_handle())) + .with_usage(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) + .with_vma_usage(VMA_MEMORY_USAGE_GPU_ONLY)}; vkb::core::ImageBuilder color_image_builder(color_image_info.extent); color_image_builder.with_format(color_image_info.format) @@ -303,8 +297,7 @@ std::unique_ptr ImageCompressionControlSample::cr { color_compression_control.flags = compression_flag; - if (VK_IMAGE_COMPRESSION_FIXED_RATE_EXPLICIT_EXT == compression_flag && - VK_IMAGE_COMPRESSION_FIXED_RATE_NONE_EXT != compression_fixed_rate_flag_color) + if (VK_IMAGE_COMPRESSION_FIXED_RATE_EXPLICIT_EXT == compression_flag && VK_IMAGE_COMPRESSION_FIXED_RATE_NONE_EXT != compression_fixed_rate_flag_color) { color_compression_control.compressionControlPlaneCount = 1; color_compression_control.pFixedRateFlags = &compression_fixed_rate_flag_color; @@ -355,8 +348,7 @@ void ImageCompressionControlSample::update(float delta_time) { elapsed_time += delta_time; - if ((gui_target_compression != last_gui_target_compression) || - (gui_fixed_rate_compression_level != last_gui_fixed_rate_compression_level)) + if ((gui_target_compression != last_gui_target_compression) || (gui_fixed_rate_compression_level != last_gui_fixed_rate_compression_level)) { update_render_targets(); @@ -410,9 +402,9 @@ void ImageCompressionControlSample::update_render_targets() get_render_context().update_swapchain(compression_flag, compression_fixed_rate_flag_swapchain); } -VkImageCompressionFixedRateFlagBitsEXT ImageCompressionControlSample::select_fixed_rate_compression_flag( - std::vector &supported_fixed_rate_flags, - FixedRateCompressionLevel compression_level) +VkImageCompressionFixedRateFlagBitsEXT + ImageCompressionControlSample::select_fixed_rate_compression_flag(std::vector &supported_fixed_rate_flags, + FixedRateCompressionLevel compression_level) { if (!supported_fixed_rate_flags.empty()) { @@ -468,7 +460,11 @@ namespace * @brief Helper function to generate a GUI drop-down options menu */ template -inline T generate_combo(T current_value, const char *combo_label, const std::unordered_map &enum_to_string, float item_width, const std::set *skip_values = nullptr) +inline T generate_combo(T current_value, + const char *combo_label, + const std::unordered_map &enum_to_string, + float item_width, + const std::set *skip_values = nullptr) { ImGui::PushItemWidth(item_width); @@ -526,10 +522,10 @@ void ImageCompressionControlSample::draw_gui() ImGui::Text("Compression:"); ImGui::SameLine(); - const TargetCompression compression = generate_combo(gui_target_compression, "##compression", - {{TargetCompression::FixedRate, "Fixed-rate"}, {TargetCompression::None, "None"}, {TargetCompression::Default, "Default"}}, - window_width * 0.2f, - &gui_skip_compression_values); + const TargetCompression compression = + generate_combo(gui_target_compression, "##compression", + {{TargetCompression::FixedRate, "Fixed-rate"}, {TargetCompression::None, "None"}, {TargetCompression::Default, "Default"}}, + window_width * 0.2f, &gui_skip_compression_values); gui_target_compression = compression; @@ -544,9 +540,9 @@ void ImageCompressionControlSample::draw_gui() ImGui::Text("Level:"); ImGui::SameLine(); - const FixedRateCompressionLevel compression_level = generate_combo(gui_fixed_rate_compression_level, "##compression-level", - {{FixedRateCompressionLevel::High, "High"}, {FixedRateCompressionLevel::Low, "Low"}}, - window_width * 0.2f); + const FixedRateCompressionLevel compression_level = + generate_combo(gui_fixed_rate_compression_level, "##compression-level", + {{FixedRateCompressionLevel::High, "High"}, {FixedRateCompressionLevel::Low, "Low"}}, window_width * 0.2f); gui_fixed_rate_compression_level = compression_level; } diff --git a/samples/performance/layout_transitions/layout_transitions.cpp b/samples/performance/layout_transitions/layout_transitions.cpp index 1f508b3378..43132a90f1 100644 --- a/samples/performance/layout_transitions/layout_transitions.cpp +++ b/samples/performance/layout_transitions/layout_transitions.cpp @@ -68,8 +68,7 @@ bool LayoutTransitions::prepare(const vkb::ApplicationOptions &options) lighting_pipeline.add_subpass(std::move(lighting_subpass)); lighting_pipeline.set_load_store(vkb::gbuffer::get_load_all_store_swapchain()); - get_stats().request_stats({vkb::StatIndex::gpu_killed_tiles, - vkb::StatIndex::gpu_ext_write_bytes}); + get_stats().request_stats({vkb::StatIndex::gpu_killed_tiles, vkb::StatIndex::gpu_ext_write_bytes}); create_gui(*window, &get_stats()); @@ -104,22 +103,13 @@ std::unique_ptr LayoutTransitions::create_render_ auto &device = swapchain_image.get_device(); auto &extent = swapchain_image.get_extent(); - vkb::core::Image depth_image{device, - extent, - vkb::get_suitable_depth_format(swapchain_image.get_device().get_gpu().get_handle()), - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, - VMA_MEMORY_USAGE_GPU_ONLY}; + vkb::core::Image depth_image{device, extent, vkb::get_suitable_depth_format(swapchain_image.get_device().get_gpu().get_handle()), + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; - vkb::core::Image albedo_image{device, - extent, - VK_FORMAT_R8G8B8A8_UNORM, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, + vkb::core::Image albedo_image{device, extent, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; - vkb::core::Image normal_image{device, - extent, - VK_FORMAT_A2B10G10R10_UNORM_PACK32, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, + vkb::core::Image normal_image{device, extent, VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; std::vector images; @@ -141,9 +131,7 @@ std::unique_ptr LayoutTransitions::create_render_ VkImageLayout LayoutTransitions::pick_old_layout(VkImageLayout last_layout) { - return (layout_transition_type == LayoutTransitionType::UNDEFINED) ? - VK_IMAGE_LAYOUT_UNDEFINED : - last_layout; + return (layout_transition_type == LayoutTransitionType::UNDEFINED) ? VK_IMAGE_LAYOUT_UNDEFINED : last_layout; } void LayoutTransitions::draw(vkb::core::CommandBufferC &command_buffer, vkb::rendering::RenderTargetC &render_target) @@ -263,7 +251,8 @@ void LayoutTransitions::draw(vkb::core::CommandBufferC &command_buffer, vkb::ren void LayoutTransitions::draw_gui() { get_gui().show_options_window( - /* body = */ [this]() { + /* body = */ + [this]() { ImGui::Text("Transition images from:"); ImGui::RadioButton("Undefined layout", reinterpret_cast(&layout_transition_type), LayoutTransitionType::UNDEFINED); ImGui::SameLine(); diff --git a/samples/performance/msaa/msaa.cpp b/samples/performance/msaa/msaa.cpp index 78ce41c80f..aee0c56070 100644 --- a/samples/performance/msaa/msaa.cpp +++ b/samples/performance/msaa/msaa.cpp @@ -112,23 +112,21 @@ bool MSAASample::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource scene_vs{"base.vert.spv"}; vkb::ShaderSource scene_fs{"base.frag.spv"}; - auto scene_subpass = std::make_unique(get_render_context(), std::move(scene_vs), std::move(scene_fs), get_scene(), *camera); - scene_pipeline = std::make_unique(); + auto scene_subpass = + std::make_unique(get_render_context(), std::move(scene_vs), std::move(scene_fs), get_scene(), *camera); + scene_pipeline = std::make_unique(); scene_pipeline->add_subpass(std::move(scene_subpass)); postprocessing_pipeline = std::make_unique(get_render_context(), vkb::ShaderSource{"postprocessing/postprocessing.vert.spv"}); - postprocessing_pipeline->add_pass() - .add_subpass(vkb::ShaderSource{"postprocessing/outline.frag.spv"}); + postprocessing_pipeline->add_pass().add_subpass(vkb::ShaderSource{"postprocessing/outline.frag.spv"}); - ms_depth_postprocessing_pipeline = std::make_unique(get_render_context(), vkb::ShaderSource{"postprocessing/postprocessing.vert.spv"}); - ms_depth_postprocessing_pipeline->add_pass() - .add_subpass(vkb::ShaderSource{"postprocessing/outline_ms_depth.frag.spv"}); + ms_depth_postprocessing_pipeline = + std::make_unique(get_render_context(), vkb::ShaderSource{"postprocessing/postprocessing.vert.spv"}); + ms_depth_postprocessing_pipeline->add_pass().add_subpass(vkb::ShaderSource{"postprocessing/outline_ms_depth.frag.spv"}); update_pipelines(); - get_stats().request_stats({vkb::StatIndex::frame_times, - vkb::StatIndex::gpu_ext_read_bytes, - vkb::StatIndex::gpu_ext_write_bytes}); + get_stats().request_stats({vkb::StatIndex::frame_times, vkb::StatIndex::gpu_ext_read_bytes, vkb::StatIndex::gpu_ext_write_bytes}); create_gui(*window, &get_stats()); @@ -172,19 +170,9 @@ std::unique_ptr MSAASample::create_render_target( depth_resolve_usage |= VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; } - vkb::core::Image depth_image{device, - extent, - depth_format, - depth_usage, - VMA_MEMORY_USAGE_GPU_ONLY, - sample_count}; + vkb::core::Image depth_image{device, extent, depth_format, depth_usage, VMA_MEMORY_USAGE_GPU_ONLY, sample_count}; - vkb::core::Image depth_resolve_image{device, - extent, - depth_format, - depth_resolve_usage, - VMA_MEMORY_USAGE_GPU_ONLY, - VK_SAMPLE_COUNT_1_BIT}; + vkb::core::Image depth_resolve_image{device, extent, depth_format, depth_resolve_usage, VMA_MEMORY_USAGE_GPU_ONLY, VK_SAMPLE_COUNT_1_BIT}; VkImageUsageFlags color_ms_usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if (ColorResolve::OnWriteback == color_resolve_method) @@ -200,12 +188,7 @@ std::unique_ptr MSAASample::create_render_target( color_ms_usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; } - vkb::core::Image color_ms_image{device, - extent, - swapchain_image.get_format(), - color_ms_usage, - VMA_MEMORY_USAGE_GPU_ONLY, - sample_count}; + vkb::core::Image color_ms_image{device, extent, swapchain_image.get_format(), color_ms_usage, VMA_MEMORY_USAGE_GPU_ONLY, sample_count}; VkImageUsageFlags color_resolve_usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if (run_postprocessing) @@ -222,12 +205,7 @@ std::unique_ptr MSAASample::create_render_target( color_resolve_usage |= VK_IMAGE_USAGE_SAMPLED_BIT; } - vkb::core::Image color_resolve_image{device, - extent, - swapchain_image.get_format(), - color_resolve_usage, - VMA_MEMORY_USAGE_GPU_ONLY, - VK_SAMPLE_COUNT_1_BIT}; + vkb::core::Image color_resolve_image{device, extent, swapchain_image.get_format(), color_resolve_usage, VMA_MEMORY_USAGE_GPU_ONLY, VK_SAMPLE_COUNT_1_BIT}; scene_load_store.clear(); std::vector images; @@ -272,10 +250,8 @@ std::unique_ptr MSAASample::create_render_target( void MSAASample::update(float delta_time) { - if ((gui_run_postprocessing != last_gui_run_postprocessing) || - (gui_sample_count != last_gui_sample_count) || - (gui_color_resolve_method != last_gui_color_resolve_method) || - (gui_resolve_depth_on_writeback != last_gui_resolve_depth_on_writeback) || + if ((gui_run_postprocessing != last_gui_run_postprocessing) || (gui_sample_count != last_gui_sample_count) || + (gui_color_resolve_method != last_gui_color_resolve_method) || (gui_resolve_depth_on_writeback != last_gui_resolve_depth_on_writeback) || (gui_depth_resolve_mode != last_gui_depth_resolve_mode)) { run_postprocessing = gui_run_postprocessing; @@ -432,8 +408,7 @@ void MSAASample::use_singlesampled_color(std::unique_ptrset_color_resolve_attachments({}); } -void MSAASample::store_multisampled_depth(std::unique_ptr &subpass, - std::vector &load_store) +void MSAASample::store_multisampled_depth(std::unique_ptr &subpass, std::vector &load_store) { if (depth_writeback_resolve_supported && resolve_depth_on_writeback) { @@ -462,8 +437,7 @@ void MSAASample::store_multisampled_depth(std::unique_ptr &subpass, - std::vector &load_store) +void MSAASample::disable_depth_writeback_resolve(std::unique_ptr &subpass, std::vector &load_store) { // Auxiliary single-sampled depth attachment is not used load_store[i_depth_resolve].store_op = VK_ATTACHMENT_STORE_OP_DONT_CARE; @@ -708,9 +682,8 @@ void MSAASample::prepare_supported_sample_count_list() // All possible sample counts are listed here from most to least preferred as default // On Mali GPUs 4X MSAA is recommended as best performance/quality trade-off - std::vector counts = {VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_2_BIT, VK_SAMPLE_COUNT_8_BIT, - VK_SAMPLE_COUNT_16_BIT, VK_SAMPLE_COUNT_32_BIT, VK_SAMPLE_COUNT_64_BIT, - VK_SAMPLE_COUNT_1_BIT}; + std::vector counts = {VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_2_BIT, VK_SAMPLE_COUNT_8_BIT, VK_SAMPLE_COUNT_16_BIT, + VK_SAMPLE_COUNT_32_BIT, VK_SAMPLE_COUNT_64_BIT, VK_SAMPLE_COUNT_1_BIT}; for (auto &count : counts) { @@ -748,8 +721,8 @@ void MSAASample::prepare_depth_resolve_mode_list() else { // All possible modes are listed here from most to least preferred as default - std::vector modes = {VK_RESOLVE_MODE_SAMPLE_ZERO_BIT, VK_RESOLVE_MODE_MIN_BIT, - VK_RESOLVE_MODE_MAX_BIT, VK_RESOLVE_MODE_AVERAGE_BIT}; + std::vector modes = {VK_RESOLVE_MODE_SAMPLE_ZERO_BIT, VK_RESOLVE_MODE_MIN_BIT, VK_RESOLVE_MODE_MAX_BIT, + VK_RESOLVE_MODE_AVERAGE_BIT}; for (auto &mode : modes) { diff --git a/samples/performance/msaa/msaa.h b/samples/performance/msaa/msaa.h index 4ad4ea19d8..345a00212b 100644 --- a/samples/performance/msaa/msaa.h +++ b/samples/performance/msaa/msaa.h @@ -133,7 +133,10 @@ class MSAASample : public vkb::VulkanSampleC * and depth attachments and uses them to apply a screen-based effect * It also draws the GUI */ - void postprocessing(vkb::core::CommandBufferC &command_buffer, vkb::rendering::RenderTargetC &render_target, VkImageLayout &swapchain_layout, bool msaa_enabled); + void postprocessing(vkb::core::CommandBufferC &command_buffer, + vkb::rendering::RenderTargetC &render_target, + VkImageLayout &swapchain_layout, + bool msaa_enabled); /** * @brief Enables MSAA if set to more than 1 sample per pixel @@ -172,18 +175,14 @@ class MSAASample : public vkb::VulkanSampleC * renderpass since it only renders a texture on single full-screen * triangle and MSAA only works on primitive edges */ - void use_multisampled_color(std::unique_ptr &subpass, - std::vector &load_store, - uint32_t resolve_attachment); + void use_multisampled_color(std::unique_ptr &subpass, std::vector &load_store, uint32_t resolve_attachment); /** * @brief Sets the single-sampled output_attachment as the output attachment, * disables color resolve and updates the load/store operations of * color attachments */ - void use_singlesampled_color(std::unique_ptr &subpass, - std::vector &load_store, - uint32_t output_attachment); + void use_singlesampled_color(std::unique_ptr &subpass, std::vector &load_store, uint32_t output_attachment); /** * @brief Submits a transfer operation to resolve the multisampled color attachment diff --git a/samples/performance/multi_draw_indirect/multi_draw_indirect.cpp b/samples/performance/multi_draw_indirect/multi_draw_indirect.cpp index e23f79cd8a..d2f12ba00b 100644 --- a/samples/performance/multi_draw_indirect/multi_draw_indirect.cpp +++ b/samples/performance/multi_draw_indirect/multi_draw_indirect.cpp @@ -112,8 +112,7 @@ void MultiDrawIndirect::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) } // Query whether the device supports buffer device addresses - m_supports_buffer_device = - REQUEST_OPTIONAL_FEATURE(gpu, VkPhysicalDeviceVulkan12Features, bufferDeviceAddress); + m_supports_buffer_device = REQUEST_OPTIONAL_FEATURE(gpu, VkPhysicalDeviceVulkan12Features, bufferDeviceAddress); // This sample references 128 objects. We need to check whether this is supported by the device VkPhysicalDeviceProperties physical_device_properties; @@ -121,7 +120,8 @@ void MultiDrawIndirect::request_gpu_features(vkb::core::PhysicalDeviceC &gpu) if (physical_device_properties.limits.maxPerStageDescriptorSamplers < 128) { - throw std::runtime_error(fmt::format(FMT_STRING("This sample requires at least 128 descriptor samplers, but device only supports {:d}"), physical_device_properties.limits.maxPerStageDescriptorSamplers)); + throw std::runtime_error(fmt::format(FMT_STRING("This sample requires at least 128 descriptor samplers, but device only supports {:d}"), + physical_device_properties.limits.maxPerStageDescriptorSamplers)); } } @@ -166,7 +166,8 @@ void MultiDrawIndirect::build_command_buffers() if (m_enable_mdi && m_supports_mdi) { - vkCmdDrawIndexedIndirect(draw_cmd_buffers[i], indirect_call_buffer->get_handle(), 0, static_cast(cpu_commands.size()), sizeof(cpu_commands[0])); + vkCmdDrawIndexedIndirect(draw_cmd_buffers[i], indirect_call_buffer->get_handle(), 0, static_cast(cpu_commands.size()), + sizeof(cpu_commands[0])); } else { @@ -317,16 +318,9 @@ void MultiDrawIndirect::load_scene() Texture texture; texture.n_mip_maps = static_cast(image->get_mipmaps().size()); assert(texture.n_mip_maps == 1); - texture.image = std::make_unique(get_device(), - image->get_extent(), - image->get_format(), - VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, - VMA_MEMORY_USAGE_GPU_ONLY, - VK_SAMPLE_COUNT_1_BIT, - 1, - 1, - VK_IMAGE_TILING_OPTIMAL, - 0); + texture.image = std::make_unique(get_device(), image->get_extent(), image->get_format(), + VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY, + VK_SAMPLE_COUNT_1_BIT, 1, 1, VK_IMAGE_TILING_OPTIMAL, 0); auto data_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), image->get_data()); @@ -337,8 +331,8 @@ void MultiDrawIndirect::load_scene() subresource_range.baseMipLevel = 0; subresource_range.levelCount = texture.n_mip_maps; - vkb::image_layout_transition( - texture_cmd->get_handle(), texture.image->get_handle(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); + vkb::image_layout_transition(texture_cmd->get_handle(), texture.image->get_handle(), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + subresource_range); auto offsets = image->get_offsets(); VkBufferImageCopy region = {}; @@ -365,9 +359,7 @@ void MultiDrawIndirect::load_scene() VkDescriptorImageInfo image_descriptor; image_descriptor.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; image_descriptor.imageView = texture.image_view->get_handle(); - image_descriptor.sampler = (fmtProps.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) ? - sampler_linear : - sampler_nearest; + image_descriptor.sampler = (fmtProps.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) ? sampler_linear : sampler_nearest; image_descriptors.push_back(image_descriptor); textures.emplace_back(std::move(texture)); @@ -401,10 +393,8 @@ void MultiDrawIndirect::load_scene() model.triangles.resize(nTriangles); for (size_t i = 0; i < nTriangles; ++i) { - model.triangles[i] = { - static_cast(temp_buffer[3 * i]), - static_cast(temp_buffer[3 * i + 1]), - static_cast(temp_buffer[3 * i + 2])}; + model.triangles[i] = {static_cast(temp_buffer[3 * i]), static_cast(temp_buffer[3 * i + 1]), + static_cast(temp_buffer[3 * i + 2])}; } } model.bounding_sphere = BoundingSphere(pts); @@ -448,18 +438,21 @@ void MultiDrawIndirect::initialize_resources() auto staging_model_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), model_buffer_size, nullptr); // We will store the GPU commands in the indirect call buffer - constexpr auto default_indirect_flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - auto indirect_flags = default_indirect_flags; + constexpr auto default_indirect_flags = + VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + auto indirect_flags = default_indirect_flags; if (m_supports_buffer_device) { indirect_flags |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; } - indirect_call_buffer = std::make_unique(get_device(), models.size() * sizeof(VkDrawIndexedIndirectCommand), indirect_flags, VMA_MEMORY_USAGE_GPU_ONLY, VMA_ALLOCATION_CREATE_MAPPED_BIT, queue_families); + indirect_call_buffer = std::make_unique(get_device(), models.size() * sizeof(VkDrawIndexedIndirectCommand), indirect_flags, + VMA_MEMORY_USAGE_GPU_ONLY, VMA_ALLOCATION_CREATE_MAPPED_BIT, queue_families); // Create a buffer containing the addresses of the indirect calls. // In this sample, the order of the addresses will match that of the other buffers, but in general they could be in any order - const size_t address_buffer_size = sizeof(VkDeviceAddress); - auto staging_address_buffer = std::make_unique(get_device(), address_buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + const size_t address_buffer_size = sizeof(VkDeviceAddress); + auto staging_address_buffer = + std::make_unique(get_device(), address_buffer_size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); if (m_supports_buffer_device) { auto *destPtr = (uint64_t *) staging_address_buffer->get_data(); @@ -493,7 +486,9 @@ void MultiDrawIndirect::initialize_resources() auto cmd = get_device().get_command_pool().request_command_buffer(); cmd->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, VK_NULL_HANDLE); auto copy = [this, &cmd](vkb::core::BufferC &staging_buffer, VkBufferUsageFlags buffer_usage_flags) { - auto output_buffer = std::make_unique(get_device(), staging_buffer.get_size(), buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VMA_MEMORY_USAGE_GPU_ONLY, VMA_ALLOCATION_CREATE_MAPPED_BIT, queue_families); + auto output_buffer = + std::make_unique(get_device(), staging_buffer.get_size(), buffer_usage_flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VMA_MEMORY_USAGE_GPU_ONLY, VMA_ALLOCATION_CREATE_MAPPED_BIT, queue_families); cmd->copy_buffer(staging_buffer, *output_buffer, staging_buffer.get_size()); vkb::BufferMemoryBarrier barrier; @@ -523,11 +518,10 @@ void MultiDrawIndirect::initialize_resources() void MultiDrawIndirect::create_pipeline() { - std::vector pool_sizes = { - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 6}, - {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 * static_cast(textures.size())}, - {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 6}}; - VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 3); + std::vector pool_sizes = {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 6}, + {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 * static_cast(textures.size())}, + {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 6}}; + VkDescriptorPoolCreateInfo descriptor_pool_create_info = vkb::initializers::descriptor_pool_create_info(pool_sizes, 3); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); // The model information will be used to index textures in the fragment shader, @@ -558,20 +552,20 @@ void MultiDrawIndirect::create_pipeline() command_buffer_binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; // Create descriptors - auto create_descriptors = [this](const std::vector &set_layout_bindings, VkDescriptorSetLayout &_descriptor_set_layout, VkPipelineLayout &_pipeline_layout) { - VkDescriptorSetLayoutCreateInfo descriptor_layout = vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); + auto create_descriptors = [this](const std::vector &set_layout_bindings, VkDescriptorSetLayout &_descriptor_set_layout, + VkPipelineLayout &_pipeline_layout) { + VkDescriptorSetLayoutCreateInfo descriptor_layout = + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &_descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &_descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&_descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &_pipeline_layout)); }; // Render pipeline - std::vector set_layout_bindings = {model_information_binding, image_array_binding, scene_uniform_binding, command_buffer_binding}; + std::vector set_layout_bindings = {model_information_binding, image_array_binding, scene_uniform_binding, + command_buffer_binding}; create_descriptors(set_layout_bindings, descriptor_set_layout, pipeline_layout); // Compute pipeline @@ -593,29 +587,27 @@ void MultiDrawIndirect::create_pipeline() create_descriptors(device_address_layout_bindings, device_address_descriptor_set_layout, device_address_pipeline_layout); } - VkPipelineInputAssemblyStateCreateInfo input_assembly_state = vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); + VkPipelineInputAssemblyStateCreateInfo input_assembly_state = + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); - VkPipelineRasterizationStateCreateInfo rasterization_state = vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + VkPipelineRasterizationStateCreateInfo rasterization_state = + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); - VkPipelineDepthStencilStateCreateInfo depth_stencil_state = vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS); - depth_stencil_state.depthBoundsTestEnable = VK_FALSE; - depth_stencil_state.minDepthBounds = 0.f; - depth_stencil_state.maxDepthBounds = 1.f; + VkPipelineDepthStencilStateCreateInfo depth_stencil_state = + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS); + depth_stencil_state.depthBoundsTestEnable = VK_FALSE; + depth_stencil_state.minDepthBounds = 0.f; + depth_stencil_state.maxDepthBounds = 1.f; VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); @@ -688,22 +680,26 @@ void MultiDrawIndirect::initialize_descriptors() VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_set_allocate_info, &_descriptor_set)); VkDescriptorBufferInfo model_buffer_descriptor = create_descriptor(*model_information_buffer); - VkWriteDescriptorSet model_write = vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, &model_buffer_descriptor, 1); + VkWriteDescriptorSet model_write = + vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, &model_buffer_descriptor, 1); - VkWriteDescriptorSet texture_array_write = vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, image_descriptors.data(), static_cast(image_descriptors.size())); + VkWriteDescriptorSet texture_array_write = vkb::initializers::write_descriptor_set( + _descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, image_descriptors.data(), static_cast(image_descriptors.size())); VkDescriptorBufferInfo scene_descriptor = create_descriptor(*scene_uniform_buffer); - VkWriteDescriptorSet scene_write = vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &scene_descriptor, 1); + VkWriteDescriptorSet scene_write = vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &scene_descriptor, 1); VkDescriptorBufferInfo draw_command_descriptor = create_descriptor(*indirect_call_buffer); - VkWriteDescriptorSet draw_command_write = vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 3, &draw_command_descriptor, 1); + VkWriteDescriptorSet draw_command_write = + vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 3, &draw_command_descriptor, 1); VkDescriptorBufferInfo device_address_descriptor; VkWriteDescriptorSet device_address_write; if (m_supports_buffer_device && device_address_buffer) { device_address_descriptor = create_descriptor(*device_address_buffer); - device_address_write = vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4, &device_address_descriptor, 1); + device_address_write = + vkb::initializers::write_descriptor_set(_descriptor_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 4, &device_address_descriptor, 1); } std::vector write_descriptor_sets; @@ -740,8 +736,8 @@ void MultiDrawIndirect::update_scene_uniform() { if (!scene_uniform_buffer) { - scene_uniform_buffer = std::make_unique( - get_device(), sizeof(SceneUniform), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU, VMA_ALLOCATION_CREATE_MAPPED_BIT, queue_families); + scene_uniform_buffer = std::make_unique(get_device(), sizeof(SceneUniform), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VMA_MEMORY_USAGE_CPU_TO_GPU, VMA_ALLOCATION_CREATE_MAPPED_BIT, queue_families); } scene_uniform.proj = camera.matrices.perspective; scene_uniform.view = camera.matrices.view; @@ -798,8 +794,7 @@ void MultiDrawIndirect::render(float delta_time) } void MultiDrawIndirect::finish() -{ -} +{} void MultiDrawIndirect::run_cull() { @@ -859,8 +854,7 @@ namespace */ struct VisibilityTester { - explicit VisibilityTester(glm::mat4x4 view_matrix) : - planes(get_view_planes(view_matrix)) + explicit VisibilityTester(glm::mat4x4 view_matrix) : planes(get_view_planes(view_matrix)) {} std::array planes; @@ -924,7 +918,9 @@ void MultiDrawIndirect::cpu_cull() if (!cpu_staging_buffer || cpu_staging_buffer->get_size() != call_buffer_size) { - cpu_staging_buffer = std::make_unique(get_device(), models.size() * sizeof(VkDrawIndexedIndirectCommand), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + cpu_staging_buffer = + std::make_unique(get_device(), models.size() * sizeof(VkDrawIndexedIndirectCommand), + VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); } cpu_staging_buffer->update(cpu_commands.data(), call_buffer_size, 0); diff --git a/samples/performance/multithreading_render_passes/multithreading_render_passes.cpp b/samples/performance/multithreading_render_passes/multithreading_render_passes.cpp index e849707f1b..9efaf9cd3f 100644 --- a/samples/performance/multithreading_render_passes/multithreading_render_passes.cpp +++ b/samples/performance/multithreading_render_passes/multithreading_render_passes.cpp @@ -97,11 +97,8 @@ std::unique_ptr MultithreadingRenderPasses::creat { VkExtent3D extent{size, size, 1}; - vkb::core::Image depth_image{get_device(), - extent, - vkb::get_suitable_depth_format(get_device().get_gpu().get_handle()), - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, - VMA_MEMORY_USAGE_GPU_ONLY}; + vkb::core::Image depth_image{get_device(), extent, vkb::get_suitable_depth_format(get_device().get_gpu().get_handle()), + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; std::vector images; @@ -113,9 +110,10 @@ std::unique_ptr MultithreadingRenderPasses::creat std::unique_ptr MultithreadingRenderPasses::create_shadow_renderpass() { // Shadowmap subpass - auto shadowmap_vs = vkb::ShaderSource{"shadows/shadowmap.vert.spv"}; - auto shadowmap_fs = vkb::ShaderSource{"shadows/shadowmap.frag.spv"}; - auto scene_subpass = std::make_unique(get_render_context(), std::move(shadowmap_vs), std::move(shadowmap_fs), get_scene(), *shadowmap_camera); + auto shadowmap_vs = vkb::ShaderSource{"shadows/shadowmap.vert.spv"}; + auto shadowmap_fs = vkb::ShaderSource{"shadows/shadowmap.frag.spv"}; + auto scene_subpass = + std::make_unique(get_render_context(), std::move(shadowmap_vs), std::move(shadowmap_fs), get_scene(), *shadowmap_camera); shadow_subpass = scene_subpass.get(); @@ -131,8 +129,8 @@ std::unique_ptr MultithreadingRenderPasses::cre // Main subpass auto main_vs = vkb::ShaderSource{"shadows/main.vert.spv"}; auto main_fs = vkb::ShaderSource{"shadows/main.frag.spv"}; - auto scene_subpass = std::make_unique( - get_render_context(), std::move(main_vs), std::move(main_fs), get_scene(), *camera, *shadowmap_camera, shadow_render_targets); + auto scene_subpass = std::make_unique(get_render_context(), std::move(main_vs), std::move(main_fs), get_scene(), *camera, *shadowmap_camera, + shadow_render_targets); // Main pipeline auto main_render_pipeline = std::make_unique(); @@ -228,12 +226,11 @@ void MultithreadingRenderPasses::record_separate_primary_command_buffers(std::ve get_render_context().get_active_frame().get_command_pool(queue, reset_mode, 1).request_command_buffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY); // Recording shadow command buffer - auto shadow_buffer_future = std::async( - [this, shadow_command_buffer]() { - shadow_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); - draw_shadow_pass(*shadow_command_buffer); - shadow_command_buffer->end(); - }); + auto shadow_buffer_future = std::async([this, shadow_command_buffer]() { + shadow_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); + draw_shadow_pass(*shadow_command_buffer); + shadow_command_buffer->end(); + }); // Recording scene command buffer main_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); @@ -264,27 +261,29 @@ void MultithreadingRenderPasses::record_separate_secondary_command_buffers(std:: // Same framebuffer and render pass should be specified in the inheritance info for secondary command buffers // and vkCmdBeginRenderPass for primary command buffers auto &shadow_render_target = *shadow_render_targets[get_render_context().get_active_frame_index()]; - auto &shadow_render_pass = main_command_buffer->get_render_pass(shadow_render_target, shadow_render_pipeline->get_load_store(), shadow_render_pipeline->get_subpasses()); - auto &shadow_framebuffer = get_device().get_resource_cache().request_framebuffer(shadow_render_target, shadow_render_pass); + auto &shadow_render_pass = + main_command_buffer->get_render_pass(shadow_render_target, shadow_render_pipeline->get_load_store(), shadow_render_pipeline->get_subpasses()); + auto &shadow_framebuffer = get_device().get_resource_cache().request_framebuffer(shadow_render_target, shadow_render_pass); auto &scene_render_target = get_render_context().get_active_frame().get_render_target(); - auto &scene_render_pass = main_command_buffer->get_render_pass(scene_render_target, main_render_pipeline->get_load_store(), main_render_pipeline->get_subpasses()); - auto &scene_framebuffer = get_device().get_resource_cache().request_framebuffer(scene_render_target, scene_render_pass); + auto &scene_render_pass = + main_command_buffer->get_render_pass(scene_render_target, main_render_pipeline->get_load_store(), main_render_pipeline->get_subpasses()); + auto &scene_framebuffer = get_device().get_resource_cache().request_framebuffer(scene_render_target, scene_render_pass); // Recording shadow command buffer - auto shadow_buffer_future = std::async( - [this, shadow_command_buffer, &shadow_render_pass, &shadow_framebuffer]() { - shadow_command_buffer->begin( - VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, &shadow_render_pass, &shadow_framebuffer, 0); - draw_shadow_pass(*shadow_command_buffer); - shadow_command_buffer->end(); - }); + auto shadow_buffer_future = std::async([this, shadow_command_buffer, &shadow_render_pass, &shadow_framebuffer]() { + shadow_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, &shadow_render_pass, + &shadow_framebuffer, 0); + draw_shadow_pass(*shadow_command_buffer); + shadow_command_buffer->end(); + }); // Recording scene command buffer vkb::ColorBlendState scene_color_blend_state; scene_color_blend_state.attachments.resize(scene_render_pass.get_color_output_count(0)); - scene_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, &scene_render_pass, &scene_framebuffer, 0); + scene_command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, &scene_render_pass, + &scene_framebuffer, 0); scene_command_buffer->set_color_blend_state(scene_color_blend_state); draw_main_pass(*scene_command_buffer); scene_command_buffer->end(); @@ -297,13 +296,15 @@ void MultithreadingRenderPasses::record_separate_secondary_command_buffers(std:: record_shadow_pass_image_memory_barrier(*main_command_buffer); - main_command_buffer->begin_render_pass(shadow_render_target, shadow_render_pass, shadow_framebuffer, shadow_render_pipeline->get_clear_value(), VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); + main_command_buffer->begin_render_pass(shadow_render_target, shadow_render_pass, shadow_framebuffer, shadow_render_pipeline->get_clear_value(), + VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); main_command_buffer->execute_commands(*shadow_command_buffer); main_command_buffer->end_render_pass(); record_main_pass_image_memory_barriers(*main_command_buffer); - main_command_buffer->begin_render_pass(scene_render_target, scene_render_pass, scene_framebuffer, main_render_pipeline->get_clear_value(), VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); + main_command_buffer->begin_render_pass(scene_render_target, scene_render_pass, scene_framebuffer, main_render_pipeline->get_clear_value(), + VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS); main_command_buffer->execute_commands(*scene_command_buffer); main_command_buffer->end_render_pass(); @@ -451,8 +452,7 @@ MultithreadingRenderPasses::MainSubpass::MainSubpass(vkb::rendering::RenderConte shadowmap_camera{shadowmap_camera}, shadow_render_targets{shadow_render_targets}, vkb::rendering::subpasses::ForwardSubpassC{render_context, std::move(vertex_source), std::move(fragment_source), scene, camera} -{ -} +{} void MultithreadingRenderPasses::MainSubpass::prepare() { @@ -504,8 +504,7 @@ MultithreadingRenderPasses::ShadowSubpass::ShadowSubpass(vkb::rendering::RenderC vkb::sg::Scene &scene, vkb::sg::Camera &camera) : vkb::rendering::subpasses::GeometrySubpassC{render_context, std::move(vertex_source), std::move(fragment_source), scene, camera} -{ -} +{} void MultithreadingRenderPasses::ShadowSubpass::prepare_pipeline_state(vkb::core::CommandBufferC &command_buffer, VkFrontFace front_face, @@ -543,8 +542,7 @@ vkb::PipelineLayout &MultithreadingRenderPasses::ShadowSubpass::prepare_pipeline return command_buffer.get_device().get_resource_cache().request_pipeline_layout({vertex_shader_module}); } -void MultithreadingRenderPasses::ShadowSubpass::prepare_push_constants(vkb::core::CommandBufferC &command_buffer, - vkb::sg::SubMesh &sub_mesh) +void MultithreadingRenderPasses::ShadowSubpass::prepare_push_constants(vkb::core::CommandBufferC &command_buffer, vkb::sg::SubMesh &sub_mesh) { // No push constants are used the in shadow pass return; diff --git a/samples/performance/pipeline_barriers/pipeline_barriers.cpp b/samples/performance/pipeline_barriers/pipeline_barriers.cpp index f01a88524c..2cd04d25dd 100644 --- a/samples/performance/pipeline_barriers/pipeline_barriers.cpp +++ b/samples/performance/pipeline_barriers/pipeline_barriers.cpp @@ -87,8 +87,8 @@ bool PipelineBarriers::prepare(const vkb::ApplicationOptions &options) auto geometry_vs = vkb::ShaderSource{"deferred/geometry.vert.spv"}; auto geometry_fs = vkb::ShaderSource{"deferred/geometry.frag.spv"}; - auto gbuffer_pass = std::make_unique( - get_render_context(), std::move(geometry_vs), std::move(geometry_fs), get_scene(), *camera); + auto gbuffer_pass = std::make_unique(get_render_context(), std::move(geometry_vs), std::move(geometry_fs), + get_scene(), *camera); gbuffer_pass->set_output_attachments({1, 2, 3}); gbuffer_pipeline.add_subpass(std::move(gbuffer_pass)); gbuffer_pipeline.set_load_store(vkb::gbuffer::get_clear_store_all()); @@ -101,9 +101,7 @@ bool PipelineBarriers::prepare(const vkb::ApplicationOptions &options) lighting_pipeline.add_subpass(std::move(lighting_subpass)); lighting_pipeline.set_load_store(vkb::gbuffer::get_load_all_store_swapchain()); - get_stats().request_stats({vkb::StatIndex::frame_times, - vkb::StatIndex::gpu_vertex_cycles, - vkb::StatIndex::gpu_fragment_cycles}, + get_stats().request_stats({vkb::StatIndex::frame_times, vkb::StatIndex::gpu_vertex_cycles, vkb::StatIndex::gpu_fragment_cycles}, vkb::CounterSamplingConfig{vkb::CounterSamplingMode::Continuous}); create_gui(*window, &get_stats()); @@ -139,22 +137,13 @@ std::unique_ptr PipelineBarriers::create_render_t auto &device = swapchain_image.get_device(); auto &extent = swapchain_image.get_extent(); - vkb::core::Image depth_image{device, - extent, - vkb::get_suitable_depth_format(swapchain_image.get_device().get_gpu().get_handle()), - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, - VMA_MEMORY_USAGE_GPU_ONLY}; + vkb::core::Image depth_image{device, extent, vkb::get_suitable_depth_format(swapchain_image.get_device().get_gpu().get_handle()), + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; - vkb::core::Image albedo_image{device, - extent, - VK_FORMAT_R8G8B8A8_UNORM, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, + vkb::core::Image albedo_image{device, extent, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; - vkb::core::Image normal_image{device, - extent, - VK_FORMAT_A2B10G10R10_UNORM_PACK32, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, + vkb::core::Image normal_image{device, extent, VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VMA_MEMORY_USAGE_GPU_ONLY}; std::vector images; @@ -347,7 +336,8 @@ void PipelineBarriers::draw_gui() } get_gui().show_options_window( - /* body = */ [this, portrait_mode]() { + /* body = */ + [this, portrait_mode]() { ImGui::Text("Pipeline barrier stages:"); ImGui::RadioButton("Bottom to top", reinterpret_cast(&dependency_type), DependencyType::BOTTOM_TO_TOP); ImGui::SameLine(); diff --git a/samples/performance/pipeline_cache/pipeline_cache.cpp b/samples/performance/pipeline_cache/pipeline_cache.cpp index 5b32441479..3d026b982a 100644 --- a/samples/performance/pipeline_cache/pipeline_cache.cpp +++ b/samples/performance/pipeline_cache/pipeline_cache.cpp @@ -135,7 +135,8 @@ bool PipelineCache::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); @@ -148,7 +149,8 @@ bool PipelineCache::prepare(const vkb::ApplicationOptions &options) void PipelineCache::draw_gui() { get_gui().show_options_window( - /* body = */ [this]() { + /* body = */ + [this]() { if (ImGui::Checkbox("Pipeline cache", &enable_pipeline_cache)) { vkb::ResourceCache &resource_cache = get_device().get_resource_cache(); diff --git a/samples/performance/render_passes/render_passes.cpp b/samples/performance/render_passes/render_passes.cpp index 290c6b08f5..a5bd71c0c9 100644 --- a/samples/performance/render_passes/render_passes.cpp +++ b/samples/performance/render_passes/render_passes.cpp @@ -61,7 +61,8 @@ void RenderPassesSample::draw_gui() } get_gui().show_options_window( - /* body = */ [this, lines]() { + /* body = */ + [this, lines]() { // Checkbox vkCmdClear ImGui::Checkbox("Use vkCmdClearAttachments (color)", &cmd_clear); @@ -105,9 +106,7 @@ bool RenderPassesSample::prepare(const vkb::ApplicationOptions &options) return false; } - get_stats().request_stats({vkb::StatIndex::gpu_fragment_cycles, - vkb::StatIndex::gpu_ext_read_bytes, - vkb::StatIndex::gpu_ext_write_bytes}); + get_stats().request_stats({vkb::StatIndex::gpu_fragment_cycles, vkb::StatIndex::gpu_ext_read_bytes, vkb::StatIndex::gpu_ext_write_bytes}); load_scene("scenes/sponza/Sponza01.gltf"); @@ -116,7 +115,8 @@ bool RenderPassesSample::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); diff --git a/samples/performance/render_passes/render_passes.h b/samples/performance/render_passes/render_passes.h index 5125c54f07..5ffa951f2e 100644 --- a/samples/performance/render_passes/render_passes.h +++ b/samples/performance/render_passes/render_passes.h @@ -65,15 +65,9 @@ class RenderPassesSample : public vkb::VulkanSampleC // Whether to use vkCmdClear or not bool cmd_clear = false; - RadioButtonGroup load{ - "Color attachment load operation", - {"Load", "Clear", "Don't care"}, - 0}; - - RadioButtonGroup store{ - "Depth attachment store operation", - {"Store", "Don't care"}, - 1}; + RadioButtonGroup load{"Color attachment load operation", {"Load", "Clear", "Don't care"}, 0}; + + RadioButtonGroup store{"Depth attachment store operation", {"Store", "Don't care"}, 1}; std::vector radio_buttons = {&load, &store}; diff --git a/samples/performance/specialization_constants/specialization_constants.cpp b/samples/performance/specialization_constants/specialization_constants.cpp index f2ccb228bb..e66f54ca0a 100644 --- a/samples/performance/specialization_constants/specialization_constants.cpp +++ b/samples/performance/specialization_constants/specialization_constants.cpp @@ -40,8 +40,7 @@ SpecializationConstants::ForwardSubpassCustomLights::ForwardSubpassCustomLights( vkb::sg::Scene &scene_, vkb::sg::Camera &camera) : vkb::rendering::subpasses::ForwardSubpassC{render_context, std::move(vertex_shader), std::move(fragment_shader), scene_, camera} -{ -} +{} bool SpecializationConstants::prepare(const vkb::ApplicationOptions &options) { @@ -149,7 +148,8 @@ void SpecializationConstants::draw_gui() uint32_t lines = landscape ? 1 : 2; get_gui().show_options_window( - /* body = */ [&]() { + /* body = */ + [&]() { ImGui::RadioButton("Uniform Buffer Objects", &specialization_constants_enabled, 0); if (landscape) { diff --git a/samples/performance/specialization_constants/specialization_constants.h b/samples/performance/specialization_constants/specialization_constants.h index 351a9a9861..4807d315b1 100644 --- a/samples/performance/specialization_constants/specialization_constants.h +++ b/samples/performance/specialization_constants/specialization_constants.h @@ -73,7 +73,8 @@ class SpecializationConstants : public vkb::VulkanSampleC * @return BufferAllocation A buffer allocation created for use in shaders */ template - vkb::BufferAllocationC allocate_custom_lights(vkb::core::CommandBufferC &command_buffer, const std::vector &scene_lights, size_t light_count) + vkb::BufferAllocationC + allocate_custom_lights(vkb::core::CommandBufferC &command_buffer, const std::vector &scene_lights, size_t light_count) { T light_info; light_info.count = vkb::to_u32(light_count); diff --git a/samples/performance/subpasses/subpasses.cpp b/samples/performance/subpasses/subpasses.cpp index 3cc6cc55d6..e744dcc863 100644 --- a/samples/performance/subpasses/subpasses.cpp +++ b/samples/performance/subpasses/subpasses.cpp @@ -63,23 +63,12 @@ std::unique_ptr Subpasses::create_render_target(v // Albedo RGBA8_UNORM (32-bit) // Normal RGB10A2_UNORM (32-bit) - vkb::core::Image depth_image{device, - extent, - vkb::get_suitable_depth_format(swapchain_image.get_device().get_gpu().get_handle()), - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | rt_usage_flags, - VMA_MEMORY_USAGE_GPU_ONLY}; - - vkb::core::Image albedo_image{device, - extent, - albedo_format, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | rt_usage_flags, - VMA_MEMORY_USAGE_GPU_ONLY}; - - vkb::core::Image normal_image{device, - extent, - normal_format, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | rt_usage_flags, - VMA_MEMORY_USAGE_GPU_ONLY}; + vkb::core::Image depth_image{device, extent, vkb::get_suitable_depth_format(swapchain_image.get_device().get_gpu().get_handle()), + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | rt_usage_flags, VMA_MEMORY_USAGE_GPU_ONLY}; + + vkb::core::Image albedo_image{device, extent, albedo_format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | rt_usage_flags, VMA_MEMORY_USAGE_GPU_ONLY}; + + vkb::core::Image normal_image{device, extent, normal_format, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | rt_usage_flags, VMA_MEMORY_USAGE_GPU_ONLY}; std::vector images; @@ -156,10 +145,7 @@ bool Subpasses::prepare(const vkb::ApplicationOptions &options) lighting_render_pipeline = create_lighting_renderpass(); // Enable stats - get_stats().request_stats({vkb::StatIndex::frame_times, - vkb::StatIndex::gpu_fragment_jobs, - vkb::StatIndex::gpu_tiles, - vkb::StatIndex::gpu_ext_read_bytes, + get_stats().request_stats({vkb::StatIndex::frame_times, vkb::StatIndex::gpu_fragment_jobs, vkb::StatIndex::gpu_tiles, vkb::StatIndex::gpu_ext_read_bytes, vkb::StatIndex::gpu_ext_write_bytes}); // Enable gui @@ -202,8 +188,7 @@ void Subpasses::update(float delta_time) } // Check whether the user switched the attachment or the G-buffer option - if (configs[Config::TransientAttachments].value != last_transient_attachment || - configs[Config::GBufferSize].value != last_g_buffer_size) + if (configs[Config::TransientAttachments].value != last_transient_attachment || configs[Config::GBufferSize].value != last_g_buffer_size) { // If attachment option has changed if (configs[Config::TransientAttachments].value != last_transient_attachment) @@ -264,7 +249,8 @@ void Subpasses::draw_gui() } get_gui().show_options_window( - /* body = */ [this, lines]() { + /* body = */ + [this, lines]() { // Create a line for every config for (size_t i = 0; i < configs.size(); ++i) { @@ -304,8 +290,8 @@ std::unique_ptr Subpasses::create_one_renderpas // Geometry subpass auto geometry_vs = vkb::ShaderSource{"deferred/geometry.vert.spv"}; auto geometry_fs = vkb::ShaderSource{"deferred/geometry.frag.spv"}; - auto scene_subpass = std::make_unique( - get_render_context(), std::move(geometry_vs), std::move(geometry_fs), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(geometry_vs), std::move(geometry_fs), + get_scene(), *camera); // Outputs are depth, albedo, and normal scene_subpass->set_output_attachments({1, 2, 3}); @@ -337,8 +323,8 @@ std::unique_ptr Subpasses::create_geometry_rend // Geometry subpass auto geometry_vs = vkb::ShaderSource{"deferred/geometry.vert.spv"}; auto geometry_fs = vkb::ShaderSource{"deferred/geometry.frag.spv"}; - auto scene_subpass = std::make_unique( - get_render_context(), std::move(geometry_vs), std::move(geometry_fs), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(geometry_vs), std::move(geometry_fs), + get_scene(), *camera); // Outputs are depth, albedo, and normal scene_subpass->set_output_attachments({1, 2, 3}); diff --git a/samples/performance/subpasses/subpasses.h b/samples/performance/subpasses/subpasses.h index f41f29ce64..28613620fe 100644 --- a/samples/performance/subpasses/subpasses.h +++ b/samples/performance/subpasses/subpasses.h @@ -126,19 +126,18 @@ class Subpasses : public vkb::VulkanSampleC VkFormat normal_format{VK_FORMAT_A2B10G10R10_UNORM_PACK32}; VkImageUsageFlags rt_usage_flags{VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT}; - std::vector configs = { - {/* config = */ Config::RenderTechnique, - /* description = */ "Render technique", - /* options = */ {"Subpasses", "Renderpasses"}, - /* value = */ 0}, - {/* config = */ Config::TransientAttachments, - /* description = */ "Transient attachments", - /* options = */ {"Enabled", "Disabled"}, - /* value = */ 0}, - {/* config = */ Config::GBufferSize, - /* description = */ "G-Buffer size", - /* options = */ {"128-bit", "More"}, - /* value = */ 0}}; + std::vector configs = {{/* config = */ Config::RenderTechnique, + /* description = */ "Render technique", + /* options = */ {"Subpasses", "Renderpasses"}, + /* value = */ 0}, + {/* config = */ Config::TransientAttachments, + /* description = */ "Transient attachments", + /* options = */ {"Enabled", "Disabled"}, + /* value = */ 0}, + {/* config = */ Config::GBufferSize, + /* description = */ "G-Buffer size", + /* options = */ {"128-bit", "More"}, + /* value = */ 0}}; }; std::unique_ptr create_subpasses(); diff --git a/samples/performance/surface_rotation/surface_rotation.cpp b/samples/performance/surface_rotation/surface_rotation.cpp index 2dc9b07447..e22cf9fc7e 100644 --- a/samples/performance/surface_rotation/surface_rotation.cpp +++ b/samples/performance/surface_rotation/surface_rotation.cpp @@ -54,8 +54,7 @@ bool SurfaceRotation::prepare(const vkb::ApplicationOptions &options) throw std::runtime_error("Requires a surface to run sample"); } - get_stats().request_stats({vkb::StatIndex::gpu_ext_read_stalls, - vkb::StatIndex::gpu_ext_write_stalls}); + get_stats().request_stats({vkb::StatIndex::gpu_ext_read_stalls, vkb::StatIndex::gpu_ext_write_stalls}); load_scene("scenes/sponza/Sponza01.gltf"); @@ -64,7 +63,8 @@ bool SurfaceRotation::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); @@ -127,14 +127,15 @@ void SurfaceRotation::draw_gui() // If pre-rotate is enabled, the aspect ratio will not change, therefore need to check if the // scene has been rotated using the swapchain preTransform attribute - auto rotated = get_render_context().get_swapchain().get_transform() & (VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR); + auto rotated = get_render_context().get_swapchain().get_transform() & (VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR); float aspect_ratio = static_cast(extent.width) / extent.height; if (aspect_ratio > 1.0f || (aspect_ratio < 1.0f && rotated)) { // GUI landscape layout uint32_t lines = 2; get_gui().show_options_window( - /* body = */ [&]() { + /* body = */ + [&]() { ImGui::Checkbox(prerotate_str.c_str(), &pre_rotate); ImGui::Text("%s | %s", transform.c_str(), resolution_str.c_str()); }, @@ -145,7 +146,8 @@ void SurfaceRotation::draw_gui() // GUI portrait layout uint32_t lines = 3; get_gui().show_options_window( - /* body = */ [&]() { + /* body = */ + [&]() { ImGui::Checkbox(prerotate_str.c_str(), &pre_rotate); ImGui::Text("%s", transform.c_str()); ImGui::Text("%s", resolution_str.c_str()); @@ -161,9 +163,7 @@ VkSurfaceTransformFlagBitsKHR SurfaceRotation::select_pre_transform() if (pre_rotate) { VkSurfaceCapabilitiesKHR surface_properties; - VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(get_device().get_gpu().get_handle(), - get_surface(), - &surface_properties)); + VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(get_device().get_gpu().get_handle(), get_surface(), &surface_properties)); // Best practice: adjust the preTransform attribute in the swapchain properties // so that it matches the value in the surface properties. This is to @@ -186,9 +186,7 @@ void SurfaceRotation::handle_no_resize_rotations() // If pre-rotate mode is enabled, the sample will detect a 180 degree change in orientation // and re-create the swapchain VkSurfaceCapabilitiesKHR surface_properties; - VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(get_device().get_gpu().get_handle(), - get_surface(), - &surface_properties)); + VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(get_device().get_gpu().get_handle(), get_surface(), &surface_properties)); if (surface_properties.currentExtent.width == get_render_context().get_surface_extent().width && surface_properties.currentExtent.height == get_render_context().get_surface_extent().height && diff --git a/samples/performance/swapchain_images/swapchain_images.cpp b/samples/performance/swapchain_images/swapchain_images.cpp index f463fc0fd6..f32df8da95 100644 --- a/samples/performance/swapchain_images/swapchain_images.cpp +++ b/samples/performance/swapchain_images/swapchain_images.cpp @@ -51,7 +51,8 @@ bool SwapchainImages::prepare(const vkb::ApplicationOptions &options) vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); @@ -83,7 +84,8 @@ void SwapchainImages::update(float delta_time) void SwapchainImages::draw_gui() { get_gui().show_options_window( - /* body = */ [this]() { + /* body = */ + [this]() { ImGui::RadioButton("Double buffering", &swapchain_image_count, 2); ImGui::SameLine(); ImGui::RadioButton("Triple buffering", &swapchain_image_count, 3); diff --git a/samples/performance/texture_compression_basisu/texture_compression_basisu.cpp b/samples/performance/texture_compression_basisu/texture_compression_basisu.cpp index 628ee72eb3..d88c594c12 100644 --- a/samples/performance/texture_compression_basisu/texture_compression_basisu.cpp +++ b/samples/performance/texture_compression_basisu/texture_compression_basisu.cpp @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, Sascha Willems +/* Copyright (c) 2021-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -55,7 +55,8 @@ bool TextureCompressionBasisu::format_supported(VkFormat format) { VkFormatProperties format_properties; vkGetPhysicalDeviceFormatProperties(get_device().get_gpu().get_handle(), format, &format_properties); - return ((format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_TRANSFER_DST_BIT) && (format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)); + return ((format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_TRANSFER_DST_BIT) && + (format_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)); } // Get a list of possible transcoding target formats supported by the selected gpu @@ -123,7 +124,8 @@ void TextureCompressionBasisu::transcode_texture(const std::string &input_file, // We are working with KTX2.0 files, so we need to use the ktxTexture2 class ktxTexture2 *ktx_texture; // Load the KTX2.0 file into memory. This is agnostic to the KTX version, so we cast the ktxTexture2 down to ktxTexture - KTX_error_code result = ktxTexture_CreateFromNamedFile(file_name.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, reinterpret_cast(&ktx_texture)); + KTX_error_code result = + ktxTexture_CreateFromNamedFile(file_name.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, reinterpret_cast(&ktx_texture)); if (result != KTX_SUCCESS) { throw std::runtime_error("Could not load the requested image file."); @@ -162,7 +164,7 @@ void TextureCompressionBasisu::transcode_texture(const std::string &input_file, VkMemoryAllocateInfo memory_allocate_info = vkb::initializers::memory_allocate_info(); VkMemoryRequirements memory_requirements = {}; vkGetBufferMemoryRequirements(get_device().get_handle(), staging_buffer, &memory_requirements); - memory_allocate_info.allocationSize = memory_requirements.size; + memory_allocate_info.allocationSize = memory_requirements.size; memory_allocate_info.memoryTypeIndex = get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VK_CHECK(vkAllocateMemory(get_device().get_handle(), &memory_allocate_info, nullptr, &staging_memory)); @@ -228,18 +230,13 @@ void TextureCompressionBasisu::transcode_texture(const std::string &input_file, vkb::image_layout_transition(copy_command, texture.image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); // Copy mip levels from staging buffer - vkCmdCopyBufferToImage( - copy_command, - staging_buffer, - texture.image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - static_cast(buffer_copy_regions.size()), - buffer_copy_regions.data()); + vkCmdCopyBufferToImage(copy_command, staging_buffer, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast(buffer_copy_regions.size()), + buffer_copy_regions.data()); // Once the data has been uploaded we transfer to the texture image to the shader read layout, so it can be sampled from // Insert a memory dependency at the proper pipeline stages that will execute the image layout transition - vkb::image_layout_transition( - copy_command, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); + vkb::image_layout_transition(copy_command, texture.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + subresource_range); // Store current layout for later reuse texture.image_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; @@ -307,8 +304,9 @@ void TextureCompressionBasisu::destroy_texture(Texture texture) void TextureCompressionBasisu::update_image_descriptor() { - VkDescriptorImageInfo image_descriptor = {texture.sampler, texture.view, texture.image_layout}; - VkWriteDescriptorSet write_descriptor_set = vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &image_descriptor); + VkDescriptorImageInfo image_descriptor = {texture.sampler, texture.view, texture.image_layout}; + VkWriteDescriptorSet write_descriptor_set = + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &image_descriptor); vkUpdateDescriptorSets(get_device().get_handle(), 1, &write_descriptor_set, 0, nullptr); } @@ -367,12 +365,8 @@ void TextureCompressionBasisu::draw() void TextureCompressionBasisu::generate_quad() { // Setup vertices for a single uv-mapped quad made from two triangles - std::vector vertices = - { - {{1.5f, 1.0f, 0.0f}, {1.0f, 1.0f}}, - {{-1.5f, 1.0f, 0.0f}, {0.0f, 1.0f}}, - {{-1.5f, -1.0f, 0.0f}, {0.0f, 0.0f}}, - {{1.5f, -1.0f, 0.0f}, {1.0f, 0.0f}}}; + std::vector vertices = { + {{1.5f, 1.0f, 0.0f}, {1.0f, 1.0f}}, {{-1.5f, 1.0f, 0.0f}, {0.0f, 1.0f}}, {{-1.5f, -1.0f, 0.0f}, {0.0f, 0.0f}}, {{1.5f, -1.0f, 0.0f}, {1.0f, 0.0f}}}; // Setup indices std::vector indices = {0, 1, 2, 2, 3, 0}; @@ -384,15 +378,11 @@ void TextureCompressionBasisu::generate_quad() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory // Vertex buffer - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); @@ -401,57 +391,36 @@ void TextureCompressionBasisu::generate_quad() void TextureCompressionBasisu::setup_descriptor_pool() { // Example uses one ubo and one image sampler - std::vector pool_sizes = - { - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), - vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; + std::vector pool_sizes = {vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1), + vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 2); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 2); VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } void TextureCompressionBasisu::setup_descriptor_set_layout() { - std::vector set_layout_bindings = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - // Binding 1 : Fragment shader image sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1)}; + std::vector set_layout_bindings = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Fragment shader image sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1)}; VkDescriptorSetLayoutCreateInfo descriptor_layout = - vkb::initializers::descriptor_set_layout_create_info( - set_layout_bindings.data(), - static_cast(set_layout_bindings.size())); + vkb::initializers::descriptor_set_layout_create_info(set_layout_bindings.data(), static_cast(set_layout_bindings.size())); VK_CHECK(vkCreateDescriptorSetLayout(get_device().get_handle(), &descriptor_layout, nullptr, &descriptor_set_layout)); - VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - &descriptor_set_layout, - 1); + VkPipelineLayoutCreateInfo pipeline_layout_create_info = vkb::initializers::pipeline_layout_create_info(&descriptor_set_layout, 1); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } void TextureCompressionBasisu::setup_descriptor_set() { - VkDescriptorSetAllocateInfo alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &descriptor_set_layout, - 1); + VkDescriptorSetAllocateInfo alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &descriptor_set_layout, 1); VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &alloc_info, &descriptor_set)); @@ -460,22 +429,17 @@ void TextureCompressionBasisu::setup_descriptor_set() // Setup a descriptor image info for the current texture to be used as a combined image sampler VkDescriptorImageInfo image_descriptor = {texture.sampler, texture.view, texture.image_layout}; - std::vector write_descriptor_sets = - { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &buffer_descriptor), - // Binding 1 : Fragment shader texture sampler - // Fragment shader: layout (binding = 1) uniform sampler2D samplerColor; - vkb::initializers::write_descriptor_set( - descriptor_set, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // The descriptor set will use a combined image sampler (sampler and image could be split) - 1, // Shader binding point 1 - &image_descriptor) // Pointer to the descriptor image for our texture - }; + std::vector write_descriptor_sets = { + // Binding 0 : Vertex shader uniform buffer + vkb::initializers::write_descriptor_set(descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor), + // Binding 1 : Fragment shader texture sampler + // Fragment shader: layout (binding = 1) uniform sampler2D samplerColor; + vkb::initializers::write_descriptor_set( + descriptor_set, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // The descriptor set will use a combined image sampler (sampler and image could be split) + 1, // Shader binding point 1 + &image_descriptor) // Pointer to the descriptor image for our texture + }; vkUpdateDescriptorSets(get_device().get_handle(), static_cast(write_descriptor_sets.size()), write_descriptor_sets.data(), 0, NULL); } @@ -483,52 +447,27 @@ void TextureCompressionBasisu::setup_descriptor_set() void TextureCompressionBasisu::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_COUNTER_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages; @@ -550,11 +489,7 @@ void TextureCompressionBasisu::prepare_pipelines() vertex_input_state.vertexAttributeDescriptionCount = static_cast(vertex_input_attributes.size()); vertex_input_state.pVertexAttributeDescriptions = vertex_input_attributes.data(); - VkGraphicsPipelineCreateInfo pipeline_create_info = - vkb::initializers::pipeline_create_info( - pipeline_layout, - render_pass, - 0); + VkGraphicsPipelineCreateInfo pipeline_create_info = vkb::initializers::pipeline_create_info(pipeline_layout, render_pass, 0); pipeline_create_info.pVertexInputState = &vertex_input_state; pipeline_create_info.pInputAssemblyState = &input_assembly_state; @@ -574,10 +509,7 @@ void TextureCompressionBasisu::prepare_pipelines() void TextureCompressionBasisu::prepare_uniform_buffers() { // Vertex shader uniform buffer block - uniform_buffer_vs = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer_vs = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); } @@ -602,14 +534,8 @@ bool TextureCompressionBasisu::prepare(const vkb::ApplicationOptions &options) return false; } get_available_target_formats(); - texture_file_names = {"kodim23_UASTC.ktx2", - "kodim23_ETC1S.ktx2", - "kodim20_UASTC.ktx2", - "kodim20_ETC1S.ktx2", - "kodim05_UASTC.ktx2", - "kodim05_ETC1S.ktx2", - "kodim03_UASTC.ktx2", - "kodim03_ETC1S.ktx2"}; + texture_file_names = {"kodim23_UASTC.ktx2", "kodim23_ETC1S.ktx2", "kodim20_UASTC.ktx2", "kodim20_ETC1S.ktx2", + "kodim05_UASTC.ktx2", "kodim05_ETC1S.ktx2", "kodim03_UASTC.ktx2", "kodim03_ETC1S.ktx2"}; transcode_texture(texture_file_names[selected_input_texture], available_target_formats[selected_transcode_target_format]); generate_quad(); prepare_uniform_buffers(); diff --git a/samples/performance/texture_compression_basisu/texture_compression_basisu.h b/samples/performance/texture_compression_basisu/texture_compression_basisu.h index 45d0ec2508..72f91a6c52 100644 --- a/samples/performance/texture_compression_basisu/texture_compression_basisu.h +++ b/samples/performance/texture_compression_basisu/texture_compression_basisu.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2025, Sascha Willems +/* Copyright (c) 2021-2026, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * @@ -37,7 +37,8 @@ class TextureCompressionBasisu : public ApiVulkanSample }; // Contains all Vulkan objects that are required to store and use a texture - // Note that this repository contains a texture class (vulkan_texture.h) that encapsulates texture loading functionality in a class that is used in subsequent demos + // Note that this repository contains a texture class (vulkan_texture.h) that encapsulates texture loading functionality in a class that is used in + // subsequent demos struct Texture { VkSampler sampler; diff --git a/samples/performance/texture_compression_comparison/texture_compression_comparison.cpp b/samples/performance/texture_compression_comparison/texture_compression_comparison.cpp index 089083ba12..7da73ad1c4 100644 --- a/samples/performance/texture_compression_comparison/texture_compression_comparison.cpp +++ b/samples/performance/texture_compression_comparison/texture_compression_comparison.cpp @@ -108,9 +108,7 @@ void TextureCompressionComparison::draw_gui() } std::vector name_pointers(gui_texture_names.size()); - std::transform(gui_texture_names.cbegin(), gui_texture_names.cend(), name_pointers.begin(), [](const std::string &in) { - return in.c_str(); - }); + std::transform(gui_texture_names.cbegin(), gui_texture_names.cend(), name_pointers.begin(), [](const std::string &in) { return in.c_str(); }); get_gui().show_options_window([this, &name_pointers]() { if (ImGui::Combo("Compressed Format", ¤t_gui_format, name_pointers.data(), static_cast(name_pointers.size()))) @@ -139,36 +137,12 @@ void TextureCompressionComparison::draw_gui() const std::vector &TextureCompressionComparison::get_texture_formats() { static std::vector formats = { - CompressedTexture_t{nullptr, - "", - VK_FORMAT_R8G8B8A8_SRGB, - KTX_TTF_RGBA32, - "KTX_TTF_RGBA32", - "RGBA 32", - true}, - CompressedTexture_t{&VkPhysicalDeviceFeatures::textureCompressionBC, - "", - VK_FORMAT_BC7_SRGB_BLOCK, - KTX_TTF_BC7_RGBA, - "KTX_TTF_BC7_RGBA", - "BC7"}, - CompressedTexture_t{&VkPhysicalDeviceFeatures::textureCompressionBC, - "", - VK_FORMAT_BC3_SRGB_BLOCK, - KTX_TTF_BC3_RGBA, - "KTX_TTF_BC3_RGBA", - "BC3"}, - CompressedTexture_t{&VkPhysicalDeviceFeatures::textureCompressionASTC_LDR, - "", - VK_FORMAT_ASTC_4x4_SRGB_BLOCK, - KTX_TTF_ASTC_4x4_RGBA, - "KTX_TTF_ASTC_4x4_RGBA", - "ASTC 4x4"}, - CompressedTexture_t{&VkPhysicalDeviceFeatures::textureCompressionETC2, - "", - VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK, - KTX_TTF_ETC2_RGBA, - "KTX_TTF_ETC2_RGBA", + CompressedTexture_t{nullptr, "", VK_FORMAT_R8G8B8A8_SRGB, KTX_TTF_RGBA32, "KTX_TTF_RGBA32", "RGBA 32", true}, + CompressedTexture_t{&VkPhysicalDeviceFeatures::textureCompressionBC, "", VK_FORMAT_BC7_SRGB_BLOCK, KTX_TTF_BC7_RGBA, "KTX_TTF_BC7_RGBA", "BC7"}, + CompressedTexture_t{&VkPhysicalDeviceFeatures::textureCompressionBC, "", VK_FORMAT_BC3_SRGB_BLOCK, KTX_TTF_BC3_RGBA, "KTX_TTF_BC3_RGBA", "BC3"}, + CompressedTexture_t{&VkPhysicalDeviceFeatures::textureCompressionASTC_LDR, "", VK_FORMAT_ASTC_4x4_SRGB_BLOCK, KTX_TTF_ASTC_4x4_RGBA, + "KTX_TTF_ASTC_4x4_RGBA", "ASTC 4x4"}, + CompressedTexture_t{&VkPhysicalDeviceFeatures::textureCompressionETC2, "", VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK, KTX_TTF_ETC2_RGBA, "KTX_TTF_ETC2_RGBA", "ETC2"}}; return formats; } @@ -211,7 +185,8 @@ void TextureCompressionComparison::create_subpass() { vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_sub_pass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); + auto scene_sub_pass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_sub_pass)); @@ -219,7 +194,8 @@ void TextureCompressionComparison::create_subpass() set_render_pipeline(std::move(render_pipeline)); } -TextureCompressionComparison::TextureBenchmark TextureCompressionComparison::update_textures(const TextureCompressionComparison::CompressedTexture_t &new_format) +TextureCompressionComparison::TextureBenchmark + TextureCompressionComparison::update_textures(const TextureCompressionComparison::CompressedTexture_t &new_format) { TextureBenchmark benchmark; std::unordered_set visited; @@ -265,7 +241,8 @@ class CompressedImage : public vkb::sg::Image std::unique_ptr TextureCompressionComparison::create_image(ktxTexture2 *ktx_texture, const std::string &name) { - std::unique_ptr staging_buffer = std::make_unique(get_device(), ktx_texture->dataSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); + std::unique_ptr staging_buffer = + std::make_unique(get_device(), ktx_texture->dataSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); memcpy(staging_buffer->map(), ktx_texture->pData, ktx_texture->dataSize); const auto vk_format = static_cast(ktx_texture->vkFormat); @@ -310,7 +287,8 @@ std::unique_ptr TextureCompressionComparison::create_image(ktxTe vkb::image_layout_transition(command_buffer, image, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, subresource_range); - vkCmdCopyBufferToImage(command_buffer, staging_buffer->get_handle(), image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast(buffer_copies.size()), buffer_copies.data()); + vkCmdCopyBufferToImage(command_buffer, staging_buffer->get_handle(), image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + static_cast(buffer_copies.size()), buffer_copies.data()); vkb::image_layout_transition(command_buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, subresource_range); @@ -319,7 +297,8 @@ std::unique_ptr TextureCompressionComparison::create_image(ktxTe return image_out; } -std::pair, TextureCompressionComparison::TextureBenchmark> TextureCompressionComparison::compress(const std::string &filename, TextureCompressionComparison::CompressedTexture_t texture_format, const std::string &name) +std::pair, TextureCompressionComparison::TextureBenchmark> TextureCompressionComparison::compress( + const std::string &filename, TextureCompressionComparison::CompressedTexture_t texture_format, const std::string &name) { ktxTexture2 *ktx_texture{nullptr}; KTX_CHECK(ktxTexture2_CreateFromNamedFile(filename.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktx_texture)); diff --git a/samples/performance/texture_compression_comparison/texture_compression_comparison.h b/samples/performance/texture_compression_comparison/texture_compression_comparison.h index a2271859b3..312c128160 100644 --- a/samples/performance/texture_compression_comparison/texture_compression_comparison.h +++ b/samples/performance/texture_compression_comparison/texture_compression_comparison.h @@ -1,4 +1,4 @@ -/* Copyright (c) 2021-2024, Holochip +/* Copyright (c) 2021-2026, Holochip * * SPDX-License-Identifier: Apache-2.0 * @@ -65,20 +65,21 @@ class TextureCompressionComparison : public vkb::VulkanSampleC }; private: - static const std::vector &get_texture_formats(); - bool is_texture_format_supported(const CompressedTexture_t &format); - void load_assets(); - void create_subpass(); - TextureBenchmark update_textures(const CompressedTexture_t &new_format); - std::unique_ptr create_image(ktxTexture2 *ktx_texture, const std::string &name); - std::pair, TextureBenchmark> compress(const std::string &filename, CompressedTexture_t texture_format, const std::string &name); - std::vector gui_texture_names; - std::unordered_map texture_raw_data; - std::vector> textures; - vkb::sg::Camera *camera{VK_NULL_HANDLE}; - TextureBenchmark current_benchmark{}; - int current_format = 0, current_gui_format = 0; - bool require_redraw = true; + static const std::vector &get_texture_formats(); + bool is_texture_format_supported(const CompressedTexture_t &format); + void load_assets(); + void create_subpass(); + TextureBenchmark update_textures(const CompressedTexture_t &new_format); + std::unique_ptr create_image(ktxTexture2 *ktx_texture, const std::string &name); + std::pair, TextureBenchmark> + compress(const std::string &filename, CompressedTexture_t texture_format, const std::string &name); + std::vector gui_texture_names; + std::unordered_map texture_raw_data; + std::vector> textures; + vkb::sg::Camera *camera{VK_NULL_HANDLE}; + TextureBenchmark current_benchmark{}; + int current_format = 0, current_gui_format = 0; + bool require_redraw = true; }; std::unique_ptr create_texture_compression_comparison(); diff --git a/samples/performance/wait_idle/wait_idle.cpp b/samples/performance/wait_idle/wait_idle.cpp index 2caaa87230..3918d30e49 100644 --- a/samples/performance/wait_idle/wait_idle.cpp +++ b/samples/performance/wait_idle/wait_idle.cpp @@ -50,8 +50,9 @@ bool WaitIdle::prepare(const vkb::ApplicationOptions &options) // Example Scene Render Pipeline vkb::ShaderSource vert_shader("base.vert.spv"); vkb::ShaderSource frag_shader("base.frag.spv"); - auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), get_scene(), *camera); - auto render_pipeline = std::make_unique(); + auto scene_subpass = std::make_unique(get_render_context(), std::move(vert_shader), std::move(frag_shader), + get_scene(), *camera); + auto render_pipeline = std::make_unique(); render_pipeline->add_subpass(std::move(scene_subpass)); set_render_pipeline(std::move(render_pipeline)); @@ -93,7 +94,8 @@ void WaitIdle::draw_gui() uint32_t lines = landscape ? 1 : 2; get_gui().show_options_window( - /* body = */ [&]() { + /* body = */ + [&]() { ImGui::RadioButton("Wait Idle", &wait_idle_enabled, 1); if (landscape) { diff --git a/samples/tooling/profiles/profiles.cpp b/samples/tooling/profiles/profiles.cpp index fc8c8ae965..193af4ae1b 100644 --- a/samples/tooling/profiles/profiles.cpp +++ b/samples/tooling/profiles/profiles.cpp @@ -122,7 +122,8 @@ std::unique_ptr Profiles::create_device(vkb::core::PhysicalD if (result != VK_SUCCESS) { - throw vkb::VulkanException{result, "Could not create device with the selected profile. The device may not support all features required by this profile!"}; + throw vkb::VulkanException{result, + "Could not create device with the selected profile. The device may not support all features required by this profile!"}; } // Post device setup required for the framework @@ -175,8 +176,9 @@ std::unique_ptr Profiles::create_instance() VK_CHECK(vkEnumerateInstanceExtensionProperties(nullptr, &instance_extension_count, available_instance_extensions.data())); // If VK_KHR_portability_enumeration is available in the implementation, then we must enable the extension - if (std::ranges::any_of(available_instance_extensions, - [](VkExtensionProperties const &extension) { return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; })) + if (std::ranges::any_of(available_instance_extensions, [](VkExtensionProperties const &extension) { + return strcmp(extension.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0; + })) { enabled_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME); create_info.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR; @@ -200,7 +202,8 @@ std::unique_ptr Profiles::create_instance() if (result != VK_SUCCESS) { - throw vkb::VulkanException{result, "Could not create instance with the selected profile. The instance may not support all features required by this profile!"}; + throw vkb::VulkanException{result, + "Could not create instance with the selected profile. The instance may not support all features required by this profile!"}; } volkLoadInstance(vulkan_instance); @@ -236,7 +239,8 @@ void Profiles::generate_textures() image_view.subresourceRange.baseArrayLayer = 0; image_view.subresourceRange.layerCount = 1; - auto staging_buffer = vkb::core::BufferC::create_staging_buffer(get_device(), image_info.extent.width * image_info.extent.height * sizeof(uint32_t), nullptr); + auto staging_buffer = + vkb::core::BufferC::create_staging_buffer(get_device(), image_info.extent.width * image_info.extent.height * sizeof(uint32_t), nullptr); textures.resize(32); for (size_t i = 0; i < textures.size(); i++) @@ -245,8 +249,9 @@ void Profiles::generate_textures() VkMemoryAllocateInfo memory_allocation_info = vkb::initializers::memory_allocate_info(); VkMemoryRequirements memory_requirements; vkGetImageMemoryRequirements(get_device().get_handle(), textures[i].image, &memory_requirements); - memory_allocation_info.allocationSize = memory_requirements.size; - memory_allocation_info.memoryTypeIndex = get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + memory_allocation_info.allocationSize = memory_requirements.size; + memory_allocation_info.memoryTypeIndex = + get_device().get_gpu().get_memory_type(memory_requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK(vkAllocateMemory(get_device().get_handle(), &memory_allocation_info, nullptr, &textures[i].memory)); VK_CHECK(vkBindImageMemory(get_device().get_handle(), textures[i].image, textures[i].memory, 0)); image_view.image = textures[i].image; @@ -318,56 +323,37 @@ void Profiles::generate_cubes() for (uint32_t i = 0; i < count; i++) { // Get a random texture index that the shader will sample from via the vertex attribute - const auto texture_index = [&rndDist, &rndEngine]() { - return rndDist(rndEngine); - }; + const auto texture_index = [&rndDist, &rndEngine]() { return rndDist(rndEngine); }; // Push vertices to buffer float pos = 2.5f * i - (count * 2.5f / 2.0f); const std::vector cube = { - {{-1.0f + pos, -1.0f, 1.0f}, {0.0f, 0.0f}, texture_index()}, - {{1.0f + pos, -1.0f, 1.0f}, {1.0f, 0.0f}, texture_index()}, - {{1.0f + pos, 1.0f, 1.0f}, {1.0f, 1.0f}, texture_index()}, - {{-1.0f + pos, 1.0f, 1.0f}, {0.0f, 1.0f}, texture_index()}, - - {{1.0f + pos, 1.0f, 1.0f}, {0.0f, 0.0f}, texture_index()}, - {{1.0f + pos, 1.0f, -1.0f}, {1.0f, 0.0f}, texture_index()}, - {{1.0f + pos, -1.0f, -1.0f}, {1.0f, 1.0f}, texture_index()}, - {{1.0f + pos, -1.0f, 1.0f}, {0.0f, 1.0f}, texture_index()}, - - {{-1.0f + pos, -1.0f, -1.0f}, {0.0f, 0.0f}, texture_index()}, - {{1.0f + pos, -1.0f, -1.0f}, {1.0f, 0.0f}, texture_index()}, - {{1.0f + pos, 1.0f, -1.0f}, {1.0f, 1.0f}, texture_index()}, - {{-1.0f + pos, 1.0f, -1.0f}, {0.0f, 1.0f}, texture_index()}, - - {{-1.0f + pos, -1.0f, -1.0f}, {0.0f, 0.0f}, texture_index()}, - {{-1.0f + pos, -1.0f, 1.0f}, {1.0f, 0.0f}, texture_index()}, - {{-1.0f + pos, 1.0f, 1.0f}, {1.0f, 1.0f}, texture_index()}, - {{-1.0f + pos, 1.0f, -1.0f}, {0.0f, 1.0f}, texture_index()}, - - {{1.0f + pos, 1.0f, 1.0f}, {0.0f, 0.0f}, texture_index()}, - {{-1.0f + pos, 1.0f, 1.0f}, {1.0f, 0.0f}, texture_index()}, - {{-1.0f + pos, 1.0f, -1.0f}, {1.0f, 1.0f}, texture_index()}, - {{1.0f + pos, 1.0f, -1.0f}, {0.0f, 1.0f}, texture_index()}, - - {{-1.0f + pos, -1.0f, -1.0f}, {0.0f, 0.0f}, texture_index()}, - {{1.0f + pos, -1.0f, -1.0f}, {1.0f, 0.0f}, texture_index()}, - {{1.0f + pos, -1.0f, 1.0f}, {1.0f, 1.0f}, texture_index()}, - {{-1.0f + pos, -1.0f, 1.0f}, {0.0f, 1.0f}, texture_index()}, + {{-1.0f + pos, -1.0f, 1.0f}, {0.0f, 0.0f}, texture_index()}, {{1.0f + pos, -1.0f, 1.0f}, {1.0f, 0.0f}, texture_index()}, + {{1.0f + pos, 1.0f, 1.0f}, {1.0f, 1.0f}, texture_index()}, {{-1.0f + pos, 1.0f, 1.0f}, {0.0f, 1.0f}, texture_index()}, + + {{1.0f + pos, 1.0f, 1.0f}, {0.0f, 0.0f}, texture_index()}, {{1.0f + pos, 1.0f, -1.0f}, {1.0f, 0.0f}, texture_index()}, + {{1.0f + pos, -1.0f, -1.0f}, {1.0f, 1.0f}, texture_index()}, {{1.0f + pos, -1.0f, 1.0f}, {0.0f, 1.0f}, texture_index()}, + + {{-1.0f + pos, -1.0f, -1.0f}, {0.0f, 0.0f}, texture_index()}, {{1.0f + pos, -1.0f, -1.0f}, {1.0f, 0.0f}, texture_index()}, + {{1.0f + pos, 1.0f, -1.0f}, {1.0f, 1.0f}, texture_index()}, {{-1.0f + pos, 1.0f, -1.0f}, {0.0f, 1.0f}, texture_index()}, + + {{-1.0f + pos, -1.0f, -1.0f}, {0.0f, 0.0f}, texture_index()}, {{-1.0f + pos, -1.0f, 1.0f}, {1.0f, 0.0f}, texture_index()}, + {{-1.0f + pos, 1.0f, 1.0f}, {1.0f, 1.0f}, texture_index()}, {{-1.0f + pos, 1.0f, -1.0f}, {0.0f, 1.0f}, texture_index()}, + + {{1.0f + pos, 1.0f, 1.0f}, {0.0f, 0.0f}, texture_index()}, {{-1.0f + pos, 1.0f, 1.0f}, {1.0f, 0.0f}, texture_index()}, + {{-1.0f + pos, 1.0f, -1.0f}, {1.0f, 1.0f}, texture_index()}, {{1.0f + pos, 1.0f, -1.0f}, {0.0f, 1.0f}, texture_index()}, + + {{-1.0f + pos, -1.0f, -1.0f}, {0.0f, 0.0f}, texture_index()}, {{1.0f + pos, -1.0f, -1.0f}, {1.0f, 0.0f}, texture_index()}, + {{1.0f + pos, -1.0f, 1.0f}, {1.0f, 1.0f}, texture_index()}, {{-1.0f + pos, -1.0f, 1.0f}, {0.0f, 1.0f}, texture_index()}, }; for (auto &vertex : cube) { vertices.push_back(vertex); } // Push indices to buffer - const std::vector cubeIndices = { - 0, 1, 2, 0, 2, 3, - 4, 5, 6, 4, 6, 7, - 8, 9, 10, 8, 10, 11, - 12, 13, 14, 12, 14, 15, - 16, 17, 18, 16, 18, 19, - 20, 21, 22, 20, 22, 23}; + const std::vector cubeIndices = {0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, + 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23}; for (auto &index : cubeIndices) { indices.push_back(index + static_cast(vertices.size())); @@ -381,15 +367,11 @@ void Profiles::generate_cubes() // Create buffers // For the sake of simplicity we won't stage the vertex data to the gpu memory - vertex_buffer = std::make_unique(get_device(), - vertex_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, + vertex_buffer = std::make_unique(get_device(), vertex_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); vertex_buffer->update(vertices.data(), vertex_buffer_size); - index_buffer = std::make_unique(get_device(), - index_buffer_size, - VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, + index_buffer = std::make_unique(get_device(), index_buffer_size, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); index_buffer->update(indices.data(), index_buffer_size); } @@ -453,10 +435,7 @@ void Profiles::setup_descriptor_pool() vkb::initializers::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, static_cast(textures.size()))}; VkDescriptorPoolCreateInfo descriptor_pool_create_info = - vkb::initializers::descriptor_pool_create_info( - static_cast(pool_sizes.size()), - pool_sizes.data(), - 3); + vkb::initializers::descriptor_pool_create_info(static_cast(pool_sizes.size()), pool_sizes.data(), 3); descriptor_pool_create_info.flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT; VK_CHECK(vkCreateDescriptorPool(get_device().get_handle(), &descriptor_pool_create_info, nullptr, &descriptor_pool)); } @@ -473,26 +452,17 @@ void Profiles::setup_descriptor_set_layout() VkDescriptorSetLayoutBindingFlagsCreateInfoEXT descriptor_set_layout_binding_flags{}; descriptor_set_layout_binding_flags.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO_EXT; descriptor_set_layout_binding_flags.bindingCount = 2; - std::vector descriptor_binding_flags = { - 0, - VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT}; - descriptor_set_layout_binding_flags.pBindingFlags = descriptor_binding_flags.data(); + std::vector descriptor_binding_flags = {0, VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT}; + descriptor_set_layout_binding_flags.pBindingFlags = descriptor_binding_flags.data(); descriptor_layout_create_info.pNext = &descriptor_set_layout_binding_flags; // Set layout for the uniform buffer and the image - set_layout_bindings = { - // Binding 0 : Vertex shader uniform buffer - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - VK_SHADER_STAGE_VERTEX_BIT, - 0), - // Binding 1 : Fragment shader combined image and sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 1, - static_cast(textures.size()))}; + set_layout_bindings = {// Binding 0 : Vertex shader uniform buffer + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0), + // Binding 1 : Fragment shader combined image and sampler + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1, + static_cast(textures.size()))}; descriptor_layout_create_info.bindingCount = static_cast(set_layout_bindings.size()); descriptor_layout_create_info.pBindings = set_layout_bindings.data(); descriptor_layout_create_info.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT; @@ -501,11 +471,7 @@ void Profiles::setup_descriptor_set_layout() // Set layout for the samplers set_layout_bindings = { // Binding 0: Fragment shader sampler - vkb::initializers::descriptor_set_layout_binding( - VK_DESCRIPTOR_TYPE_SAMPLER, - VK_SHADER_STAGE_FRAGMENT_BIT, - 0, - static_cast(textures.size()))}; + vkb::initializers::descriptor_set_layout_binding(VK_DESCRIPTOR_TYPE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 0, static_cast(textures.size()))}; descriptor_layout_create_info.bindingCount = static_cast(set_layout_bindings.size()); descriptor_layout_create_info.pBindings = set_layout_bindings.data(); descriptor_layout_create_info.pNext = nullptr; @@ -515,9 +481,7 @@ void Profiles::setup_descriptor_set_layout() // Set layout for the base descriptors in set 0 and set layout for the sampler descriptors in set 1 std::vector set_layouts = {base_descriptor_set_layout, sampler_descriptor_set_layout}; VkPipelineLayoutCreateInfo pipeline_layout_create_info = - vkb::initializers::pipeline_layout_create_info( - set_layouts.data(), - static_cast(set_layouts.size())); + vkb::initializers::pipeline_layout_create_info(set_layouts.data(), static_cast(set_layouts.size())); VK_CHECK(vkCreatePipelineLayout(get_device().get_handle(), &pipeline_layout_create_info, nullptr, &pipeline_layout)); } @@ -527,17 +491,13 @@ void Profiles::setup_descriptor_set() VkDescriptorSetAllocateInfo descriptor_set_alloc_info{}; // Descriptors set for the uniform buffer and the image - descriptor_set_alloc_info = - vkb::initializers::descriptor_set_allocate_info( - descriptor_pool, - &base_descriptor_set_layout, - 1); + descriptor_set_alloc_info = vkb::initializers::descriptor_set_allocate_info(descriptor_pool, &base_descriptor_set_layout, 1); VkDescriptorSetVariableDescriptorCountAllocateInfoEXT variableDescriptorCountAllocInfo = {}; uint32_t variableDescCounts[] = {static_cast(textures.size())}; - variableDescriptorCountAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO_EXT; - variableDescriptorCountAllocInfo.descriptorSetCount = 1; - variableDescriptorCountAllocInfo.pDescriptorCounts = variableDescCounts; + variableDescriptorCountAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO_EXT; + variableDescriptorCountAllocInfo.descriptorSetCount = 1; + variableDescriptorCountAllocInfo.pDescriptorCounts = variableDescCounts; descriptor_set_alloc_info.pNext = &variableDescriptorCountAllocInfo; VK_CHECK(vkAllocateDescriptorSets(get_device().get_handle(), &descriptor_set_alloc_info, &base_descriptor_set)); @@ -552,11 +512,7 @@ void Profiles::setup_descriptor_set() std::vector write_descriptor_sets(2); // Binding 0 : Vertex shader uniform buffer - write_descriptor_sets[0] = vkb::initializers::write_descriptor_set( - base_descriptor_set, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - 0, - &buffer_descriptor); + write_descriptor_sets[0] = vkb::initializers::write_descriptor_set(base_descriptor_set, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &buffer_descriptor); // Binding 1 : Fragment shader sampled image // Put all images into a single array @@ -585,52 +541,27 @@ void Profiles::setup_descriptor_set() void Profiles::prepare_pipelines() { VkPipelineInputAssemblyStateCreateInfo input_assembly_state = - vkb::initializers::pipeline_input_assembly_state_create_info( - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, - 0, - VK_FALSE); + vkb::initializers::pipeline_input_assembly_state_create_info(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterization_state = - vkb::initializers::pipeline_rasterization_state_create_info( - VK_POLYGON_MODE_FILL, - VK_CULL_MODE_NONE, - VK_FRONT_FACE_CLOCKWISE, - 0); - - VkPipelineColorBlendAttachmentState blend_attachment_state = - vkb::initializers::pipeline_color_blend_attachment_state( - 0xf, - VK_FALSE); - - VkPipelineColorBlendStateCreateInfo color_blend_state = - vkb::initializers::pipeline_color_blend_state_create_info( - 1, - &blend_attachment_state); + vkb::initializers::pipeline_rasterization_state_create_info(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE, 0); + + VkPipelineColorBlendAttachmentState blend_attachment_state = vkb::initializers::pipeline_color_blend_attachment_state(0xf, VK_FALSE); + + VkPipelineColorBlendStateCreateInfo color_blend_state = vkb::initializers::pipeline_color_blend_state_create_info(1, &blend_attachment_state); // Note: Using reversed depth-buffer for increased precision, so Greater depth values are kept VkPipelineDepthStencilStateCreateInfo depth_stencil_state = - vkb::initializers::pipeline_depth_stencil_state_create_info( - VK_TRUE, - VK_TRUE, - VK_COMPARE_OP_GREATER); + vkb::initializers::pipeline_depth_stencil_state_create_info(VK_TRUE, VK_TRUE, VK_COMPARE_OP_GREATER); - VkPipelineViewportStateCreateInfo viewport_state = - vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); + VkPipelineViewportStateCreateInfo viewport_state = vkb::initializers::pipeline_viewport_state_create_info(1, 1, 0); - VkPipelineMultisampleStateCreateInfo multisample_state = - vkb::initializers::pipeline_multisample_state_create_info( - VK_SAMPLE_COUNT_1_BIT, - 0); + VkPipelineMultisampleStateCreateInfo multisample_state = vkb::initializers::pipeline_multisample_state_create_info(VK_SAMPLE_COUNT_1_BIT, 0); - std::vector dynamic_state_enables = { - VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_SCISSOR}; + std::vector dynamic_state_enables = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; VkPipelineDynamicStateCreateInfo dynamic_state = - vkb::initializers::pipeline_dynamic_state_create_info( - dynamic_state_enables.data(), - static_cast(dynamic_state_enables.size()), - 0); + vkb::initializers::pipeline_dynamic_state_create_info(dynamic_state_enables.data(), static_cast(dynamic_state_enables.size()), 0); // Load shaders std::array shader_stages{}; @@ -672,10 +603,7 @@ void Profiles::prepare_pipelines() void Profiles::prepare_uniform_buffers() { // Vertex shader uniform buffer block - uniform_buffer_vs = std::make_unique(get_device(), - sizeof(ubo_vs), - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, - VMA_MEMORY_USAGE_CPU_TO_GPU); + uniform_buffer_vs = std::make_unique(get_device(), sizeof(ubo_vs), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VMA_MEMORY_USAGE_CPU_TO_GPU); update_uniform_buffers(); }