Misc renderer improvements:

- Use VK_KHR_multiview
- Compute bounding boxes, use them to sort primitives
- Add shader reflection
- Add debug drawer
This commit is contained in:
Guillaume Meunier
2025-10-25 10:25:53 +02:00
parent 17ac7ab7d9
commit 7963efc034
23 changed files with 1679 additions and 615 deletions
+13 -34
View File
@@ -31,6 +31,7 @@
#include <vulkan/vulkan_raii.hpp>
#include "utils/magic_hash.h"
#include "vertex_layout.h"
#include "vk/allocation.h"
namespace renderer
@@ -61,7 +62,7 @@ struct material
float metallic_factor = 1;
float roughness_factor = 1;
float occlusion_strength = 0;
float normal_scale = 0;
float normal_scale = 1;
float alpha_cutoff = 0.5;
uint32_t base_color_texcoord = 0;
@@ -73,13 +74,6 @@ struct material
// TODO: add fastgltf::TextureTransform?
};
enum class alpha_mode_t
{
opaque,
mask,
blend
};
std::shared_ptr<texture> base_color_texture;
std::shared_ptr<texture> metallic_roughness_texture;
std::shared_ptr<texture> occlusion_texture;
@@ -89,7 +83,9 @@ struct material
// Disable back face culling with this material
bool double_sided = true;
alpha_mode_t alpha_mode;
bool blend_enable = false;
bool depth_test_enable = true;
bool depth_write_enable = true;
gpu_data staging;
@@ -98,7 +94,7 @@ struct material
size_t offset;
std::string name;
std::string shader_name = "lit";
std::string fragment_shader_name = "lit.frag";
};
struct primitive
@@ -108,7 +104,13 @@ struct primitive
uint32_t vertex_count;
vk::IndexType index_type;
vk::DeviceSize index_offset;
vk::DeviceSize vertex_offset;
std::vector<vk::DeviceSize> vertex_offset; // TODO: inplace_vector
vertex_layout layout;
glm::vec3 obb_min;
glm::vec3 obb_max;
std::string vertex_shader;
// See also material::double_sided
vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone;
@@ -124,29 +126,6 @@ struct mesh
std::vector<primitive> primitives;
std::shared_ptr<buffer_allocation> buffer;
};
// TODO move vertex class in .cpp, put vertex description in the primitive
struct vertex
{
glm::vec3 position;
glm::vec3 normal;
glm::vec4 tangent;
std::array<glm::vec2, 2> texcoord;
glm::vec4 color;
std::array<glm::vec4, 1> joints;
std::array<glm::vec4, 1> weights;
struct description
{
vk::VertexInputBindingDescription binding;
std::vector<vk::VertexInputAttributeDescription> attributes;
std::vector<std::string> attribute_names;
vk::PipelineVertexInputStateCreateFlags flags{};
};
static description describe();
};
} // namespace renderer
namespace std
+283 -161
View File
@@ -22,7 +22,12 @@
#include "gpu_buffer.h"
#include "image_loader.h"
#include "render/scene_components.h"
#include "render/vertex_layout.h"
#include "utils/ranges.h"
#include "vk/shader.h"
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <entt/entt.hpp>
#include <fastgltf/base64.hpp>
#include <fastgltf/core.hpp>
@@ -32,67 +37,47 @@
#include <fastgltf/types.hpp>
#include <fastgltf/util.hpp>
#include <glm/ext.hpp>
#include <glm/fwd.hpp>
#include <limits>
#include <ranges>
#include <spdlog/spdlog.h>
#include <string>
#include <vulkan/vulkan_format_traits.hpp>
namespace fastgltf
{
// glm_element_traits.hpp is missing all the glm::vec<1, T> and glm:::vec<n, int32_t> specializations
// clang-format off
template <> struct ElementTraits<glm::u8vec1> : ElementTraitsBase<glm::u8vec1, AccessorType::Scalar, std::uint8_t> {};
template <> struct ElementTraits<glm::i8vec1> : ElementTraitsBase<glm::i8vec1, AccessorType::Scalar, std::int8_t> {};
template <> struct ElementTraits<glm::u16vec1> : ElementTraitsBase<glm::u16vec1, AccessorType::Scalar, std::uint16_t> {};
template <> struct ElementTraits<glm::i16vec1> : ElementTraitsBase<glm::i16vec1, AccessorType::Scalar, std::int16_t> {};
template <> struct ElementTraits<glm::u32vec1> : ElementTraitsBase<glm::u32vec1, AccessorType::Scalar, std::uint32_t> {};
template <> struct ElementTraits<glm::i32vec1> : ElementTraitsBase<glm::i32vec1, AccessorType::Scalar, std::int32_t> {};
template <> struct ElementTraits<glm::i32vec2> : ElementTraitsBase<glm::i32vec2, AccessorType::Vec2, std::int32_t> {};
template <> struct ElementTraits<glm::i32vec3> : ElementTraitsBase<glm::i32vec3, AccessorType::Vec3, std::int32_t> {};
template <> struct ElementTraits<glm::i32vec4> : ElementTraitsBase<glm::i32vec4, AccessorType::Vec4, std::int32_t> {};
template <> struct ElementTraits<glm::fvec1> : ElementTraitsBase<glm::fvec1, AccessorType::Scalar, float> {};
template <> struct ElementTraits<glm::dvec1> : ElementTraitsBase<glm::dvec1, AccessorType::Scalar, float> {};
// clang-format on
} // namespace fastgltf
namespace
{
// BEGIN Utility functions
template <class T>
constexpr vk::Format vk_attribute_format = vk::Format::eUndefined;
template <>
constexpr vk::Format vk_attribute_format<float> = vk::Format::eR32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec2> = vk::Format::eR32G32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec3> = vk::Format::eR32G32B32Sfloat;
template <>
constexpr vk::Format vk_attribute_format<glm::vec4> = vk::Format::eR32G32B32A32Sfloat;
template <typename T, size_t N>
constexpr vk::Format vk_attribute_format<std::array<T, N>> = vk_attribute_format<T>;
template <class T>
constexpr size_t nb_attributes = 1;
template <typename T, size_t N>
constexpr size_t nb_attributes<std::array<T, N>> = N;
template <class T>
struct remove_array
{
using type = T;
};
template <class T, size_t N>
struct remove_array<std::array<T, N>>
{
using type = T;
};
template <class T>
using remove_array_t = remove_array<T>::type;
template <class T>
struct is_array : std::false_type
{
};
template <class T, size_t N>
struct is_array<std::array<T, N>> : std::true_type
{
};
template <class T>
constexpr bool is_array_v = is_array<T>::value;
// END
// BEGIN GLTF -> Vulkan conversion functions
std::pair<vk::Filter, vk::SamplerMipmapMode> convert(fastgltf::Filter filter)
{
switch (filter)
{
case fastgltf::Filter::Nearest:
return {vk::Filter::eNearest, {}};
case fastgltf::Filter::Linear:
return {vk::Filter::eLinear, {}};
case fastgltf::Filter::NearestMipMapNearest:
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest};
case fastgltf::Filter::Linear:
case fastgltf::Filter::LinearMipMapNearest:
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest};
@@ -176,21 +161,6 @@ glm::vec3 convert(const fastgltf::math::nvec3 & v)
return {v[0], v[1], v[2]};
}
renderer::material::alpha_mode_t convert(fastgltf::AlphaMode alpha_mode)
{
switch (alpha_mode)
{
case fastgltf::AlphaMode::Opaque:
return renderer::material::alpha_mode_t::opaque;
case fastgltf::AlphaMode::Mask:
return renderer::material::alpha_mode_t::mask;
case fastgltf::AlphaMode::Blend:
return renderer::material::alpha_mode_t::blend;
}
throw std::invalid_argument("alpha_mode");
}
components::animation_track_base::interpolation_t convert(fastgltf::AnimationInterpolation interpolation)
{
switch (interpolation)
@@ -209,57 +179,194 @@ components::animation_track_base::interpolation_t convert(fastgltf::AnimationInt
// BEGIN Vertex attributes loading
template <typename T>
requires is_array_v<T>
void copy_vertex_attributes(
const fastgltf::Asset & asset,
const fastgltf::Primitive & primitive,
std::string attribute_name,
std::vector<renderer::vertex> & vertices,
T renderer::vertex::*attribute)
std::vector<glm::dvec4> read_vertex_attribute_aux2(const fastgltf::Asset & asset, const fastgltf::Accessor & accessor)
{
using U = T::value_type;
constexpr size_t N = std::tuple_size_v<T>;
std::vector<glm::dvec4> output;
output.resize(accessor.count);
for (size_t i = 0; i < N; i++)
size_t index = 0;
switch (fastgltf::getNumComponents(accessor.type))
{
auto it = primitive.findAttribute(attribute_name + std::to_string(i));
if (it == primitive.attributes.end())
continue;
const fastgltf::Accessor & accessor = asset.accessors.at(it->accessorIndex);
if (vertices.size() < accessor.count)
vertices.resize(accessor.count, {});
fastgltf::iterateAccessorWithIndex<U>(asset, accessor, [&](U value, std::size_t idx) {
(vertices[idx].*attribute)[i] = value;
});
case 1:
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](const T & value, size_t index) {
output[index] = glm::dvec4(value[0], 0, 0, 1);
});
break;
case 2:
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](const T & value, size_t index) {
output[index] = glm::dvec4(value[0], value[1], 0, 1);
});
break;
case 3:
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](const T & value, size_t index) {
output[index] = glm::dvec4(value[0], value[1], value[2], 1);
});
break;
case 4:
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](const T & value, size_t index) {
output[index] = glm::dvec4(value[0], value[1], value[2], value[3]);
});
break;
default:
abort();
}
return output;
}
template <typename T>
requires(!is_array_v<T>)
std::vector<glm::dvec4> read_vertex_attribute_aux(const fastgltf::Asset & asset, const fastgltf::Accessor & accessor)
{
switch (fastgltf::getNumComponents(accessor.type))
{
// clang-format off
case 1: return read_vertex_attribute_aux2<glm::vec<1, T>>(asset, accessor);
case 2: return read_vertex_attribute_aux2<glm::vec<2, T>>(asset, accessor);
case 3: return read_vertex_attribute_aux2<glm::vec<3, T>>(asset, accessor);
case 4: return read_vertex_attribute_aux2<glm::vec<4, T>>(asset, accessor);
//clang-format on
}
return {};
}
std::vector<glm::dvec4> read_vertex_attribute(const fastgltf::Asset & asset, const fastgltf::Accessor & accessor)
{
switch (accessor.componentType)
{
// clang-format off
case fastgltf::ComponentType::Byte: return read_vertex_attribute_aux<int8_t>(asset, accessor);
case fastgltf::ComponentType::UnsignedByte: return read_vertex_attribute_aux<uint8_t>(asset, accessor);
case fastgltf::ComponentType::Short: return read_vertex_attribute_aux<int16_t>(asset, accessor);
case fastgltf::ComponentType::UnsignedShort: return read_vertex_attribute_aux<uint16_t>(asset, accessor);
case fastgltf::ComponentType::Int: return read_vertex_attribute_aux<int32_t>(asset, accessor);
case fastgltf::ComponentType::UnsignedInt: return read_vertex_attribute_aux<uint32_t>(asset, accessor);
case fastgltf::ComponentType::Float: return read_vertex_attribute_aux<float>(asset, accessor);
//clang-format on
case fastgltf::ComponentType::Double: // TODO
abort();
break;
case fastgltf::ComponentType::Invalid:
abort();
break;
}
return {};
}
template <typename T>
void write_vertex_attribute_aux(std::byte * output, size_t stride, int components, const std::vector<glm::dvec4> & input)
{
switch (components)
{
case 1:
for (size_t i = 0, n = input.size(); i < n; i++, output += stride)
*reinterpret_cast<glm::vec<1, T> *>(output) = glm::vec<1, T>(input[i].x);
break;
case 2:
for (size_t i = 0, n = input.size(); i < n; i++, output += stride)
*reinterpret_cast<glm::vec<2, T> *>(output) = glm::vec<2, T>(input[i].x, input[i].y);
break;
case 3:
for (size_t i = 0, n = input.size(); i < n; i++, output += stride)
*reinterpret_cast<glm::vec<3, T> *>(output) = glm::vec<3, T>(input[i].x, input[i].y, input[i].z);
break;
case 4:
for (size_t i = 0, n = input.size(); i < n; i++, output += stride)
*reinterpret_cast<glm::vec<3, T> *>(output) = glm::vec<4, T>(input[i].x, input[i].y, input[i].z, input[i].w);
break;
default:
abort();
}
}
void write_vertex_attribute(std::vector<std::byte> & output, size_t offset, size_t stride, vk::Format format, std::vector<glm::dvec4> input)
{
assert(output.size() >= input.size() * stride);
switch (format)
{
case vk::Format::eR32Sfloat:
case vk::Format::eR32G32Sfloat:
case vk::Format::eR32G32B32Sfloat:
case vk::Format::eR32G32B32A32Sfloat:
write_vertex_attribute_aux<float>(output.data() + offset, stride, vk::componentCount(format), input);
return;
default:
return;
}
}
void copy_vertex_attributes(
const fastgltf::Asset & asset,
const fastgltf::Primitive & primitive,
std::string attribute_name,
std::vector<renderer::vertex> & vertices,
T renderer::vertex::*attribute)
const fastgltf::Accessor & accessor,
std::vector<std::byte> & buffer,
const vk::VertexInputBindingDescription & binding,
const vk::VertexInputAttributeDescription & attribute)
{
auto it = primitive.findAttribute(attribute_name);
assert(buffer.size() >= accessor.count * binding.stride);
if (it == primitive.attributes.end())
return;
write_vertex_attribute(buffer, attribute.offset, binding.stride, attribute.format, read_vertex_attribute(asset, accessor));
}
const fastgltf::Accessor & accessor = asset.accessors.at(it->accessorIndex);
std::pair<size_t, std::vector<std::vector<std::byte>>> create_vertex_buffers(
const renderer::vertex_layout & layout,
const fastgltf::Asset & asset,
const fastgltf::Primitive & primitive)
{
std::pair<size_t, std::vector<std::vector<std::byte>>> size_buffers;
auto & [vertex_count, buffers] = size_buffers;
if (vertices.size() < accessor.count)
vertices.resize(accessor.count, {});
// Count the vertices
vertex_count = 0;
for (const auto & name: layout.attribute_names)
{
if (auto attribute = primitive.findAttribute(name); attribute != primitive.attributes.cend())
vertex_count = std::max(vertex_count, asset.accessors.at(attribute->accessorIndex).count);
}
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](T value, std::size_t idx) {
vertices[idx].*attribute = value;
});
// Allocate buffers
int max_binding = std::ranges::max(layout.bindings, {}, &vk::VertexInputBindingDescription::binding).binding;
buffers.resize(max_binding + 1);
for (const vk::VertexInputBindingDescription & binding: layout.bindings)
{
switch (binding.inputRate)
{
case vk::VertexInputRate::eVertex:
buffers[binding.binding].resize(binding.stride * vertex_count);
break;
case vk::VertexInputRate::eInstance:
buffers[binding.binding].resize(binding.stride);
break;
}
}
// Copy attributes
for (auto && [name, attribute]: std::views::zip(layout.attribute_names, layout.attributes))
{
auto binding_iter = std::ranges::find(layout.bindings, attribute.binding, &vk::VertexInputBindingDescription::binding);
assert(binding_iter != layout.bindings.end());
const vk::VertexInputBindingDescription & binding = *binding_iter;
std::vector<std::byte> & buffer = buffers.at(binding.binding);
const fastgltf::Attribute * gltf_attribute = primitive.findAttribute(name);
if (gltf_attribute == primitive.attributes.cend())
{
// Also check if it's an array of size 1
gltf_attribute = primitive.findAttribute(name + "_0");
if (gltf_attribute == primitive.attributes.cend())
continue;
}
const fastgltf::Accessor & accessor = asset.accessors.at(gltf_attribute->accessorIndex);
copy_vertex_attributes(asset, accessor, buffer, binding, attribute);
}
return size_buffers;
}
// END
@@ -584,7 +691,24 @@ public:
material.buffer.reset();
material.double_sided = gltf_material.doubleSided;
material.alpha_mode = convert(gltf_material.alphaMode);
switch (gltf_material.alphaMode)
{
case fastgltf::AlphaMode::Opaque:
material.fragment_shader_name = "lit.frag";
material.blend_enable = false;
break;
case fastgltf::AlphaMode::Mask:
material.fragment_shader_name = "lit_mask.frag";
material.blend_enable = false;
break;
case fastgltf::AlphaMode::Blend:
material.fragment_shader_name = "lit.frag";
material.blend_enable = true;
break;
}
renderer::material::gpu_data & material_data = material.staging;
@@ -678,29 +802,73 @@ public:
}
}
else
{
primitive_ref.indexed = false;
renderer::vertex_layout & layout = primitive_ref.layout;
if (gltf_primitive.findAttribute("JOINTS_0") == gltf_primitive.attributes.cend())
primitive_ref.vertex_shader = "lit.vert";
else
primitive_ref.vertex_shader = "lit_skinned.vert";
// For attributes types, see https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview (§ 3.7.2.1)
const std::vector<shader::input> & shader_inputs = load_shader(device, primitive_ref.vertex_shader)->inputs;
for (const auto & input: shader_inputs)
{
std::string semantic = input.name;
std::transform(semantic.begin(), semantic.end(), semantic.begin(), [](auto c) { return std::toupper(c); });
if (semantic.starts_with("IN_"))
semantic = semantic.substr(3);
int binding;
if (semantic == "POSITION" or
semantic == "JOINTS" or
semantic == "WEIGHTS")
binding = 0;
else
binding = 1;
layout.add_vertex_attribute(semantic, input.format, binding, input.location, input.array_size);
}
std::vector<renderer::vertex> vertices;
auto [vertex_count, buffers] = create_vertex_buffers(layout, gltf, gltf_primitive);
primitive_ref.vertex_count = vertex_count;
copy_vertex_attributes(gltf, gltf_primitive, "POSITION", vertices, &renderer::vertex::position);
copy_vertex_attributes(gltf, gltf_primitive, "NORMAL", vertices, &renderer::vertex::normal);
copy_vertex_attributes(gltf, gltf_primitive, "TANGENT", vertices, &renderer::vertex::tangent);
copy_vertex_attributes(gltf, gltf_primitive, "TEXCOORD_", vertices, &renderer::vertex::texcoord);
copy_vertex_attributes(gltf, gltf_primitive, "COLOR", vertices, &renderer::vertex::color);
copy_vertex_attributes(gltf, gltf_primitive, "JOINTS_", vertices, &renderer::vertex::joints);
copy_vertex_attributes(gltf, gltf_primitive, "WEIGHTS_", vertices, &renderer::vertex::weights);
for (auto & buffer: buffers)
primitive_ref.vertex_offset.push_back(staging_buffer.add_vertices(buffer));
primitive_ref.vertex_offset = staging_buffer.add_vertices(vertices);
primitive_ref.vertex_count = vertices.size();
primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC
primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC
primitive_ref.topology = convert(gltf_primitive.type);
// Compute the OBB
glm::vec3 obb_min{std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max()};
glm::vec3 obb_max = -obb_min;
fastgltf::iterateAccessor<glm::vec3>(gltf, gltf.accessors.at(gltf_primitive.findAttribute("POSITION")->accessorIndex), [&](glm::vec3 position) {
obb_min.x = std::min(obb_min.x, position.x);
obb_min.y = std::min(obb_min.y, position.y);
obb_min.z = std::min(obb_min.z, position.z);
obb_max.x = std::max(obb_max.x, position.x);
obb_max.y = std::max(obb_max.y, position.y);
obb_max.z = std::max(obb_max.z, position.z);
});
primitive_ref.obb_min = obb_min;
primitive_ref.obb_max = obb_max;
if (gltf_primitive.materialIndex)
primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex);
if (primitive_ref.material_ and primitive_ref.material_->double_sided)
{
primitive_ref.cull_mode = vk::CullModeFlagBits::eFrontAndBack;
primitive_ref.front_face = vk::FrontFace::eCounterClockwise;
}
else
{
primitive_ref.cull_mode = vk::CullModeFlagBits::eBack;
primitive_ref.front_face = vk::FrontFace::eCounterClockwise;
}
primitive_ref.topology = convert(gltf_primitive.type);
}
}
@@ -872,52 +1040,6 @@ public:
} // namespace
renderer::vertex::description
renderer::vertex::describe()
{
renderer::vertex::description desc;
desc.binding = vk::VertexInputBindingDescription{
.binding = 0,
.stride = sizeof(vertex),
.inputRate = vk::VertexInputRate::eVertex,
};
vk::VertexInputAttributeDescription attribute{
.location = 0,
.binding = 0,
};
#define VERTEX_ATTR(member) \
attribute.format = vk_attribute_format<decltype(vertex::member)>; \
for (size_t i = 0; i < nb_attributes<decltype(vertex::member)>; i++) \
{ \
attribute.offset = offsetof(vertex, member) + i * sizeof(remove_array_t<decltype(vertex::member)>); \
desc.attributes.push_back(attribute); \
attribute.location++; \
if (is_array_v<decltype(vertex::member)>) \
{ \
desc.attribute_names.push_back(#member "_" + std::to_string(i)); \
} \
else \
{ \
desc.attribute_names.push_back(#member); \
} \
}
VERTEX_ATTR(position);
VERTEX_ATTR(normal);
VERTEX_ATTR(tangent);
VERTEX_ATTR(texcoord);
VERTEX_ATTR(color);
VERTEX_ATTR(joints);
VERTEX_ATTR(weights);
static_assert(vertex{}.joints.size() == vertex{}.weights.size());
return desc;
}
std::shared_ptr<entt::registry> scene_loader::operator()(std::span<const std::byte> data, const std::string & name, const std::filesystem::path & parent_path)
{
vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
+512 -164
View File
@@ -21,6 +21,7 @@
#include "application.h"
#include "render/image_loader.h"
#include "render/scene_components.h"
#include "render/vertex_layout.h"
#include "utils/alignment.h"
#include "utils/fmt_glm.h"
#include "utils/ranges.h"
@@ -31,10 +32,12 @@
#include <boost/pfr/core.hpp>
#include <entt/entity/entity.hpp>
#include <entt/entt.hpp>
#include <glm/ext/matrix_transform.hpp>
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/quaternion.hpp>
#include <memory>
#include <numeric>
#include <ranges>
#include <spdlog/spdlog.h>
#include <vk_mem_alloc.h>
@@ -43,6 +46,38 @@
#include <vulkan/vulkan_handles.hpp>
#include <vulkan/vulkan_structs.hpp>
namespace
{
struct frustum
{
// Only 5 planes because the far plane is infinitely far
std::array<glm::vec4, 5> planes;
frustum() = default;
frustum(const frustum &) = default;
frustum(const glm::mat4 & proj)
{
/* Let [x',y',z',w'] = proj * [x,y,z,1]
* Extract the planes from the projection matrix s.t.
*
* (dot(planes[0], [x,y,z,1]) > 0 <=> x' < w' <=> w' - x' > 0) <=> planes[0] = row3-row0
* (dot(planes[1], [x,y,z,1]) > 0 <=> x' > -w' <=> x' + w' > 0) <=> planes[1] = row0+row3
* (dot(planes[2], [x,y,z,1]) > 0 <=> y' < w' <=> w' - y' > 0) <=> planes[2] = row3-row1
* (dot(planes[3], [x,y,z,1]) > 0 <=> y' > -w' <=> y' + w' > 0) <=> planes[3] = row1+row3
* (dot(planes[4], [x,y,z,1]) > 0 <=> z' < w' <=> w' - z' > 0) <=> planes[4] = row3-row2
*
* See Gribb & Hartmann
*/
planes[0] = glm::row(proj, 3) - glm::row(proj, 0);
planes[1] = glm::row(proj, 0) + glm::row(proj, 3);
planes[2] = glm::row(proj, 3) - glm::row(proj, 1);
planes[3] = glm::row(proj, 1) + glm::row(proj, 3);
planes[4] = glm::row(proj, 3) - glm::row(proj, 2);
}
};
} // namespace
// TODO move in lobby?
vk::Format scene_renderer::find_usable_image_format(
vk::raii::PhysicalDevice physical_device,
@@ -139,6 +174,32 @@ static vk::FrontFace reverse(vk::FrontFace face)
return vk::FrontFace::eCounterClockwise;
}
// Return true if the OBB is outside the frustum
static bool frustum_cull(
const frustum & fru,
const glm::mat4 & model,
const glm::vec3 & obb_min,
const glm::vec3 & obb_max)
{
for (const glm::vec4 & plane: fru.planes)
{
int out = 0;
out += glm::dot(plane, model * glm::vec4(obb_min.x, obb_min.y, obb_min.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_min.x, obb_min.y, obb_max.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_min.x, obb_max.y, obb_min.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_min.x, obb_max.y, obb_max.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_max.x, obb_min.y, obb_min.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_max.x, obb_min.y, obb_max.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_max.x, obb_max.y, obb_min.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_max.x, obb_max.y, obb_max.z, 1)) < 0;
if (out == 8)
return true;
}
return false;
}
static std::array layout_bindings_0{
vk::DescriptorSetLayoutBinding{
// scene_ubo: per-frame/view data
@@ -272,7 +333,7 @@ scene_renderer::renderpass & scene_renderer::get_renderpass(const renderpass_inf
scene_renderer::renderpass scene_renderer::create_renderpass(const renderpass_info & info_)
{
vk::StructureChain<vk::RenderPassCreateInfo, vk::RenderPassFragmentDensityMapCreateInfoEXT> info;
vk::StructureChain<vk::RenderPassCreateInfo, vk::RenderPassFragmentDensityMapCreateInfoEXT, vk::RenderPassMultiviewCreateInfo> info;
scene_renderer::renderpass rp;
std::vector<vk::AttachmentDescription> attachments;
@@ -380,6 +441,15 @@ scene_renderer::renderpass scene_renderer::create_renderpass(const renderpass_in
}};
info.get().setDependencies(dependencies);
auto & multiview = info.get<vk::RenderPassMultiviewCreateInfo>();
multiview.subpassCount = 1;
std::array view_mask{uint32_t((1 << info_.multiview_count) - 1)};
multiview.setViewMasks(view_mask);
std::array correlation_mask{uint32_t((1 << info_.multiview_count) - 1)};
multiview.setCorrelationMasks(correlation_mask);
rp.attachment_count = (uint32_t)attachments.size();
rp.renderpass = vk::raii::RenderPass(device, info.get());
return rp;
@@ -402,15 +472,15 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
out.image_view = vk::raii::ImageView(
device, vk::ImageViewCreateInfo{
.image = info.color,
.viewType = vk::ImageViewType::e2D,
.viewType = vk::ImageViewType::e2DArray,
.format = info.renderpass.color_format,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = info.base_array_layer,
.layerCount = 1,
.baseArrayLayer = 0,
.layerCount = info.renderpass.multiview_count,
},
});
@@ -427,7 +497,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.arrayLayers = info.renderpass.multiview_count,
.samples = info.renderpass.msaa_samples,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
@@ -442,15 +512,15 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
device,
vk::ImageViewCreateInfo{
.image = info.depth ? info.depth : out.depth_buffer,
.viewType = vk::ImageViewType::e2D,
.viewType = vk::ImageViewType::e2DArray,
.format = info.renderpass.depth_format,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eDepth,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = info.depth ? info.base_array_layer : 0,
.layerCount = 1,
.baseArrayLayer = 0,
.layerCount = info.renderpass.multiview_count,
},
});
@@ -467,7 +537,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.arrayLayers = info.renderpass.multiview_count,
.samples = info.renderpass.msaa_samples,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
@@ -483,7 +553,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
device,
vk::ImageViewCreateInfo{
.image = out.multisample_image,
.viewType = vk::ImageViewType::e2D,
.viewType = vk::ImageViewType::e2DArray,
.format = info.renderpass.color_format,
.components{},
.subresourceRange = {
@@ -491,7 +561,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
.layerCount = info.renderpass.multiview_count,
},
});
}
@@ -504,15 +574,15 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
device,
vk::ImageViewCreateInfo{
.image = info.foveation,
.viewType = vk::ImageViewType::e2D,
.viewType = vk::ImageViewType::e2DArray,
.format = vk::Format::eR8G8Unorm,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = info.base_array_layer,
.layerCount = 1,
.baseArrayLayer = 0,
.layerCount = info.renderpass.multiview_count,
},
});
}
@@ -597,12 +667,10 @@ vk::raii::PipelineLayout scene_renderer::create_pipeline_layout(std::span<vk::De
vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
{
auto vertex_description = renderer::vertex::describe();
spdlog::debug("Creating pipeline");
auto vertex_shader = load_shader(device, info.shader_name + ".vert");
auto fragment_shader = load_shader(device, info.shader_name + ".frag");
auto vertex_shader = load_shader(device, info.vertex_shader_name);
auto fragment_shader = load_shader(device, info.fragment_shader_name);
auto specialization = make_specialization_constants(
int32_t(info.nb_texcoords),
@@ -630,8 +698,8 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
},
},
.VertexBindingDescriptions = {vertex_description.binding},
.VertexAttributeDescriptions = vertex_description.attributes,
.VertexBindingDescriptions = info.vertex_layout.bindings,
.VertexAttributeDescriptions = info.vertex_layout.attributes,
.InputAssemblyState = {{
.topology = info.topology,
.primitiveRestartEnable = false,
@@ -745,6 +813,8 @@ void scene_renderer::start_frame()
},
"scene_renderer::render (UBO)"};
}
f.frame_stats = stats{};
}
void scene_renderer::end_frame()
@@ -835,8 +905,11 @@ void scene_renderer::render(
vk::Image color_buffer,
vk::Image depth_buffer,
vk::Image foveation_image,
std::span<frame_info> frames)
std::span<frame_info> frames,
bool render_debug_draws)
{
assert(frames.size() <= instance_gpu_data{}.modelview.size());
per_frame_resources & resources = current_frame();
size_t buffer_alignment = std::max<size_t>(sizeof(glm::mat4), physical_device_properties.limits.minUniformBufferOffsetAlignment);
@@ -885,159 +958,389 @@ void scene_renderer::render(
.msaa_samples = vk::SampleCountFlagBits::e1,
// .msaa_samples = vk::SampleCountFlagBits::e4, // FIXME: MSAA does not work
.fragment_density_map = foveation_image != vk::Image{},
.multiview_count = (uint32_t)frames.size(),
};
vk::raii::RenderPass & renderpass = get_renderpass(rp_info).renderpass;
for (const auto && [frame_index, frame]: utils::enumerate(frames))
// Get the average view position/direction for sorting:
// The distance from a given view is (view * xform_to_root * vec4(0,0,0,1)).z
// => dot(view * xform_to_root * vec4(0,0,0,1), vec4(0,0,1,0))
// => transpose(vec4(0,0,1,0)) * view * xform_to_root * vec(0,0,0,1)
// => dot(row(view, 2), xform_to_root * vec(0,0,0,1))
auto avg_view = 1.f / frames.size() * std::accumulate(frames.begin(), frames.end(), glm::vec4(0, 0, 0, 0), [](const glm::vec4 sum_view, const frame_info & frame) { return sum_view + glm::row(frame.view, 2); });
// Compute the views frustum
std::vector<frustum> frusta;
for (const auto & frame: frames)
{
scene_renderer::output_image & output = get_output_image_data(output_image_info{
.renderpass = rp_info,
.output_size = output_size,
.color = color_buffer,
.depth = depth_buffer,
.foveation = foveation_image,
.base_array_layer = (uint32_t)frame_index,
});
glm::mat4 viewproj = frame.projection * frame.view;
frusta.push_back(frustum{frame.projection * frame.view});
}
vk::DeviceSize frame_ubo_offset = resources.uniform_buffer_offset;
frame_gpu_data & frame_ubo = *reinterpret_cast<frame_gpu_data *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(frame_gpu_data));
// Accumulate all visible primitives
std::vector<std::tuple<bool, float, components::node *, renderer::primitive *>> primitives; // TODO keep it between frames
for (auto && [entity, node]: scene.view<components::node>().each())
{
if (not node.global_visible or not node.mesh or (node.global_layer_mask & layer_mask) == 0)
continue;
// 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.1, 0.1, 0.1, 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;
cb.beginRenderPass(
vk::RenderPassBeginInfo{
.renderPass = *renderpass,
.framebuffer = *output.framebuffer,
.renderArea = {
.offset = {0, 0},
.extent = output_size,
},
.clearValueCount = clear_values.size(),
.pClearValues = clear_values.data(),
},
vk::SubpassContents::eInline);
// Accumulate all visible primitives
std::vector<std::tuple<bool, float, components::node *, renderer::primitive *>> primitives; // TODO keep it between frames
for (auto && [entity, node]: scene.view<components::node>().each())
for (renderer::primitive & primitive: node.mesh->primitives)
{
if (not node.global_visible or not node.mesh or (node.global_layer_mask & layer_mask) == 0)
continue;
size_t nb_triangles;
size_t nb_vertices = primitive.indexed ? primitive.index_count : primitive.vertex_count;
switch (primitive.topology)
{
case vk::PrimitiveTopology::eTriangleList:
nb_triangles = nb_vertices / 3;
break;
case vk::PrimitiveTopology::eTriangleFan:
nb_triangles = nb_vertices - 2;
break;
case vk::PrimitiveTopology::eTriangleStrip:
nb_triangles = nb_vertices - 2;
break;
default:
nb_triangles = 0;
break;
}
resources.frame_stats.count_primitives++;
resources.frame_stats.count_triangles += nb_triangles;
// Compute the primitive center
glm::vec3 center = 0.5f * (primitive.obb_min + primitive.obb_max);
// Position relative to the camera
glm::vec4 position = frame.view * node.transform_to_root * glm::vec4(0, 0, 0, 1);
float position = glm::dot(avg_view, node.transform_to_root * glm::vec4(center, 1));
for (renderer::primitive & primitive: node.mesh->primitives)
renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material;
if (node.joints.empty())
{
renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material;
primitives.emplace_back(material.alpha_mode == renderer::material::alpha_mode_t::blend or material.alpha_mode == renderer::material::alpha_mode_t::mask, position.z, &node, &primitive);
bool visible = false;
for (const auto & fru: frusta)
visible = visible or not frustum_cull(fru, node.transform_to_root, primitive.obb_min, primitive.obb_max);
if (visible)
primitives.emplace_back(material.blend_enable, position, &node, &primitive);
else
{
resources.frame_stats.count_culled_primitives++;
resources.frame_stats.count_culled_triangles += nb_triangles;
}
}
else
primitives.emplace_back(material.blend_enable, position, &node, &primitive);
}
}
// Sort by blending / distance
std::ranges::stable_sort(primitives, [](const auto & a, const auto & b) -> bool {
// Put the opaque objects first
if (std::get<0>(a) < std::get<0>(b))
return true;
if (std::get<0>(a) > std::get<0>(b))
return false;
// If blending is disabled (std::get<0> == false), put the closest objects first
// If blending is enabled (std::get<0> == true), put the farthest objeccts first
return std::get<0>(a) ^ (std::get<1>(a) > std::get<1>(b));
});
scene_renderer::output_image & output = get_output_image_data(output_image_info{
.renderpass = rp_info,
.output_size = output_size,
.color = color_buffer,
.depth = depth_buffer,
.foveation = foveation_image,
});
vk::DeviceSize frame_ubo_offset = resources.uniform_buffer_offset;
frame_gpu_data & frame_ubo = *reinterpret_cast<frame_gpu_data *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(frame_gpu_data));
// 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.1, 0.1, 0.1, 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
std::array<glm::mat4, 2> viewproj;
for (const auto && [frame_index, frame]: utils::enumerate(frames))
{
viewproj[frame_index] = frame.projection * frame.view;
frame_ubo.view[frame_index] = frame.view;
}
cb.beginRenderPass(vk::RenderPassBeginInfo{
.renderPass = *renderpass,
.framebuffer = *output.framebuffer,
.renderArea = {
.offset = {0, 0},
.extent = output_size,
},
.clearValueCount = clear_values.size(),
.pClearValues = clear_values.data(),
},
vk::SubpassContents::eInline);
// TODO try to add a depth pre-pass
for (auto & [blend_enable, distance, node_ptr, primitive_ptr]: primitives)
{
components::node & node = *node_ptr;
renderer::primitive & primitive = *primitive_ptr;
glm::mat4 & transform = node.transform_to_root;
// TODO: reuse the UBO if another primitive of the same mesh has already been drawn
vk::DeviceSize instance_ubo_offset = resources.uniform_buffer_offset;
instance_gpu_data & object_ubo = *reinterpret_cast<instance_gpu_data *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(instance_gpu_data));
vk::DeviceSize joints_ubo_offset = 0;
if (!node.joints.empty())
{
joints_ubo_offset = resources.uniform_buffer_offset;
glm::mat4 * joint_matrices = reinterpret_cast<glm::mat4 *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(glm::mat4) * 32);
assert(node.joints.size() <= 32);
for (auto && [idx, joint]: utils::enumerate(node.joints))
{
glm::mat4 & joint_transform = scene.get<components::node>(joint.first).transform_to_root;
joint_matrices[idx] = glm::inverse(transform) * joint_transform * joint.second;
}
}
// Sort by blending / distance
// TODO add frustum culling
std::ranges::stable_sort(primitives, [](const auto & a, const auto & b) -> bool {
// Put the opaque objects first
if (std::get<0>(a) < std::get<0>(b))
return true;
if (std::get<0>(a) > std::get<0>(b))
return false;
// If blending is disabled (std::get<0> == false), put the closest objects first
// If blending is enabled (std::get<0> == true), put the farthest objeccts first
return std::get<0>(a) ^ (std::get<1>(a) > std::get<1>(b));
});
// TODO try to add a depth pre-pass
for (auto & [blend_enable, distance, node_ptr, primitive_ptr]: primitives)
object_ubo.model = transform;
for (const auto && [frame_index, frame]: utils::enumerate(frames))
{
components::node & node = *node_ptr;
renderer::primitive & primitive = *primitive_ptr;
object_ubo.modelview[frame_index] = frame.view * transform;
object_ubo.modelviewproj[frame_index] = viewproj[frame_index] * transform;
}
object_ubo.clipping_planes = node.clipping_planes;
glm::mat4 & transform = node.transform_to_root;
// Get the material
std::shared_ptr<renderer::material> material = primitive.material_ ? primitive.material_ : default_material;
// TODO: reuse the UBO if another primitive of the same mesh has already been drawn
// Get the pipeline
pipeline_info info{
.renderpass = rp_info,
.vertex_shader_name = primitive.vertex_shader,
.fragment_shader_name = material->fragment_shader_name,
.vertex_layout = primitive.layout,
.cull_mode = primitive.cull_mode,
.front_face = primitive.front_face,
.topology = primitive.topology,
.blend_enable = material->blend_enable,
.nb_texcoords = 2, // TODO
.skinning = !node.joints.empty(),
};
if (material->double_sided)
info.cull_mode = vk::CullModeFlagBits::eNone;
if (node.reverse_side)
info.front_face = reverse(info.front_face);
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
cb.setViewport(0, vk::Viewport{
.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1,
});
cb.setScissor(0, vk::Rect2D{
.offset = {0, 0},
.extent = output_size,
});
if (primitive.indexed)
cb.bindIndexBuffer(*node.mesh->buffer, primitive.index_offset, primitive.index_type);
std::vector<vk::Buffer> buffers;
buffers.resize(primitive.vertex_offset.size(), (vk::Buffer)*node.mesh->buffer);
cb.bindVertexBuffers(0, buffers, primitive.vertex_offset);
vk::DescriptorBufferInfo buffer_info_1{
.buffer = resources.uniform_buffer,
.offset = frame_ubo_offset,
.range = sizeof(frame_gpu_data),
};
vk::DescriptorBufferInfo buffer_info_2{
.buffer = resources.uniform_buffer,
.offset = instance_ubo_offset,
.range = sizeof(instance_gpu_data),
};
vk::DescriptorBufferInfo buffer_info_3{
.buffer = resources.uniform_buffer,
.offset = joints_ubo_offset,
.range = sizeof(glm::mat4) * 32,
};
vk::DescriptorBufferInfo buffer_info_4{
.buffer = *material->buffer,
.offset = material->offset,
.range = sizeof(renderer::material::gpu_data),
};
auto f = [&](renderer::texture & texture) {
return vk::DescriptorImageInfo{
.sampler = get_sampler(texture.sampler),
.imageView = **(texture.image_view),
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
};
};
std::array write_ds_image{
f(*material->base_color_texture),
f(*material->metallic_roughness_texture),
f(*material->occlusion_texture),
f(*material->emissive_texture),
f(*material->normal_texture),
};
std::array descriptors{
vk::WriteDescriptorSet{
.dstBinding = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_1,
},
vk::WriteDescriptorSet{
.dstBinding = 1,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_2,
},
vk::WriteDescriptorSet{
.dstBinding = 2,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_3,
},
vk::WriteDescriptorSet{
.dstBinding = 3,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data(),
},
vk::WriteDescriptorSet{
.dstBinding = 4,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 1,
},
vk::WriteDescriptorSet{
.dstBinding = 5,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 2,
},
vk::WriteDescriptorSet{
.dstBinding = 6,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 3,
},
vk::WriteDescriptorSet{
.dstBinding = 7,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 4,
},
vk::WriteDescriptorSet{
.dstBinding = 8,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_4,
},
};
cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
if (primitive.indexed)
cb.drawIndexed(primitive.index_count, 1, 0, 0, 0);
else
cb.draw(primitive.vertex_count, 1, 0, 0);
}
if (render_debug_draws and not debug_draw_vertices.empty())
{
size_t size_bytes = std::span{debug_draw_vertices}.size_bytes();
if (not resources.debug_draw or resources.debug_draw.info().size < size_bytes)
{
resources.debug_draw = buffer_allocation{
device,
vk::BufferCreateInfo{
.size = size_bytes,
.usage = vk::BufferUsageFlagBits::eVertexBuffer,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST,
},
"scene_renderer::render (debug draw)",
};
}
memcpy(resources.debug_draw.map(), debug_draw_vertices.data(), size_bytes);
renderer::vertex_layout vertex_layout;
vertex_layout.add_vertex_attribute("Position", vk::Format::eR32G32B32A32Sfloat, 0, 0);
vertex_layout.add_vertex_attribute("Color", vk::Format::eR32G32B32A32Sfloat, 0, 1);
pipeline_info info{
.renderpass = rp_info,
.vertex_shader_name = "debug_draw.vert",
.fragment_shader_name = "debug_draw.frag",
.vertex_layout = vertex_layout,
.cull_mode = vk::CullModeFlagBits::eFrontAndBack,
.front_face = vk::FrontFace::eClockwise,
.topology = vk::PrimitiveTopology::eLineList,
.blend_enable = true,
.depth_test_enable = false,
.depth_write_enable = false,
};
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
cb.setViewport(0, vk::Viewport{
.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1,
});
cb.setScissor(0, vk::Rect2D{
.offset = {0, 0},
.extent = output_size,
});
{
vk::DeviceSize instance_ubo_offset = resources.uniform_buffer_offset;
instance_gpu_data & object_ubo = *reinterpret_cast<instance_gpu_data *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(instance_gpu_data));
vk::DeviceSize joints_ubo_offset = 0;
if (!node.joints.empty())
object_ubo.model = glm::identity<glm::mat4>();
for (const auto && [frame_index, frame]: utils::enumerate(frames))
{
joints_ubo_offset = resources.uniform_buffer_offset;
glm::mat4 * joint_matrices = reinterpret_cast<glm::mat4 *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(glm::mat4) * 32);
assert(node.joints.size() <= 32);
for (auto && [idx, joint]: utils::enumerate(node.joints))
{
glm::mat4 & joint_transform = scene.get<components::node>(joint.first).transform_to_root;
joint_matrices[idx] = glm::inverse(transform) * joint_transform * joint.second;
}
object_ubo.modelview[frame_index] = frame.view;
object_ubo.modelviewproj[frame_index] = viewproj[frame_index];
}
object_ubo.model = transform;
object_ubo.modelview = frame.view * transform;
object_ubo.modelviewproj = viewproj * transform;
object_ubo.clipping_planes = node.clipping_planes;
// Get the material
std::shared_ptr<renderer::material> material = primitive.material_ ? primitive.material_ : default_material;
// Get the pipeline
pipeline_info info{
.renderpass = rp_info,
.shader_name = material->shader_name,
.cull_mode = primitive.cull_mode,
.front_face = primitive.front_face,
.topology = primitive.topology,
.blend_enable = material->alpha_mode == renderer::material::alpha_mode_t::blend or material->alpha_mode == renderer::material::alpha_mode_t::mask,
.nb_texcoords = 2, // TODO
.alpha_cutout = material->alpha_mode == renderer::material::alpha_mode_t::mask,
.skinning = !node.joints.empty(),
};
if (material->double_sided)
info.cull_mode = vk::CullModeFlagBits::eNone;
if (node.reverse_side)
info.front_face = reverse(info.front_face);
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
cb.setViewport(0, vk::Viewport{
.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1,
});
cb.setScissor(0, vk::Rect2D{
.offset = {0, 0},
.extent = output_size,
});
if (primitive.indexed)
cb.bindIndexBuffer(*node.mesh->buffer, primitive.index_offset, primitive.index_type);
cb.bindVertexBuffers(0, (vk::Buffer)*node.mesh->buffer, primitive.vertex_offset);
vk::DescriptorBufferInfo buffer_info_1{
.buffer = resources.uniform_buffer,
.offset = frame_ubo_offset,
@@ -1050,12 +1353,12 @@ void scene_renderer::render(
};
vk::DescriptorBufferInfo buffer_info_3{
.buffer = resources.uniform_buffer,
.offset = joints_ubo_offset,
.offset = 0,
.range = sizeof(glm::mat4) * 32,
};
vk::DescriptorBufferInfo buffer_info_4{
.buffer = *material->buffer,
.offset = material->offset,
.buffer = *default_material->buffer,
.offset = default_material->offset,
.range = sizeof(renderer::material::gpu_data),
};
@@ -1068,11 +1371,11 @@ void scene_renderer::render(
};
std::array write_ds_image{
f(*material->base_color_texture),
f(*material->metallic_roughness_texture),
f(*material->occlusion_texture),
f(*material->emissive_texture),
f(*material->normal_texture),
f(*default_material->base_color_texture),
f(*default_material->metallic_roughness_texture),
f(*default_material->occlusion_texture),
f(*default_material->emissive_texture),
f(*default_material->normal_texture),
};
std::array descriptors{
vk::WriteDescriptorSet{
@@ -1132,12 +1435,57 @@ void scene_renderer::render(
};
cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
if (primitive.indexed)
cb.drawIndexed(primitive.index_count, 1, 0, 0, 0);
else
cb.draw(primitive.vertex_count, 1, 0, 0);
}
cb.endRenderPass();
cb.bindVertexBuffers(0, (vk::Buffer)resources.debug_draw, (vk::DeviceSize)0);
cb.draw(debug_draw_vertices.size(), 1, 0, 0);
}
cb.endRenderPass();
}
void scene_renderer::debug_draw_clear()
{
debug_draw_vertices.clear();
}
void scene_renderer::debug_draw_box(const glm::mat4 & model, glm::vec3 min, glm::vec3 max, glm::vec4 color)
{
std::array<glm::vec4, 8> v{
model * glm::vec4{min.x, min.y, min.z, 1}, // 2-------6 ^
model * glm::vec4{min.x, min.y, max.z, 1}, // /| /| | +Y
model * glm::vec4{min.x, max.y, min.z, 1}, // 3-------7 | |
model * glm::vec4{min.x, max.y, max.z, 1}, // | | | | O--> +X
model * glm::vec4{max.x, min.y, min.z, 1}, // | 0-----|-4 /
model * glm::vec4{max.x, min.y, max.z, 1}, // |/ |/ v
model * glm::vec4{max.x, max.y, min.z, 1}, // 1-------5 +Z
model * glm::vec4{max.x, max.y, max.z, 1}, //
};
debug_draw_vertices.emplace_back(v[0], color);
debug_draw_vertices.emplace_back(v[1], color);
debug_draw_vertices.emplace_back(v[1], color);
debug_draw_vertices.emplace_back(v[3], color);
debug_draw_vertices.emplace_back(v[3], color);
debug_draw_vertices.emplace_back(v[2], color);
debug_draw_vertices.emplace_back(v[2], color);
debug_draw_vertices.emplace_back(v[0], color);
debug_draw_vertices.emplace_back(v[4], color);
debug_draw_vertices.emplace_back(v[5], color);
debug_draw_vertices.emplace_back(v[5], color);
debug_draw_vertices.emplace_back(v[7], color);
debug_draw_vertices.emplace_back(v[7], color);
debug_draw_vertices.emplace_back(v[6], color);
debug_draw_vertices.emplace_back(v[6], color);
debug_draw_vertices.emplace_back(v[4], color);
debug_draw_vertices.emplace_back(v[0], color);
debug_draw_vertices.emplace_back(v[4], color);
debug_draw_vertices.emplace_back(v[1], color);
debug_draw_vertices.emplace_back(v[5], color);
debug_draw_vertices.emplace_back(v[2], color);
debug_draw_vertices.emplace_back(v[6], color);
debug_draw_vertices.emplace_back(v[3], color);
debug_draw_vertices.emplace_back(v[7], color);
}
+42 -7
View File
@@ -18,6 +18,7 @@
#pragma once
#include "render/vertex_layout.h"
#include <array>
#include <cstdint>
#include <glm/mat4x4.hpp>
@@ -42,6 +43,7 @@ struct renderpass_info
bool keep_depth_buffer;
vk::SampleCountFlagBits msaa_samples = vk::SampleCountFlagBits::e1;
bool fragment_density_map;
uint32_t multiview_count;
bool operator==(const renderpass_info & other) const noexcept = default;
};
@@ -50,7 +52,9 @@ struct pipeline_info
{
renderpass_info renderpass;
std::string shader_name;
std::string vertex_shader_name;
std::string fragment_shader_name;
renderer::vertex_layout vertex_layout;
vk::CullModeFlags cull_mode = vk::CullModeFlagBits::eNone;
vk::FrontFace front_face = vk::FrontFace::eClockwise;
@@ -76,7 +80,6 @@ struct output_image_info
VkImage color;
VkImage depth;
VkImage foveation;
uint32_t base_array_layer;
bool operator==(const output_image_info & other) const noexcept = default;
};
@@ -178,8 +181,7 @@ class scene_renderer
struct frame_gpu_data
{
glm::mat4 view;
glm::mat4 proj;
std::array<glm::mat4, 2> view;
glm::vec4 light_position;
glm::vec4 ambient_color;
glm::vec4 light_color;
@@ -188,11 +190,29 @@ class scene_renderer
struct instance_gpu_data
{
glm::mat4 model;
glm::mat4 modelview;
glm::mat4 modelviewproj;
std::array<glm::mat4, 2> modelview;
std::array<glm::mat4, 2> modelviewproj;
std::array<glm::vec4, 4> clipping_planes;
};
struct debug_draw_vertex
{
glm::vec4 position;
glm::vec4 colour;
};
std::vector<debug_draw_vertex> debug_draw_vertices;
public:
struct stats
{
size_t count_primitives;
size_t count_culled_primitives;
size_t count_triangles;
size_t count_culled_triangles;
};
private:
struct per_frame_resources
{
vk::raii::Fence fence = nullptr;
@@ -204,6 +224,11 @@ class scene_renderer
// device local, host visible, host coherent
size_t uniform_buffer_offset;
buffer_allocation uniform_buffer;
buffer_allocation debug_draw;
// Statistics
stats frame_stats;
};
std::vector<per_frame_resources> frame_resources;
@@ -249,9 +274,19 @@ public:
vk::Image color_buffer,
vk::Image depth_buffer,
vk::Image foveation_image,
std::span<frame_info> info);
std::span<frame_info> info,
bool render_debug_draws = false);
void end_frame();
void debug_draw_clear();
// void debug_draw(std::span<glm::vec3> line, glm::vec4 color);
void debug_draw_box(const glm::mat4 & model, glm::vec3 min, glm::vec3 max, glm::vec4 color);
const stats & last_frame_stats() const
{
return frame_resources[current_frame_index].frame_stats;
}
double get_gpu_time() const
{
return gpu_time_s;
+95
View File
@@ -0,0 +1,95 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "utils/magic_hash.h"
#include <cstddef>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <string>
#include <vector>
#include <vulkan/vulkan.hpp>
#include <vulkan/vulkan_format_traits.hpp>
namespace renderer
{
struct vertex_layout
{
std::vector<vk::VertexInputBindingDescription> bindings;
std::vector<vk::VertexInputAttributeDescription> attributes;
std::vector<std::string> attribute_names;
void add_attribute(std::string name, vk::Format format, uint32_t binding, uint32_t location, vk::VertexInputRate input_rate, int array_size = 1)
{
size_t texel_size = vk::blockSize(format);
uint32_t offset = 0;
if (auto iter = std::ranges::find(bindings, binding, &vk::VertexInputBindingDescription::binding); iter == bindings.end())
bindings.push_back(vk::VertexInputBindingDescription{
.binding = binding,
.stride = (uint32_t)(texel_size * array_size),
.inputRate = input_rate,
});
else
{
offset = iter->stride;
iter->stride += texel_size * array_size;
}
for (int index = 0; index < array_size; index++)
{
attributes.push_back(vk::VertexInputAttributeDescription{
.location = location + index,
.binding = binding,
.format = format,
.offset = (uint32_t)(offset + index * texel_size),
});
if (array_size == 1)
attribute_names.push_back(name);
else
attribute_names.push_back(name + "_" + std::to_string(index));
}
}
void add_vertex_attribute(std::string name, vk::Format format, uint32_t binding, uint32_t location, int array_size = 1)
{
add_attribute(std::move(name), format, binding, location, vk::VertexInputRate::eVertex, array_size);
}
bool operator==(const vertex_layout & other) const noexcept = default;
};
} // namespace renderer
namespace std
{
template <>
struct hash<renderer::vertex_layout> : utils::magic_hash<renderer::vertex_layout>
{};
template <>
struct hash<vk::VertexInputBindingDescription> : utils::magic_hash<vk::VertexInputBindingDescription>
{};
template <>
struct hash<vk::VertexInputAttributeDescription> : utils::magic_hash<vk::VertexInputAttributeDescription>
{};
} // namespace std