Basic GUI

This commit is contained in:
Guillaume Meunier
2024-01-28 11:33:35 +01:00
parent a7bd88aa6c
commit d84095e1ea
42 changed files with 1970 additions and 363 deletions
+5 -2
View File
@@ -23,6 +23,7 @@
#include <fastgltf/types.hpp>
#include <fastgltf/tools.hpp>
#include "vk/allocation.h"
#include "utils/alignment.h"
class gpu_buffer
{
@@ -33,7 +34,7 @@ class gpu_buffer
size_t add(size_t alignment, const void * data_to_add, size_t size)
{
size_t offset = ((bytes.size() + alignment - 1) / alignment) * alignment;
size_t offset = utils::align_up(alignment, bytes.size());
bytes.resize(offset + size);
@@ -121,7 +122,9 @@ public:
.usage = usage},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO}};
.usage = VMA_MEMORY_USAGE_AUTO},
"gpu_buffer::copy_to_gpu"
};
memcpy(gpu_buffer.map(), bytes.data(), bytes.size());
gpu_buffer.unmap();
+2 -2
View File
@@ -156,7 +156,7 @@ void image_loader::do_load(vk::raii::Device & device, vk::raii::CommandBuffer &
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
}, "image_loader::do_load (staging)"};
memcpy(staging_buffer.map(), pixels, byte_size);
staging_buffer.unmap();
@@ -176,7 +176,7 @@ void image_loader::do_load(vk::raii::Device & device, vk::raii::CommandBuffer &
VmaAllocationCreateInfo{
.flags = 0,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
}, "image_loader::do_load"};
// Transition all mipmap levels layout to eTransferDstOptimal
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
+206 -83
View File
@@ -20,6 +20,7 @@
#include "imgui_impl.h"
#include "application.h"
#include "asset.h"
#include "openxr/openxr.h"
#include "utils/ranges.h"
#include "vulkan/vulkan_enums.hpp"
@@ -43,7 +44,7 @@
* struct ImGui_ImplVulkanH_Window
*/
static vk::raii::RenderPass create_renderpass(vk::raii::Device& device, vk::Format format, vk::ImageLayout final_layout, bool clear)
static vk::raii::RenderPass create_renderpass(vk::raii::Device& device, vk::Format format, bool clear)
{
vk::AttachmentDescription attachment{
.format = format,
@@ -53,7 +54,7 @@ static vk::raii::RenderPass create_renderpass(vk::raii::Device& device, vk::Form
.stencilLoadOp = vk::AttachmentLoadOp::eDontCare,
.stencilStoreOp = vk::AttachmentStoreOp::eDontCare,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = final_layout,
.finalLayout = vk::ImageLayout::eTransferSrcOptimal,
};
vk::AttachmentReference color_attachment{
@@ -138,7 +139,7 @@ imgui_context::imgui_viewport::imgui_viewport(vk::raii::Device& device, vk::raii
device(device),
size(size)
{
uint32_t num_mipmaps = 1;
num_mipmaps = std::floor(std::log2(std::max(size.width, size.height))) + 1;
for(auto& frame:frames)
{
@@ -155,7 +156,7 @@ imgui_context::imgui_viewport::imgui_viewport(vk::raii::Device& device, vk::raii
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled,
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst,
.initialLayout = vk::ImageLayout::eUndefined,
},
VmaAllocationCreateInfo{
@@ -163,7 +164,21 @@ imgui_context::imgui_viewport::imgui_viewport(vk::raii::Device& device, vk::raii
}
);
frame.image_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{
// Only 1 mipmap level for the framebuffer view
frame.image_view_framebuffer = vk::raii::ImageView(device, vk::ImageViewCreateInfo{
.image = (vk::Image)frame.image,
.viewType = vk::ImageViewType::e2D,
.format = format,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
}
});
frame.image_view_texture = vk::raii::ImageView(device, vk::ImageViewCreateInfo{
.image = (vk::Image)frame.image,
.viewType = vk::ImageViewType::e2D,
.format = format,
@@ -179,7 +194,7 @@ imgui_context::imgui_viewport::imgui_viewport(vk::raii::Device& device, vk::raii
frame.framebuffer = vk::raii::Framebuffer(device, vk::FramebufferCreateInfo{
.renderPass = renderpass,
.attachmentCount = 1,
.pAttachments = &*frame.image_view,
.pAttachments = &*frame.image_view_framebuffer,
.width = size.width,
.height = size.height,
.layers = 1,
@@ -194,7 +209,7 @@ imgui_context::imgui_viewport::imgui_viewport(vk::raii::Device& device, vk::raii
}
}
imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_index, vk::raii::Queue& queue, XrSpace world, std::span<controller> controllers_) :
imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_index, vk::raii::Queue& queue, XrSpace world, std::span<controller> controllers_, float resolution, glm::vec2 scale) :
device(device),
queue_family_index(queue_family_index),
queue(queue),
@@ -205,7 +220,7 @@ imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_ind
.poolSizeCount = pool_sizes.size(),
.pPoolSizes = pool_sizes.data(),
}),
renderpass(create_renderpass(device, vk::Format::eR8G8B8A8Unorm, vk::ImageLayout::eShaderReadOnlyOptimal, true)),
renderpass(create_renderpass(device, vk::Format::eR8G8B8A8Unorm, true)),
command_pool(device, vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient,
.queueFamilyIndex = queue_family_index,
@@ -218,15 +233,15 @@ imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_ind
for(const auto& i:controllers_)
controllers.emplace_back(i, controller_state{});
viewport = std::make_shared<imgui_viewport>(device, command_pool, *renderpass, vk::Extent2D{1000, 1000}, vk::Format::eR8G8B8A8Unorm);
vk::Extent2D extent{
(uint32_t)(resolution * scale.x),
(uint32_t)(resolution * scale.y)
};
ini_filename = application::get_config_path() / "imgui.ini";
io.IniFilename = ini_filename.c_str();
viewport = std::make_shared<imgui_viewport>(device, command_pool, *renderpass, extent, vk::Format::eR8G8B8A8Unorm);
viewport->scale = scale;
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
//ImGui::StyleColorsLight();
io.IniFilename = nullptr;
ImGui_ImplVulkan_InitInfo init_info = {
.Instance = *application::get_vulkan_instance(),
@@ -246,51 +261,50 @@ imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_ind
ImGui_ImplVulkan_Init(&init_info, *renderpass);
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
io.Fonts->AddFontDefault();
//io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != nullptr);
ImFontConfig config;
asset roboto("Roboto-Regular.ttf");
config.FontDataOwnedByAtlas = false;
io.Fonts->AddFontFromMemoryTTF(const_cast<std::byte*>(roboto.data()), roboto.size(), 45, &config);
large_font = io.Fonts->AddFontFromMemoryTTF(const_cast<std::byte*>(roboto.data()), roboto.size(), 90, &config);
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
//ImGui::StyleColorsLight();
ImGuiStyle& style = ImGui::GetStyle();
style.ScaleAllSizes(2.5f);
style.WindowPadding = { 50, 50 };
style.WindowBorderSize = 10; // Not scaled by ScaleAllSizes
style.WindowRounding = 25;
style.ItemSpacing = {50, 50};
style.FrameRounding = 10;
style.FramePadding = ImVec2(15, 10);
// TODO: scroll to drag https://github.com/ocornut/imgui/issues/3379
}
static float read_action_bool_or_float(imgui_context::controller::typed_action action)
void imgui_context::set_position(glm::vec3 position, glm::quat orientation)
{
assert(action.second == XR_ACTION_TYPE_BOOLEAN_INPUT || action.second == XR_ACTION_TYPE_FLOAT_INPUT);
float value = 0;
switch(action.second)
{
case XR_ACTION_TYPE_BOOLEAN_INPUT:
if (auto act = application::read_action_bool(action.first); act)
value = act->second;
break;
case XR_ACTION_TYPE_FLOAT_INPUT:
if (auto act = application::read_action_float(action.first); act)
value = act->second;
break;
default:
__builtin_unreachable();
}
return value;
auto& vp = *viewport;
vp.position = position;
vp.orientation = orientation;
}
void imgui_context::new_frame(XrTime display_time)
{
if (last_display_time)
io.DeltaTime = std::min((display_time - last_display_time) * 1e-9f, 0.1f);
last_display_time = display_time;
float scroll_scale = io.DeltaTime * 3;
size_t new_focused_controller = focused_controller;
std::vector<controller_state> new_states;
@@ -312,37 +326,39 @@ void imgui_context::new_frame(XrTime display_time)
new_state.active = false;
}
if (ctrl.squeeze.first)
if (ctrl.squeeze)
{
new_state.squeeze_value = read_action_bool_or_float(ctrl.squeeze);
auto squeeze = application::read_action_float(ctrl.squeeze).value_or(std::pair{0,0});
new_state.squeeze_value = squeeze.second;
// TODO tunable
if (new_state.squeeze_value < 0.5)
new_state.squeeze_clicked = false;
else if (new_state.squeeze_value > 0.8)
new_state.squeeze_clicked = true;
}
if (ctrl.trigger.first)
if (ctrl.trigger)
{
new_state.trigger_value = read_action_bool_or_float(ctrl.trigger);
auto trigger = application::read_action_float(ctrl.trigger).value_or(std::pair{0,0});
new_state.trigger_value = trigger.second;
// TODO tunable
if (new_state.trigger_value < 0.5)
new_state.trigger_clicked = false;
else if (new_state.trigger_value > 0.8)
new_state.trigger_clicked = true;
}
if (ctrl.scroll.first)
if (ctrl.scroll)
{
assert(ctrl.scroll.second == XR_ACTION_TYPE_VECTOR2F_INPUT);
if (auto act = application::read_action_vec2(ctrl.scroll.first); act)
new_state.scroll_value = { act->second.x, act->second.y };
if (auto act = application::read_action_vec2(ctrl.scroll); act)
new_state.scroll_value = { -act->second.x * scroll_scale, act->second.y * scroll_scale };
else
new_state.scroll_value = {0, 0};
}
if (new_state.squeeze_clicked || new_state.trigger_clicked || glm::length(new_state.scroll_value) > 0.1f)
if (new_state.squeeze_clicked || new_state.trigger_clicked || glm::length(new_state.scroll_value) > 0.01f)
{
new_focused_controller = index;
}
@@ -356,6 +372,7 @@ void imgui_context::new_frame(XrTime display_time)
{
// Focused controller changed: end the current click
io.AddMouseButtonEvent(0, false);
button_pressed = false;
}
std::optional<ImVec2> position;
@@ -367,19 +384,29 @@ void imgui_context::new_frame(XrTime display_time)
trigger = new_states[new_focused_controller].trigger_value;
auto scroll = new_states[new_focused_controller].scroll_value;
bool last_trigger = controllers[new_focused_controller].second.trigger_clicked;
if (position)
{
io.AddMousePosEvent(position->x, position->y);
bool last_trigger = controllers[new_focused_controller].second.trigger_clicked;
bool next_trigger = new_states[new_focused_controller].trigger_clicked;
button_pressed = new_states[new_focused_controller].trigger_clicked;
if (focused_change || last_trigger != next_trigger)
io.AddMouseButtonEvent(0, next_trigger);
if (focused_change || last_trigger != button_pressed)
{
io.AddMouseButtonEvent(0, button_pressed);
}
if (glm::length(scroll) > 0.1f)
if (glm::length(scroll) > 0.01f)
io.AddMouseWheelEvent(scroll.x, scroll.y);
}
else
{
if (last_trigger && !button_pressed)
{
io.AddMouseButtonEvent(0, button_pressed);
}
}
}
else
{
@@ -400,21 +427,19 @@ void imgui_context::new_frame(XrTime display_time)
io.DisplayFramebufferScale = ImVec2(1, 1);
// See ImGui_ImplSDL2_ProcessEvent
if (last_display_time)
io.DeltaTime = std::min((display_time - last_display_time) * 1e-9f, 0.1f);
last_display_time = display_time;
// io.AddMouseWheelEvent(wheel_x, wheel_y);
ImGui::NewFrame();
ImDrawList* draw_list = ImGui::GetForegroundDrawList();
if (position)
draw_list->AddCircle(*position, 30*(1-0.7*trigger), ImGui::GetColorU32(ImVec4(1, 0, 0, 0.8)), 20, 10);
{
ImU32 color_pressed = ImGui::GetColorU32(ImVec4(0, 0.2, 1, 0.8));
ImU32 color_unpressed = ImGui::GetColorU32(ImVec4(1, 1, 1, 0.8));
draw_list->AddCircleFilled(*position, 10, button_pressed ? color_pressed : color_unpressed);
draw_list->AddCircle(*position, 12, ImGui::GetColorU32(ImVec4(0,0,0,0.8)), 0, 4);
}
}
std::shared_ptr<vk::raii::ImageView> imgui_context::render()
@@ -453,6 +478,111 @@ std::shared_ptr<vk::raii::ImageView> imgui_context::render()
cb.endRenderPass();
// TODO: create mipmaps
// Create mipmaps
int width = vp.size.width;
int height = vp.size.height;
vk::ImageLayout prev_layout = vk::ImageLayout::eTransferSrcOptimal;
for(uint32_t level = 1; level < vp.num_mipmaps; level++)
{
int next_width = width > 1 ? width / 2 : 1;
int next_height = height > 1 ? height / 2 : 1;
// Transition source image layout to eTransferSrcOptimal and destination image layout to eTransferDstOptimal
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {},
{
vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eTransferWrite,
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
.oldLayout = prev_layout,
.newLayout = vk::ImageLayout::eTransferSrcOptimal,
.image = f.image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = level - 1,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eTransferWrite, // TODO
.dstAccessMask = vk::AccessFlagBits::eShaderRead, // TODO
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eTransferDstOptimal,
.image = f.image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = level,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
});
prev_layout = vk::ImageLayout::eTransferDstOptimal;
// Blit level n-1 to level n
cb.blitImage(f.image, vk::ImageLayout::eTransferSrcOptimal, f.image, vk::ImageLayout::eTransferDstOptimal,
vk::ImageBlit{
.srcSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = level - 1,
.baseArrayLayer = 0,
.layerCount = 1},
.srcOffsets = std::array{
vk::Offset3D{0, 0, 0},
vk::Offset3D{width, height, 1},
},
.dstSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = level,
.baseArrayLayer = 0,
.layerCount = 1
},
.dstOffsets = std::array{
vk::Offset3D{0, 0, 0},
vk::Offset3D{next_width, next_height, 1},
},
},
vk::Filter::eLinear);
// Transition source image layout to eShaderReadOnlyOptimal
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eTransferRead,
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
.oldLayout = vk::ImageLayout::eTransferSrcOptimal,
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.image = f.image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = level - 1,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
});
width = next_width;
height = next_height;
}
// Transition the last level to eShaderReadOnlyOptimal
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eTransferWrite,
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
.oldLayout = prev_layout,
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.image = f.image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = vp.num_mipmaps - 1,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
});
cb.end();
@@ -462,7 +592,7 @@ std::shared_ptr<vk::raii::ImageView> imgui_context::render()
}, *f.fence);
// Use the aliasing constructor
return std::shared_ptr<vk::raii::ImageView>{viewport, &vp.frames[vp.frameindex].image_view};
return std::shared_ptr<vk::raii::ImageView>{viewport, &vp.frames[vp.frameindex].image_view_texture};
}
imgui_context::~imgui_context()
@@ -481,11 +611,4 @@ imgui_context::~imgui_context()
ImGui_ImplVulkan_Shutdown();
ImGui::DestroyContext(context);
// ImGui_ImplSDL2_Shutdown();
// ImGui::DestroyContext();
// ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator);
// SDL_DestroyWindow(window);
// SDL_Quit();
}
+19 -7
View File
@@ -18,6 +18,7 @@
#pragma once
#include "render/scene_data.h"
#include <imgui.h>
#include <vulkan/vulkan_raii.hpp>
#include <glm/glm.hpp>
@@ -31,7 +32,8 @@ public:
struct imgui_frame
{
image_allocation image;
vk::raii::ImageView image_view = nullptr;
vk::raii::ImageView image_view_framebuffer = nullptr;
vk::raii::ImageView image_view_texture = nullptr;
vk::raii::Framebuffer framebuffer = nullptr;
vk::raii::CommandBuffer command_buffer = nullptr;
vk::raii::Fence fence = nullptr;
@@ -40,6 +42,8 @@ public:
struct imgui_viewport
{
static constexpr int frames_in_flight = 2;
uint32_t num_mipmaps;
std::array<imgui_frame, frames_in_flight> frames;
int frameindex = 0;
@@ -58,11 +62,10 @@ public:
struct controller
{
using typed_action = std::pair<XrAction, XrActionType>;
XrSpace aim;
typed_action trigger;
typed_action squeeze;
typed_action scroll;
XrAction trigger; // XR_ACTION_TYPE_FLOAT_INPUT
XrAction squeeze; // XR_ACTION_TYPE_FLOAT_INPUT
XrAction scroll; // XR_ACTION_TYPE_VECTOR2F_INPUT
// TODO: thresholds?
};
@@ -106,18 +109,27 @@ private:
ImGuiContext * context;
ImGuiIO& io;
std::string ini_filename;
// std::string ini_filename;
std::vector<std::pair<controller, controller_state>> controllers;
XrSpace world;
size_t focused_controller = (size_t)-1;
XrTime last_display_time = 0;
bool button_pressed = false;
public:
imgui_context(vk::raii::Device& device, uint32_t queue_family_index,
vk::raii::Queue& queue, XrSpace world, std::span<controller> controllers);
vk::raii::Queue& queue, XrSpace world, std::span<controller> controllers, float resolution, glm::vec2 scale);
~imgui_context();
void set_position(glm::vec3 position, glm::quat orientation);
void new_frame(XrTime display_time);
std::shared_ptr<vk::raii::ImageView> render();
ImFont * large_font;
size_t get_focused_controller() const
{
return focused_controller;
}
};
+3 -1
View File
@@ -610,6 +610,8 @@ public:
material_ref.buffer.reset();
material_ref.ds.reset();
material_ref.double_sided = gltf_material.doubleSided;
scene_data::material::gpu_data & material_data = material_ref.staging;
material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor);
@@ -718,7 +720,7 @@ public:
primitive_ref.vertex_count = vertices.size();
primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC
primitive_ref.front_face = vk::FrontFace::eClockwise; // TBC
primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC
primitive_ref.topology = convert(gltf_primitive.type);
if (gltf_primitive.materialIndex)
+2
View File
@@ -117,6 +117,8 @@ struct scene_data
bool ds_dirty;
std::string name;
std::string shader_name = "lit";
bool blend_enable = false;
};
struct vertex
+104 -16
View File
@@ -173,7 +173,7 @@ scene_renderer::scene_renderer(vk::raii::Device & device, vk::raii::PhysicalDevi
.uniform_buffer_dynamic = frames_in_flight,
},
frames_in_flight),
ds_pool_material(device, {.combined_image_sampler = 500, .uniform_buffer = 100}, 100)
ds_pool_material(device, {.combined_image_sampler = 500, .uniform_buffer = 100}, 100) // TODO tunable
{
// Create the default material
default_material = create_default_material(cb_pool);
@@ -253,7 +253,7 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
std::array attachments = {
vk::AttachmentDescription{
.format = output_format,
.samples = vk::SampleCountFlagBits::e1,
.samples = vk::SampleCountFlagBits::e4,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = vk::ImageLayout::eUndefined,
@@ -261,7 +261,7 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
},
vk::AttachmentDescription{
.format = depth_format,
.samples = vk::SampleCountFlagBits::e1,
.samples = vk::SampleCountFlagBits::e4,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eDontCare,
.stencilLoadOp = vk::AttachmentLoadOp::eClear,
@@ -269,6 +269,17 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal,
},
vk::AttachmentDescription{
.format = output_format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eDontCare,
.storeOp = vk::AttachmentStoreOp::eStore,
.stencilLoadOp = vk::AttachmentLoadOp::eClear,
.stencilStoreOp = vk::AttachmentStoreOp::eDontCare,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
}};
info.setAttachments(attachments);
@@ -282,11 +293,18 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal,
};
vk::AttachmentReference resolve_attachment{
.attachment = 2,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::SubpassDescription subpasses{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
.colorAttachmentCount = 1,
.pColorAttachments = &color_attachment,
.pResolveAttachments = &resolve_attachment,
.pDepthStencilAttachment = &depth_attachment,
};
subpasses.setColorAttachments(color_attachment);
info.setSubpasses(subpasses);
std::array dependencies{
@@ -343,13 +361,14 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.samples = vk::SampleCountFlagBits::e4,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment
.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, .usage = VMA_MEMORY_USAGE_AUTO,
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check
}};
@@ -361,6 +380,35 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image
.subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eDepth, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
});
out.multisample_image = image_allocation{vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = output_format,
.extent = {
.width = output_size.width,
.height = output_size.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e4,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check
.preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT,
}};
out.multisample_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{
.image = out.multisample_image,
.viewType = vk::ImageViewType::e2D,
.format = output_format,
.components{},
.subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
});
vk::FramebufferCreateInfo fb_info{
.renderPass = *renderpass,
.width = output_size.width,
@@ -369,8 +417,10 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image
};
std::array attachments{
vk::ImageView{*out.multisample_view},
vk::ImageView{*out.depth_view},
vk::ImageView{*out.image_view},
vk::ImageView{*out.depth_view}};
};
fb_info.setAttachments(attachments);
out.framebuffer = vk::raii::Framebuffer(device, fb_info);
@@ -433,7 +483,7 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
.lineWidth = 1.0,
}},
.MultisampleState = {vk::PipelineMultisampleStateCreateInfo{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
.rasterizationSamples = vk::SampleCountFlagBits::e4,
}},
.DepthStencilState = {vk::PipelineDepthStencilStateCreateInfo{
.depthTestEnable = true,
@@ -445,6 +495,13 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
}},
.ColorBlendState = {vk::PipelineColorBlendStateCreateInfo{}},
.ColorBlendAttachments = {vk::PipelineColorBlendAttachmentState{
.blendEnable = info.blend_enable,
.srcColorBlendFactor = vk::BlendFactor::eSrcAlpha,
.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha,
.colorBlendOp = vk::BlendOp::eAdd,
.srcAlphaBlendFactor = vk::BlendFactor::eSrcAlpha,
.dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha,
.alphaBlendOp = vk::BlendOp::eAdd,
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB}},
.DynamicState = {},
.layout = *pipeline_layout,
@@ -465,6 +522,8 @@ vk::Sampler scene_renderer::get_sampler(const sampler_info & info)
.mipmapMode = info.min_filter_mipmap,
.addressModeU = info.wrapS,
.addressModeV = info.wrapT,
// .anisotropyEnable = true,
// .maxAnisotropy = 4,
});
samplers.emplace(info, out);
@@ -480,7 +539,6 @@ scene_renderer::per_frame_resources & scene_renderer::start_frame()
frame_resources[current_frame].resources.clear();
frame_resources[current_frame].cb.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
// frame_resources[current_frame].
return frame_resources[current_frame];
}
@@ -534,6 +592,23 @@ void scene_renderer::update_material_descriptor_set(scene_data::material& materi
device.updateDescriptorSets(write_ds, {});
}
static void print_scene_hierarchy(const scene_data& scene, std::span<glm::mat4> model_matrices, size_t root = scene_data::scene_object::root_id, int level = 0)
{
for(const auto&& [index, node]: utils::enumerate(scene.scene_objects))
{
if (node.parent_id != root)
continue;
// glm::mat4 M = model_matrices[index];
// glm::vec4 pos = glm::column(M, 3);
// spdlog::info("{:{}} {} pos={}, rot={}, pos to root={}", "", level * 2, node.name, node.translation, node.rotation, glm::vec3(pos));
spdlog::info("{:{}} {}", "", level * 2, node.name);
print_scene_hierarchy(scene, model_matrices, index, level + 1);
}
}
void scene_renderer::render(scene_data & scene, std::span<frame_info> frames)
{
size_t ubo_alignment = physical_device_properties.limits.minUniformBufferOffsetAlignment;
@@ -582,7 +657,9 @@ void scene_renderer::render(scene_data & scene, std::span<frame_info> frames)
.usage = vk::BufferUsageFlagBits::eUniformBuffer},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}};
.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE},
"scene_renderer::render (UBO staging)"
};
}
// if (!resources.uniform_buffer || resources.uniform_buffer.info().size < ubo_size)
@@ -610,6 +687,7 @@ void scene_renderer::render(scene_data & scene, std::span<frame_info> frames)
std::vector<bool> reverse_side(scene.scene_objects.size());
std::vector<bool> visible(scene.scene_objects.size());
for(const auto& [index, object]: utils::enumerate(scene.scene_objects))
{
glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), object.translation) * (glm::mat4)object.rotation * glm::scale(glm::mat4(1), object.scale);
@@ -634,6 +712,8 @@ void scene_renderer::render(scene_data & scene, std::span<frame_info> frames)
}
}
// print_scene_hierarchy(scene, transform_to_root);
for (const auto && [frame_index, frame]: utils::enumerate(frames))
{
scene_renderer::output_image & output = get_output_image_data(frame.destination);
@@ -641,9 +721,16 @@ void scene_renderer::render(scene_data & scene, std::span<frame_info> frames)
frame_gpu_data& frame_ubo = *reinterpret_cast<frame_gpu_data*>(ubo + *current_ubo_frame_offset);
frame_ubo.ambient_color = glm::vec4(0.5,0.5,0.5,0); // TODO
frame_ubo.light_color = glm::vec4(0.5,0.5,0.5,0); // TODO
frame_ubo.light_position = glm::vec4(0,1,0,0); // TODO
// frame_ubo.ambient_color = glm::vec4(0.5,0.5,0.5,0); // TODO
// frame_ubo.light_color = glm::vec4(0.5,0.5,0.5,0); // TODO
// frame_ubo.ambient_color = glm::vec4(0.2,0.2,0.2,0); // TODO
// frame_ubo.light_color = glm::vec4(0.8,0.8,0.8,0); // TODO
frame_ubo.ambient_color = glm::vec4(0,0,0,0); // TODO
frame_ubo.light_color = glm::vec4(0.8,0.8,0.8,0); // TODO
frame_ubo.light_position = glm::vec4(1,1,1,0); // TODO
frame_ubo.proj = frame.projection;
frame_ubo.view = frame.view;
@@ -712,10 +799,11 @@ void scene_renderer::render(scene_data & scene, std::span<frame_info> frames)
// Get the pipeline
pipeline_info info{
.shader_name = "lit",
.shader_name = material->shader_name,
.cull_mode = primitive.cull_mode,
.front_face = primitive.front_face,
.topology = primitive.topology
.topology = primitive.topology,
.blend_enable = material->blend_enable,
};
if (material->double_sided)
+5 -1
View File
@@ -42,6 +42,7 @@ struct pipeline_info
vk::CullModeFlags cull_mode = vk::CullModeFlagBits::eNone;
vk::FrontFace front_face = vk::FrontFace::eClockwise;
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
bool blend_enable = false;
bool operator==(const pipeline_info & other) const noexcept = default;
};
@@ -75,6 +76,9 @@ public:
image_allocation depth_buffer;
vk::raii::ImageView depth_view = nullptr;
image_allocation multisample_image;
vk::raii::ImageView multisample_view = nullptr;
};
// Initialization functions
@@ -164,7 +168,7 @@ public:
void update_material_descriptor_set(scene_data::material& material);
public:
scene_renderer(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool, vk::Extent2D output_size, vk::Format output_format, std::span<vk::Format> depth_formats, int frames_in_flight = 3);
scene_renderer(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool, vk::Extent2D output_size, vk::Format output_format, std::span<vk::Format> depth_formats, int frames_in_flight = 2);
~scene_renderer();