Misc renderer improvements:

- Reuse renderer and gltf loader between scenes
- Use puish descriptors to simplify the management of descriptor sets in the scene renderer
- Don't keep the imgui swapchain in the scene classes
- Fix alpha blending, add alpha masking
- Fix mipmaps not being used in renderer
- Add cache when loading images and models
- Only premultiply the colours if required
- Add support for gltTF animations

Allow removing an object and its descendants from the scene, allow loading from a memory buffer
This commit is contained in:
Guillaume Meunier
2025-10-23 21:39:12 +02:00
parent 1f6ea0d4ca
commit aad1bb6a1b
21 changed files with 918 additions and 375 deletions
+150
View File
@@ -0,0 +1,150 @@
/*
* 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/>.
*/
#include "animation.h"
#include "render/scene_components.h"
#include <algorithm>
#include <cmath>
#include <entt/entt.hpp>
#include <glm/ext/quaternion_geometric.hpp>
namespace
{
glm::vec3 interp(const glm::vec3 & a, const glm::vec3 & b, float t)
{
return a + t * (b - a);
}
glm::quat interp(const glm::quat & a, const glm::quat & b, float t)
{
float d = glm::dot(a, b);
if (d > 0.99999)
{
return a + t * (b - a);
}
else
{
float θ = std::acos(std::abs(d));
float sinθ = std::sin(θ);
float sinθt = std::sin(θ * t);
float sinθ1_t = std::sin(θ * (1 - t));
return sinθ1_t / sinθ * a + std::copysign(sinθt / sinθ, d) * b;
}
}
glm::vec3 cubic_spline(const glm::vec3 & a, const glm::vec3 & va, const glm::vec3 & vb, const glm::vec3 & b, float t, float td)
{
float t2 = t * t;
float t3 = t2 * t;
return (2 * t3 - 3 * t2 + 1) * a +
td * (t3 - 2 * t2 + t) * va +
(3 * t2 - 2 * t3) * b +
td * (t3 - t2) * vb;
}
glm::quat cubic_spline(const glm::quat & a, const glm::quat & vb, const glm::quat & va, const glm::quat & b, float t, float td)
{
float t2 = t * t;
float t3 = t2 * t;
return glm::normalize((2 * t3 - 3 * t2 + 1) * a +
td * (t3 - 2 * t2 + t) * vb +
(3 * t2 - 2 * t3) * b +
td * (t3 - t2) * va);
}
template <auto components::node::*Field>
void apply_track(entt::registry & scene, const components::animation_track_impl<Field> & track, float current_time)
{
entt::entity target = track.target;
auto interpolation = track.interpolation;
auto field = track.field;
auto & value = scene.get<components::node>(track.target).*field;
// Find the first keyframe with a timestamp strictly greater than the current time
size_t k = std::ranges::upper_bound(track.timestamp, current_time) - track.timestamp.begin();
if (k == 0)
{
value = track.value[0];
return;
}
switch (interpolation)
{
case components::animation_track_base::interpolation_t::step:
value = track.value[k - 1];
break;
case components::animation_track_base::interpolation_t::linear:
if (k == track.timestamp.size())
value = track.value[k - 1];
else
{
float t = (current_time - track.timestamp[k - 1]) / (track.timestamp[k] - track.timestamp[k - 1]);
const auto & a = track.value[k - 1];
const auto & b = track.value[k];
value = interp(a, b, t);
}
break;
case components::animation_track_base::interpolation_t::cubic_spline:
if (k == track.timestamp.size())
value = track.value[k - 1];
else
{
float t = (current_time - track.timestamp[k - 1]) / (track.timestamp[k] - track.timestamp[k - 1]);
const auto & a = track.value[3 * k - 2]; // v_k in gltf spec
const auto & vb = track.value[3 * k - 1]; // b_k
const auto & va = track.value[3 * k]; // a_k+1
const auto & b = track.value[3 * k + 1]; // v_k+1
value = cubic_spline(a, va, vb, b, t, track.timestamp[k] - track.timestamp[k - 1]);
}
break;
}
}
} // namespace
void renderer::animate(entt::registry & scene, float dt)
{
for (auto && [entity, animation]: scene.view<components::animation>().each())
{
if (not animation.playing)
continue;
animation.current_time += dt;
if (animation.current_time > animation.duration)
{
if (animation.looping)
animation.current_time = std::fmod(animation.current_time, animation.duration);
else
animation.current_time = animation.duration;
}
else if (animation.current_time < 0)
animation.current_time = 0;
for (const auto & track: animation.tracks)
std::visit([&](auto & track) { apply_track(scene, track, animation.current_time); }, track);
}
}
+26
View File
@@ -0,0 +1,26 @@
/*
* 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 <entt/entity/fwd.hpp>
namespace renderer
{
void animate(entt::registry & registry, float dt);
}
+59 -45
View File
@@ -318,7 +318,52 @@ image_loader::~image_loader()
ktxVulkanDeviceInfo_Destruct(&vdi); ktxVulkanDeviceInfo_Destruct(&vdi);
} }
loaded_image image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format, const std::string & name) template <typename T>
float alpha_scale;
template <>
float alpha_scale<uint8_t> = 1. / 255.;
template <>
float alpha_scale<uint16_t> = 1. / 65535.;
template <>
float alpha_scale<float> = 1.;
template <typename T>
void premultiply_alpha_aux(T * destination, const T * source, int n)
{
for (int i = 0; i < n; i++)
{
float alpha = source[4 * i + 3] * alpha_scale<T>;
destination[4 * i + 0] = source[4 * i + 0] * alpha;
destination[4 * i + 1] = source[4 * i + 1] * alpha;
destination[4 * i + 2] = source[4 * i + 2] * alpha;
destination[4 * i + 3] = source[4 * i + 3];
}
}
static void premultiply_alpha(void * destination, const void * source, vk::Extent3D extent, vk::Format format)
{
switch (format)
{
case vk::Format::eR8G8B8A8Srgb: // TODO: sRGB
case vk::Format::eR8G8B8A8Unorm:
premultiply_alpha_aux<uint8_t>((uint8_t *)destination, (const uint8_t *)source, extent.width * extent.height * extent.depth);
break;
case vk::Format::eR16G16B16A16Unorm:
premultiply_alpha_aux<uint16_t>((uint16_t *)destination, (const uint16_t *)source, extent.width * extent.height * extent.depth);
break;
case vk::Format::eR32G32B32A32Sfloat:
premultiply_alpha_aux<float>((float *)destination, (const float *)source, extent.width * extent.height * extent.depth);
break;
default:
break;
}
}
loaded_image image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format, const std::string & name, bool premultiply)
{ {
auto cb = std::move(device.allocateCommandBuffers({ auto cb = std::move(device.allocateCommandBuffers({
.commandPool = *cb_pool, .commandPool = *cb_pool,
@@ -346,7 +391,11 @@ loaded_image image_loader::do_load_raw(const void * pixels, vk::Extent3D extent,
}, },
name + " (staging)"}; name + " (staging)"};
memcpy(staging_buffer.map(), pixels, byte_size); if (premultiply)
premultiply_alpha(staging_buffer.map(), pixels, extent, format);
else
memcpy(staging_buffer.map(), pixels, byte_size);
staging_buffer.unmap(); staging_buffer.unmap();
// Allocate image // Allocate image
@@ -544,6 +593,7 @@ loaded_image image_loader::do_load_raw(const void * pixels, vk::Extent3D extent,
.extent = extent, .extent = extent,
.num_mipmaps = num_mipmaps, .num_mipmaps = num_mipmaps,
.image_view_type = image_view_type, .image_view_type = image_view_type,
.is_alpha_premultiplied = premultiply,
}; };
} }
@@ -609,6 +659,7 @@ loaded_image image_loader::do_load_ktx(std::span<const std::byte> bytes, bool sr
.extent{vk::Extent3D(texture->baseWidth, texture->baseHeight, texture->baseDepth)}, .extent{vk::Extent3D(texture->baseWidth, texture->baseHeight, texture->baseDepth)},
.num_mipmaps = texture->numLevels, .num_mipmaps = texture->numLevels,
.image_view_type = vk::ImageViewType(vk_texture.viewType), .image_view_type = vk::ImageViewType(vk_texture.viewType),
.is_alpha_premultiplied = ktxTexture2_GetPremultipliedAlpha(texture),
}; };
} }
@@ -617,42 +668,7 @@ static constexpr bool starts_with(std::span<const std::byte> data, std::span<con
return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size()); return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size());
} }
template <typename T> loaded_image image_loader::do_load_image(std::span<const std::byte> bytes, bool srgb, const std::string & name, bool premultiply)
void premultiply_alpha_aux(T * pixels, float alpha_scale, int width, int height)
{
for (int i = 0, n = width * height; i < n; i++)
{
float alpha = pixels[4 * i + 3] * alpha_scale;
pixels[4 * i + 0] = pixels[4 * i + 0] * alpha;
pixels[4 * i + 1] = pixels[4 * i + 1] * alpha;
pixels[4 * i + 2] = pixels[4 * i + 2] * alpha;
}
}
static void premultiply_alpha(void * pixels, vk::Extent3D extent, vk::Format format)
{
switch (format)
{
case vk::Format::eR8G8B8A8Srgb: // TODO: sRGB
case vk::Format::eR8G8B8A8Unorm:
premultiply_alpha_aux<uint8_t>((uint8_t *)pixels, 1. / 255., extent.width, extent.height);
break;
case vk::Format::eR16G16B16A16Unorm:
premultiply_alpha_aux<uint16_t>((uint16_t *)pixels, 1. / 65535., extent.width, extent.height);
break;
case vk::Format::eR32G32B32A32Sfloat:
premultiply_alpha_aux<float>((float *)pixels, 1, extent.width, extent.height);
break;
default:
break;
}
}
loaded_image image_loader::do_load_image(std::span<const std::byte> bytes, bool srgb, const std::string & name)
{ {
const stbi_uc * image_data = (const stbi_uc *)bytes.data(); const stbi_uc * image_data = (const stbi_uc *)bytes.data();
size_t image_size = bytes.size(); size_t image_size = bytes.size();
@@ -691,13 +707,11 @@ loaded_image image_loader::do_load_image(std::span<const std::byte> bytes, bool
.depth = 1, .depth = 1,
}; };
premultiply_alpha(pixels.get(), extent, format); return do_load_raw(pixels.get(), extent, format, name, premultiply);
return do_load_raw(pixels.get(), extent, format, name);
} }
// Load a PNG/JPEG/KTX2 file // Load a PNG/JPEG/KTX2 file
loaded_image image_loader::load(std::span<const std::byte> bytes, bool srgb, const std::string & name) loaded_image image_loader::load(std::span<const std::byte> bytes, bool srgb, const std::string & name, bool premultiply)
{ {
const uint8_t ktx1_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; const uint8_t ktx1_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
const uint8_t ktx2_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; const uint8_t ktx2_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A};
@@ -705,14 +719,14 @@ loaded_image image_loader::load(std::span<const std::byte> bytes, bool srgb, con
if (starts_with(bytes, ktx1_magic) || starts_with(bytes, ktx2_magic)) if (starts_with(bytes, ktx1_magic) || starts_with(bytes, ktx2_magic))
return do_load_ktx(bytes, srgb, name); return do_load_ktx(bytes, srgb, name);
else else
return do_load_image(bytes, srgb, name); return do_load_image(bytes, srgb, name, premultiply);
} }
// Load raw pixel data // Load raw pixel data
loaded_image image_loader::load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format, const std::string & name) loaded_image image_loader::load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format, const std::string & name, bool premultiply)
{ {
if (size < extent.width * extent.height * extent.depth * bytes_per_pixel(format)) if (size < extent.width * extent.height * extent.depth * bytes_per_pixel(format))
throw std::invalid_argument("size"); throw std::invalid_argument("size");
return do_load_raw(pixels, extent, format, name); return do_load_raw(pixels, extent, format, name, premultiply);
} }
+16 -7
View File
@@ -28,6 +28,7 @@
#include <glm/vec4.hpp> #include <glm/vec4.hpp>
#include <ktxvulkan.h> #include <ktxvulkan.h>
#include <span> #include <span>
#include <utility>
#include <vector> #include <vector>
#include <vulkan/vulkan.hpp> #include <vulkan/vulkan.hpp>
@@ -40,6 +41,7 @@ struct loaded_image
vk::Extent3D extent; vk::Extent3D extent;
uint32_t num_mipmaps; uint32_t num_mipmaps;
vk::ImageViewType image_view_type; vk::ImageViewType image_view_type;
bool is_alpha_premultiplied;
}; };
struct image_loader struct image_loader
@@ -50,29 +52,36 @@ struct image_loader
~image_loader(); ~image_loader();
// Load a PNG/JPEG/KTX2 file // Load a PNG/JPEG/KTX2 file
loaded_image load(std::span<const std::byte> bytes, bool srgb, const std::string & name = ""); loaded_image load(std::span<const std::byte> bytes, bool srgb, const std::string & name = "", bool premultiply = false);
// Load raw pixel data // Load raw pixel data
loaded_image load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format, const std::string & name = ""); loaded_image load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format, const std::string & name = "", bool premultiply = false);
template <typename T> template <typename T>
loaded_image load(std::span<T> pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "") loaded_image load(std::span<T> pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "", bool premultiply = false)
{ {
return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name); return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name);
} }
template <typename T, size_t N> template <typename T, size_t N>
loaded_image load(const std::array<T, N> & pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "") loaded_image load(const std::array<T, N> & pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "", bool premultiply = false)
{ {
return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name); return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name);
} }
template <typename T> template <typename T>
loaded_image load(const std::vector<T> & pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "") loaded_image load(const std::vector<T> & pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "", bool premultiply = false)
{ {
return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name); return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name);
} }
template <typename... Args>
std::shared_ptr<loaded_image> operator()(Args &&... args)
{
auto result = std::make_shared<loaded_image>(load(std::forward<Args>(args)...));
return result;
}
private: private:
ktxVulkanDeviceInfo vdi; ktxVulkanDeviceInfo vdi;
vk::raii::Device & device; vk::raii::Device & device;
@@ -84,8 +93,8 @@ private:
buffer_allocation staging_buffer; buffer_allocation staging_buffer;
loaded_image do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format, const std::string & name); loaded_image do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format, const std::string & name, bool premultiply);
loaded_image do_load_image(std::span<const std::byte> bytes, bool srgb, const std::string & name); loaded_image do_load_image(std::span<const std::byte> bytes, bool srgb, const std::string & name, bool premultiply);
loaded_image do_load_ktx(std::span<const std::byte> bytes, bool srgb, const std::string & name); loaded_image do_load_ktx(std::span<const std::byte> bytes, bool srgb, const std::string & name);
}; };
+25 -15
View File
@@ -190,7 +190,8 @@ imgui_textures::imgui_textures(
vk::raii::PhysicalDevice physical_device, vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device, vk::raii::Device & device,
uint32_t queue_family_index, uint32_t queue_family_index,
thread_safe<vk::raii::Queue> & queue) : thread_safe<vk::raii::Queue> & queue,
std::shared_ptr<image_cache_type> image_cache) :
physical_device(physical_device), physical_device(physical_device),
device(device), device(device),
queue(queue), queue(queue),
@@ -200,8 +201,12 @@ imgui_textures::imgui_textures(
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient, .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient,
.queueFamilyIndex = queue_family_index, .queueFamilyIndex = queue_family_index,
}), }),
image_cache(image_cache),
descriptor_pool(device, ds_layout, layout_bindings) descriptor_pool(device, ds_layout, layout_bindings)
{} {
if (not image_cache)
this->image_cache = std::make_shared<image_cache_type>(physical_device, device, queue, command_pool);
}
std::vector<std::pair<ImVec2, float>> imgui_context::ray_plane_intersection(const imgui_context::controller_state & in) const std::vector<std::pair<ImVec2, float>> imgui_context::ray_plane_intersection(const imgui_context::controller_state & in) const
{ {
@@ -320,20 +325,22 @@ imgui_context::imgui_context(
uint32_t queue_family_index, uint32_t queue_family_index,
thread_safe<vk::raii::Queue> & queue, thread_safe<vk::raii::Queue> & queue,
std::span<controller> controllers_, std::span<controller> controllers_,
xr::swapchain & swapchain, xr::swapchain && swapchain_,
std::vector<viewport> layers) : std::vector<viewport> layers,
std::shared_ptr<image_cache_type> image_cache) :
imgui_textures( imgui_textures(
physical_device, physical_device,
device, device,
queue_family_index, queue_family_index,
queue), queue,
image_cache),
queue_family_index(queue_family_index), queue_family_index(queue_family_index),
renderpass(create_renderpass(device, swapchain.format(), true)), renderpass(create_renderpass(device, swapchain_.format(), true)),
command_buffers(swapchain.images().size()), command_buffers(swapchain_.images().size()),
size(swapchain.extent().width, swapchain.extent().height), size(swapchain_.extent().width, swapchain_.extent().height),
format(swapchain.format()), format(swapchain_.format()),
layers_(std::move(layers)), layers_(std::move(layers)),
swapchain(swapchain), swapchain(std::move(swapchain_)),
context(ImGui::CreateContext()), context(ImGui::CreateContext()),
plot_context(ImPlot::CreateContext()), plot_context(ImPlot::CreateContext()),
io((ImGui::SetCurrentContext(context), ImGui::GetIO())), io((ImGui::SetCurrentContext(context), ImGui::GetIO())),
@@ -1040,15 +1047,18 @@ ImTextureID imgui_textures::load_texture(const std::string & filename, vk::raii:
ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & bytes, vk::raii::Sampler && sampler, const std::string & name) ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & bytes, vk::raii::Sampler && sampler, const std::string & name)
{ {
bool srgb = true; bool srgb = true;
// TODO: reuse the image loader
image_loader loader(physical_device, device, queue, command_pool); std::shared_ptr<loaded_image> image;
auto image = loader.load(bytes, srgb, name); if (name == "")
image = image_cache->load_uncached(bytes, srgb, "", true /* premultiply alpha */);
else
image = image_cache->load(name, bytes, srgb, name, true /* premultiply alpha */);
std::shared_ptr<vk::raii::DescriptorSet> ds = descriptor_pool.allocate(); std::shared_ptr<vk::raii::DescriptorSet> ds = descriptor_pool.allocate();
vk::DescriptorImageInfo image_info{ vk::DescriptorImageInfo image_info{
.sampler = *sampler, .sampler = *sampler,
.imageView = *image.image_view, .imageView = *image->image_view,
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
}; };
@@ -1066,7 +1076,7 @@ ImTextureID imgui_textures::load_texture(const std::span<const std::byte> & byte
id, id,
texture_data{ texture_data{
.sampler = std::move(sampler), .sampler = std::move(sampler),
.image = std::move(image), .image = image,
.descriptor_set = std::move(ds), .descriptor_set = std::move(ds),
}); });
+11 -5
View File
@@ -20,6 +20,7 @@
#include "image_loader.h" #include "image_loader.h"
#include "render/growable_descriptor_pool.h" #include "render/growable_descriptor_pool.h"
#include "utils/cache.h"
#include "utils/thread_safe.h" #include "utils/thread_safe.h"
#include "wivrn_config.h" #include "wivrn_config.h"
#include "xr/hand_tracker.h" #include "xr/hand_tracker.h"
@@ -42,7 +43,7 @@ class imgui_textures
struct texture_data struct texture_data
{ {
vk::raii::Sampler sampler; vk::raii::Sampler sampler;
loaded_image image; std::shared_ptr<loaded_image> image;
std::shared_ptr<vk::raii::DescriptorSet> descriptor_set; std::shared_ptr<vk::raii::DescriptorSet> descriptor_set;
}; };
@@ -53,6 +54,9 @@ protected:
vk::raii::DescriptorSetLayout ds_layout; vk::raii::DescriptorSetLayout ds_layout;
vk::raii::CommandPool command_pool; vk::raii::CommandPool command_pool;
using image_cache_type = utils::cache<std::string, loaded_image, image_loader>;
std::shared_ptr<image_cache_type> image_cache;
private: private:
growable_descriptor_pool descriptor_pool; growable_descriptor_pool descriptor_pool;
std::unordered_map<ImTextureID, texture_data> textures; std::unordered_map<ImTextureID, texture_data> textures;
@@ -62,7 +66,8 @@ public:
vk::raii::PhysicalDevice physical_device, vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device, vk::raii::Device & device,
uint32_t queue_family_index, uint32_t queue_family_index,
thread_safe<vk::raii::Queue> & queue); thread_safe<vk::raii::Queue> & queue,
std::shared_ptr<image_cache_type> image_cache = {});
ImTextureID load_texture(const std::string & filename, vk::raii::Sampler && sampler); ImTextureID load_texture(const std::string & filename, vk::raii::Sampler && sampler);
ImTextureID load_texture(const std::string & filename); ImTextureID load_texture(const std::string & filename);
ImTextureID load_texture(const std::span<const std::byte> & bytes, vk::raii::Sampler && sampler, const std::string & name = ""); ImTextureID load_texture(const std::span<const std::byte> & bytes, vk::raii::Sampler && sampler, const std::string & name = "");
@@ -165,7 +170,7 @@ private:
std::vector<viewport> layers_; std::vector<viewport> layers_;
xr::swapchain & swapchain; xr::swapchain swapchain;
int image_index; int image_index;
ImGuiContext * context; ImGuiContext * context;
@@ -200,8 +205,9 @@ public:
uint32_t queue_family_index, uint32_t queue_family_index,
thread_safe<vk::raii::Queue> & queue, thread_safe<vk::raii::Queue> & queue,
std::span<controller> controllers, std::span<controller> controllers,
xr::swapchain & swapchain, xr::swapchain && swapchain,
std::vector<viewport> layers); std::vector<viewport> layers,
std::shared_ptr<imgui_textures::image_cache_type> image_cache);
~imgui_context(); ~imgui_context();
+63 -13
View File
@@ -20,6 +20,9 @@
#include <array> #include <array>
#include <memory> #include <memory>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector> #include <vector>
#include <entt/entity/entity.hpp> #include <entt/entity/entity.hpp>
@@ -59,6 +62,7 @@ struct material
float roughness_factor = 1; float roughness_factor = 1;
float occlusion_strength = 0; float occlusion_strength = 0;
float normal_scale = 0; float normal_scale = 0;
float alpha_cutoff = 0.5;
uint32_t base_color_texcoord = 0; uint32_t base_color_texcoord = 0;
uint32_t metallic_roughness_texcoord = 0; uint32_t metallic_roughness_texcoord = 0;
@@ -69,6 +73,13 @@ struct material
// TODO: add fastgltf::TextureTransform? // TODO: add fastgltf::TextureTransform?
}; };
enum class alpha_mode_t
{
opaque,
mask,
blend
};
std::shared_ptr<texture> base_color_texture; std::shared_ptr<texture> base_color_texture;
std::shared_ptr<texture> metallic_roughness_texture; std::shared_ptr<texture> metallic_roughness_texture;
std::shared_ptr<texture> occlusion_texture; std::shared_ptr<texture> occlusion_texture;
@@ -78,9 +89,7 @@ struct material
// Disable back face culling with this material // Disable back face culling with this material
bool double_sided = true; bool double_sided = true;
// TODO transparency alpha_mode_t alpha_mode;
// fastgltf::AlphaMode alphaMode;
// float alpha_cutoff;
gpu_data staging; gpu_data staging;
@@ -88,17 +97,8 @@ struct material
std::shared_ptr<buffer_allocation> buffer; std::shared_ptr<buffer_allocation> buffer;
size_t offset; size_t offset;
// The descriptor set is managed by the scene renderer, it is updated whenever ds_dirty is true
// Bindings 0-4: textures
// Binding 5: uniform buffer
std::shared_ptr<vk::raii::DescriptorSet> ds;
// Set to true to update the descriptor set at the next frame
bool ds_dirty;
std::string name; std::string name;
std::string shader_name = "lit"; std::string shader_name = "lit";
bool blend_enable = true;
}; };
struct primitive struct primitive
@@ -118,6 +118,7 @@ struct primitive
std::shared_ptr<material> material_; std::shared_ptr<material> material_;
}; };
// TODO make sure the mesh cannot be changed while it is used
struct mesh struct mesh
{ {
std::vector<primitive> primitives; std::vector<primitive> primitives;
@@ -129,7 +130,7 @@ struct vertex
{ {
glm::vec3 position; glm::vec3 position;
glm::vec3 normal; glm::vec3 normal;
glm::vec3 tangent; glm::vec4 tangent;
std::array<glm::vec2, 2> texcoord; std::array<glm::vec2, 2> texcoord;
glm::vec4 color; glm::vec4 color;
std::array<glm::vec4, 1> joints; std::array<glm::vec4, 1> joints;
@@ -180,6 +181,55 @@ struct node
bool reverse_side; bool reverse_side;
uint32_t global_layer_mask; uint32_t global_layer_mask;
}; };
struct animation_track_base
{
enum class interpolation_t
{
step,
linear,
cubic_spline,
};
entt::entity target;
interpolation_t interpolation;
};
template <auto node::*Field>
struct animation_track_impl : animation_track_base
{
static const constexpr auto field = Field;
using type = std::remove_reference_t<decltype(std::declval<node>().*field)>;
std::vector<float> timestamp;
std::vector<type> value;
};
using animation_track_position = animation_track_impl<&node::position>;
using animation_track_orientation = animation_track_impl<&node::orientation>;
using animation_track_scale = animation_track_impl<&node::scale>;
static_assert(std::is_same_v<animation_track_position::type, glm::vec3>);
static_assert(std::is_same_v<animation_track_orientation::type, glm::quat>);
static_assert(std::is_same_v<animation_track_scale::type, glm::vec3>);
struct animation
{
std::string name;
std::vector<
std::variant<
animation_track_position,
animation_track_orientation,
animation_track_scale>>
tracks;
float duration = 0;
float current_time = 0;
bool playing = true;
bool looping = true;
};
} // namespace components } // namespace components
entt::entity find_node_by_name(entt::registry & scene, std::string_view name); entt::entity find_node_by_name(entt::registry & scene, std::string_view name);
+175 -66
View File
@@ -27,6 +27,7 @@
#include <fastgltf/base64.hpp> #include <fastgltf/base64.hpp>
#include <fastgltf/core.hpp> #include <fastgltf/core.hpp>
#include <fastgltf/glm_element_traits.hpp> #include <fastgltf/glm_element_traits.hpp>
#include <fastgltf/math.hpp>
#include <fastgltf/tools.hpp> #include <fastgltf/tools.hpp>
#include <fastgltf/types.hpp> #include <fastgltf/types.hpp>
#include <fastgltf/util.hpp> #include <fastgltf/util.hpp>
@@ -174,6 +175,36 @@ glm::vec3 convert(const fastgltf::math::nvec3 & v)
{ {
return {v[0], v[1], v[2]}; 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)
{
case fastgltf::AnimationInterpolation::Linear:
return components::animation_track_base::interpolation_t::linear;
case fastgltf::AnimationInterpolation::Step:
return components::animation_track_base::interpolation_t::step;
case fastgltf::AnimationInterpolation::CubicSpline:
return components::animation_track_base::interpolation_t::cubic_spline;
}
throw std::invalid_argument("interpolation");
}
// END // END
// BEGIN Vertex attributes loading // BEGIN Vertex attributes loading
@@ -548,54 +579,54 @@ public:
for (const fastgltf::Material & gltf_material: gltf.materials) for (const fastgltf::Material & gltf_material: gltf.materials)
{ {
// Copy the default material, without references to its buffer or descriptor set // Copy the default material, without references to its buffer or descriptor set
auto & material_ref = *materials.emplace_back(std::make_shared<renderer::material>(default_material)); auto & material = *materials.emplace_back(std::make_shared<renderer::material>(default_material));
material_ref.name = gltf_material.name; material.name = gltf_material.name;
material_ref.buffer.reset(); material.buffer.reset();
material_ref.ds.reset();
material_ref.double_sided = gltf_material.doubleSided; material.double_sided = gltf_material.doubleSided;
material_ref.blend_enable = gltf_material.alphaMode == fastgltf::AlphaMode::Blend; // TODO handle alpha cut off mode material.alpha_mode = convert(gltf_material.alphaMode);
renderer::material::gpu_data & material_data = material_ref.staging; renderer::material::gpu_data & material_data = material.staging;
material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor); material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor);
material_data.base_emissive_factor = glm::vec4(convert(gltf_material.emissiveFactor), 0); material_data.base_emissive_factor = glm::vec4(convert(gltf_material.emissiveFactor), 0);
material_data.metallic_factor = gltf_material.pbrData.metallicFactor; material_data.metallic_factor = gltf_material.pbrData.metallicFactor;
material_data.roughness_factor = gltf_material.pbrData.roughnessFactor; material_data.roughness_factor = gltf_material.pbrData.roughnessFactor;
material_data.alpha_cutoff = gltf_material.alphaCutoff;
if (gltf_material.pbrData.baseColorTexture) if (gltf_material.pbrData.baseColorTexture)
{ {
material_ref.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex); material.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex);
material_data.base_color_texcoord = gltf_material.pbrData.baseColorTexture->texCoordIndex; material_data.base_color_texcoord = gltf_material.pbrData.baseColorTexture->texCoordIndex;
} }
if (gltf_material.pbrData.metallicRoughnessTexture) if (gltf_material.pbrData.metallicRoughnessTexture)
{ {
material_ref.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex); material.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex);
material_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex; material_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex;
} }
if (gltf_material.occlusionTexture) if (gltf_material.occlusionTexture)
{ {
material_ref.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex); material.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex);
material_data.occlusion_texcoord = gltf_material.occlusionTexture->texCoordIndex; material_data.occlusion_texcoord = gltf_material.occlusionTexture->texCoordIndex;
material_data.occlusion_strength = gltf_material.occlusionTexture->strength; material_data.occlusion_strength = gltf_material.occlusionTexture->strength;
} }
if (gltf_material.emissiveTexture) if (gltf_material.emissiveTexture)
{ {
material_ref.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex); material.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex);
material_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex; material_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex;
} }
if (gltf_material.normalTexture) if (gltf_material.normalTexture)
{ {
material_ref.normal_texture = textures.at(gltf_material.normalTexture->textureIndex); material.normal_texture = textures.at(gltf_material.normalTexture->textureIndex);
material_data.normal_texcoord = gltf_material.normalTexture->texCoordIndex; material_data.normal_texcoord = gltf_material.normalTexture->texCoordIndex;
material_data.normal_scale = gltf_material.normalTexture->scale; material_data.normal_scale = gltf_material.normalTexture->scale;
} }
material_ref.offset = staging_buffer.add_uniform(material_data); material.offset = staging_buffer.add_uniform(material_data);
} }
return materials; return materials;
@@ -676,10 +707,8 @@ public:
return meshes; return meshes;
} }
entt::registry load_all_nodes(const std::vector<std::shared_ptr<renderer::mesh>> & meshes) std::vector<entt::entity> load_all_nodes(entt::registry & registry, const std::vector<std::shared_ptr<renderer::mesh>> & meshes)
{ {
entt::registry registry;
std::vector<entt::entity> entities{gltf.nodes.size()}; std::vector<entt::entity> entities{gltf.nodes.size()};
registry.create(entities.begin(), entities.end()); registry.create(entities.begin(), entities.end());
@@ -727,7 +756,117 @@ public:
std::ranges::fill(node.clipping_planes, glm::vec4{0, 0, 0, 1}); std::ranges::fill(node.clipping_planes, glm::vec4{0, 0, 0, 1});
} }
return registry; return entities;
}
void load_all_animations(entt::registry & registry, const std::vector<entt::entity> & node_entities)
{
std::vector<entt::entity> entities{gltf.animations.size()};
registry.create(entities.begin(), entities.end());
// Create all animation components first
registry.insert<components::animation>(entities.begin(), entities.end());
for (const auto & [entity, gltf_animation]: std::ranges::zip_view(entities, gltf.animations))
{
auto & animation = registry.get<components::animation>(entity);
animation.name = gltf_animation.name;
animation.tracks.reserve(gltf_animation.channels.size());
for (const auto & channel: gltf_animation.channels)
{
if (not channel.nodeIndex.has_value() or *channel.nodeIndex > node_entities.size())
// Ignore this channel
continue;
const auto & sampler = gltf_animation.samplers.at(channel.samplerIndex);
const auto & time = gltf.accessors.at(sampler.inputAccessor);
const auto & value = gltf.accessors.at(sampler.outputAccessor);
const auto interpolation = convert(sampler.interpolation);
switch (interpolation)
{
case components::animation_track_base::interpolation_t::step:
case components::animation_track_base::interpolation_t::linear:
if (time.count != value.count)
// There must be the same number of elements
continue;
break;
case components::animation_track_base::interpolation_t::cubic_spline:
// TODO: does not work for morph targets
if (3 * time.count != value.count or time.count < 2)
continue;
break;
}
size_t count = time.count;
switch (channel.path)
{
// TODO: templatize the switch
case fastgltf::AnimationPath::Translation: {
components::animation_track_position track;
track.target = node_entities.at(*channel.nodeIndex);
track.interpolation = interpolation;
track.timestamp.resize(time.count);
track.value.resize(value.count);
fastgltf::iterateAccessorWithIndex<float>(gltf, time, [&](float t, size_t index) {
track.timestamp[index] = t;
animation.duration = std::max(animation.duration, t);
});
fastgltf::iterateAccessorWithIndex<glm::vec3>(gltf, value, [&](glm::vec3 value, size_t index) {
track.value[index] = value;
});
animation.tracks.emplace_back(std::move(track));
break;
}
case fastgltf::AnimationPath::Rotation: {
components::animation_track_orientation track;
track.target = node_entities.at(*channel.nodeIndex);
track.interpolation = interpolation;
track.timestamp.resize(time.count);
track.value.resize(value.count);
fastgltf::iterateAccessorWithIndex<float>(gltf, time, [&](float t, size_t index) {
track.timestamp[index] = t;
animation.duration = std::max(animation.duration, t);
});
fastgltf::iterateAccessorWithIndex<glm::vec4>(gltf, value, [&](glm::vec4 value, size_t index) {
track.value[index] = glm::quat::wxyz(value.w, value.x, value.y, value.z);
});
animation.tracks.emplace_back(std::move(track));
break;
}
case fastgltf::AnimationPath::Scale: {
components::animation_track_scale track;
track.target = node_entities.at(*channel.nodeIndex);
track.interpolation = interpolation;
track.timestamp.resize(time.count);
track.value.resize(value.count);
fastgltf::iterateAccessorWithIndex<float>(gltf, time, [&](float t, size_t index) {
track.timestamp[index] = t;
animation.duration = std::max(animation.duration, t);
});
fastgltf::iterateAccessorWithIndex<glm::vec3>(gltf, value, [&](glm::vec3 value, size_t index) {
track.value[index] = value;
});
animation.tracks.emplace_back(std::move(track));
break;
}
case fastgltf::AnimationPath::Weights:
// TODO morph weights
break;
}
}
}
} }
}; };
@@ -779,7 +918,7 @@ renderer::vertex::describe()
return desc; return desc;
} }
entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path) 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(); vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{ vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{
@@ -787,16 +926,12 @@ entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path)
.queueFamilyIndex = queue_family_index, .queueFamilyIndex = queue_family_index,
}}; }};
spdlog::debug("Loading {}", gltf_path.native()); auto data_buffer = fastgltf::GltfDataBuffer::FromBytes(data.data(), data.size());
asset asset_file(gltf_path);
auto data_buffer = fastgltf::GltfDataBuffer::FromBytes(asset_file.data(), asset_file.size());
if (auto error = data_buffer.error(); error != fastgltf::Error::None) if (auto error = data_buffer.error(); error != fastgltf::Error::None)
throw std::system_error((int)error, fastgltf_error_category); throw std::system_error((int)error, fastgltf_error_category);
fastgltf::Asset asset = load_gltf_asset(data_buffer.get(), gltf_path.parent_path()); fastgltf::Asset asset = load_gltf_asset(data_buffer.get(), parent_path);
loader_context ctx(gltf_path.parent_path(), gltf_path, asset, physical_device, device, queue, cb_pool); loader_context ctx(parent_path, name, asset, physical_device, device, queue, cb_pool);
#ifndef NDEBUG #ifndef NDEBUG
if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None) if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None)
@@ -818,7 +953,11 @@ entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path)
auto meshes = ctx.load_all_meshes(materials, staging_buffer); auto meshes = ctx.load_all_meshes(materials, staging_buffer);
// Load all nodes // Load all nodes
entt::registry loaded_scene = ctx.load_all_nodes(meshes); auto loaded_scene = std::make_shared<entt::registry>();
auto node_entities = ctx.load_all_nodes(*loaded_scene, meshes);
// Load animations
ctx.load_all_animations(*loaded_scene, node_entities);
// Copy the staging buffer to the GPU // Copy the staging buffer to the GPU
spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size()); spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size());
@@ -833,45 +972,15 @@ entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path)
return loaded_scene; return loaded_scene;
} }
template <typename T> std::shared_ptr<entt::registry> scene_loader::operator()(const std::filesystem::path & gltf_path)
void copy_components(entt::registry & scene, const entt::registry & prefab, const std::unordered_map<entt::entity, entt::entity> & entity_map)
{ {
for (const auto & [entity, component]: prefab.view<T>().each()) spdlog::debug("Loading {}", gltf_path.native());
{
scene.emplace<T>(entity_map.at(entity), component); asset asset_file(gltf_path);
}
} auto data_buffer = fastgltf::GltfDataBuffer::FromBytes(asset_file.data(), asset_file.size());
if (auto error = data_buffer.error(); error != fastgltf::Error::None)
void scene_loader::add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root) throw std::system_error((int)error, fastgltf_error_category);
{
assert(scene.valid(root) or root == entt::null); return (*this)(asset_file, gltf_path.filename(), gltf_path.parent_path());
auto prefab_entities = prefab.view<entt::entity>();
std::vector<entt::entity> scene_entities{prefab_entities.size()};
scene.create(scene_entities.begin(), scene_entities.end());
std::unordered_map<entt::entity, entt::entity> entity_map; // key: prefab entity, value: scene entity
entity_map.emplace(entt::null, root);
for (auto [prefab_entity, scene_entity]: std::ranges::zip_view(prefab_entities, scene_entities))
entity_map.emplace(prefab_entity, scene_entity);
copy_components<components::node>(scene, prefab, entity_map);
// update links
for (auto [prefab_entity, scene_entity]: entity_map)
{
if (prefab_entity == entt::null)
continue;
auto & node = scene.get<components::node>(scene_entity);
node.parent = entity_map.at(node.parent);
for (auto & joint: node.joints)
{
joint.first = entity_map.at(joint.first);
}
}
} }
+4 -3
View File
@@ -18,6 +18,7 @@
#pragma once #pragma once
#include <entt/core/fwd.hpp>
#include <filesystem> #include <filesystem>
#include <vulkan/vulkan_raii.hpp> #include <vulkan/vulkan_raii.hpp>
@@ -40,8 +41,8 @@ public:
queue_family_index(queue_family_index), queue_family_index(queue_family_index),
default_material(default_material) default_material(default_material)
{} {}
scene_loader(const scene_loader &) = default;
entt::registry operator()(const std::filesystem::path & gltf_path); std::shared_ptr<entt::registry> operator()(const std::filesystem::path & gltf_path);
std::shared_ptr<entt::registry> operator()(std::span<const std::byte> data, const std::string & name = "", const std::filesystem::path & parent_path = "");
void add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root = entt::null);
}; };
+96 -118
View File
@@ -140,58 +140,64 @@ static vk::FrontFace reverse(vk::FrontFace face)
static std::array layout_bindings_0{ static std::array layout_bindings_0{
vk::DescriptorSetLayoutBinding{ vk::DescriptorSetLayoutBinding{
// scene_ubo: per-frame/view data
.binding = 0, .binding = 0,
.descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
}, },
vk::DescriptorSetLayoutBinding{ vk::DescriptorSetLayoutBinding{
// mesh_ubo: per-instance data
.binding = 1, .binding = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
}, },
vk::DescriptorSetLayoutBinding{ vk::DescriptorSetLayoutBinding{
// joints_ubo: skeletal animation
.binding = 2, .binding = 2,
.descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
}, },
};
static std::array layout_bindings_1{
vk::DescriptorSetLayoutBinding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{
.binding = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{
.binding = 2,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{ vk::DescriptorSetLayoutBinding{
// base_color
.binding = 3, .binding = 3,
.descriptorType = vk::DescriptorType::eCombinedImageSampler, .descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment, .stageFlags = vk::ShaderStageFlagBits::eFragment,
}, },
vk::DescriptorSetLayoutBinding{ vk::DescriptorSetLayoutBinding{
// metallic_roughness
.binding = 4, .binding = 4,
.descriptorType = vk::DescriptorType::eCombinedImageSampler, .descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment, .stageFlags = vk::ShaderStageFlagBits::eFragment,
}, },
vk::DescriptorSetLayoutBinding{ vk::DescriptorSetLayoutBinding{
// occlusion
.binding = 5, .binding = 5,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{
// emissive
.binding = 6,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{
// normal_map
.binding = 7,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{
// material_ubo
.binding = 8,
.descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment, .stageFlags = vk::ShaderStageFlagBits::eFragment,
@@ -208,9 +214,7 @@ scene_renderer::scene_renderer(
device(device), device(device),
physical_device_properties(physical_device.getProperties()), physical_device_properties(physical_device.getProperties()),
queue(queue), queue(queue),
layout_0(create_descriptor_set_layout(layout_bindings_0, vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR)), layout_0(create_descriptor_set_layout(layout_bindings_0, vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR))
layout_1(create_descriptor_set_layout(layout_bindings_1)),
ds_pool_material(device, layout_1, layout_bindings_1, 100) // TODO tunable
{ {
// Create the default material // Create the default material
default_material = create_default_material(cb_pool); default_material = create_default_material(cb_pool);
@@ -237,7 +241,7 @@ scene_renderer::scene_renderer(
.queryCount = uint32_t(2 * frames_in_flight), .queryCount = uint32_t(2 * frames_in_flight),
}); });
std::array layouts{*layout_0, *layout_1}; std::array layouts{*layout_0};
pipeline_layout = create_pipeline_layout(layouts); pipeline_layout = create_pipeline_layout(layouts);
} }
@@ -588,7 +592,7 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
.ColorBlendState = {vk::PipelineColorBlendStateCreateInfo{}}, .ColorBlendState = {vk::PipelineColorBlendStateCreateInfo{}},
.ColorBlendAttachments = {vk::PipelineColorBlendAttachmentState{ .ColorBlendAttachments = {vk::PipelineColorBlendAttachmentState{
.blendEnable = info.blend_enable, .blendEnable = info.blend_enable,
.srcColorBlendFactor = vk::BlendFactor::eOne, .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha,
.dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha,
.colorBlendOp = vk::BlendOp::eAdd, .colorBlendOp = vk::BlendOp::eAdd,
.srcAlphaBlendFactor = vk::BlendFactor::eOne, .srcAlphaBlendFactor = vk::BlendFactor::eOne,
@@ -621,6 +625,8 @@ vk::Sampler scene_renderer::get_sampler(const renderer::sampler_info & info)
.addressModeV = info.wrapT, .addressModeV = info.wrapT,
// .anisotropyEnable = true, // .anisotropyEnable = true,
// .maxAnisotropy = 4, // .maxAnisotropy = 4,
.minLod = 0,
.maxLod = vk::LodClampNone,
}); });
samplers.emplace(info, out); samplers.emplace(info, out);
@@ -695,84 +701,6 @@ scene_renderer::per_frame_resources & scene_renderer::current_frame()
return frame_resources[current_frame_index]; return frame_resources[current_frame_index];
} }
void scene_renderer::update_material_descriptor_set(renderer::material & material)
{
if (!material.ds || material.ds.use_count() != 1)
material.ds = ds_pool_material.allocate();
vk::DescriptorSet ds = **material.ds;
auto f = [&](std::shared_ptr<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),
};
vk::DescriptorBufferInfo write_ds_buffer{
.buffer = *material.buffer,
.offset = material.offset,
.range = sizeof(renderer::material::gpu_data),
};
// Write each descriptor separately because the HTC XR Elite needs it for some reason
std::array write_ds{
vk::WriteDescriptorSet{
.dstSet = ds,
.dstBinding = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data(),
},
vk::WriteDescriptorSet{
.dstSet = ds,
.dstBinding = 1,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 1,
},
vk::WriteDescriptorSet{
.dstSet = ds,
.dstBinding = 2,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 2,
},
vk::WriteDescriptorSet{
.dstSet = ds,
.dstBinding = 3,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 3,
},
vk::WriteDescriptorSet{
.dstSet = ds,
.dstBinding = 4,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 4,
},
vk::WriteDescriptorSet{
.dstSet = ds,
.dstBinding = (uint32_t)write_ds_image.size(),
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &write_ds_buffer,
},
};
device.updateDescriptorSets(write_ds, {});
}
[[maybe_unused]] static void print_scene_hierarchy(const entt::registry & scene, entt::entity root = entt::null, int level = 0) [[maybe_unused]] static void print_scene_hierarchy(const entt::registry & scene, entt::entity root = entt::null, int level = 0)
{ {
if (level == 0) if (level == 0)
@@ -949,7 +877,7 @@ void scene_renderer::render(
for (renderer::primitive & primitive: node.mesh->primitives) for (renderer::primitive & primitive: node.mesh->primitives)
{ {
renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material; renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material;
primitives.emplace_back(material.blend_enable, position.z, &node, &primitive); 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);
} }
} }
@@ -1003,9 +931,6 @@ void scene_renderer::render(
// Get the material // Get the material
std::shared_ptr<renderer::material> material = primitive.material_ ? primitive.material_ : default_material; std::shared_ptr<renderer::material> material = primitive.material_ ? primitive.material_ : default_material;
if (material->ds_dirty || !material->ds)
update_material_descriptor_set(*material);
// Get the pipeline // Get the pipeline
pipeline_info info{ pipeline_info info{
.renderpass = { .renderpass = {
@@ -1016,9 +941,10 @@ void scene_renderer::render(
.cull_mode = primitive.cull_mode, .cull_mode = primitive.cull_mode,
.front_face = primitive.front_face, .front_face = primitive.front_face,
.topology = primitive.topology, .topology = primitive.topology,
.blend_enable = material->blend_enable, .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 .nb_texcoords = 2, // TODO
.alpha_cutout = material->alpha_mode == renderer::material::alpha_mode_t::mask,
.skinning = !node.joints.empty(), .skinning = !node.joints.empty(),
}; };
@@ -1052,18 +978,39 @@ void scene_renderer::render(
vk::DescriptorBufferInfo buffer_info_1{ vk::DescriptorBufferInfo buffer_info_1{
.buffer = resources.uniform_buffer, .buffer = resources.uniform_buffer,
.offset = frame_ubo_offset, .offset = frame_ubo_offset,
.range = sizeof(frame_gpu_data) .range = sizeof(frame_gpu_data),
}; };
vk::DescriptorBufferInfo buffer_info_2{ vk::DescriptorBufferInfo buffer_info_2{
.buffer = resources.uniform_buffer, .buffer = resources.uniform_buffer,
.offset = instance_ubo_offset, .offset = instance_ubo_offset,
.range = sizeof(instance_gpu_data)}; .range = sizeof(instance_gpu_data),
};
vk::DescriptorBufferInfo buffer_info_3{ vk::DescriptorBufferInfo buffer_info_3{
.buffer = resources.uniform_buffer, .buffer = resources.uniform_buffer,
.offset = joints_ubo_offset, .offset = joints_ubo_offset,
.range = sizeof(glm::mat4) * 32}; .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{ std::array descriptors{
vk::WriteDescriptorSet{ vk::WriteDescriptorSet{
.dstBinding = 0, .dstBinding = 0,
@@ -1083,19 +1030,50 @@ void scene_renderer::render(
.descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_3, .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); cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
// Set 1: material
cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 1, **material->ds, {});
if (primitive.indexed) if (primitive.indexed)
cb.drawIndexed(primitive.index_count, 1, 0, 0, 0); cb.drawIndexed(primitive.index_count, 1, 0, 0, 0);
else else
cb.draw(primitive.vertex_count, 1, 0, 0); cb.draw(primitive.vertex_count, 1, 0, 0);
resources.resources.push_back(material->ds);
} }
cb.endRenderPass(); cb.endRenderPass();
} }
+2 -8
View File
@@ -32,7 +32,6 @@
#include "vk/allocation.h" #include "vk/allocation.h"
#include "render/growable_descriptor_pool.h"
#include "render/scene_components.h" #include "render/scene_components.h"
#include "utils/thread_safe.h" #include "utils/thread_safe.h"
@@ -138,11 +137,7 @@ class scene_renderer
vk::raii::Pipeline & get_pipeline(const pipeline_info & info); vk::raii::Pipeline & get_pipeline(const pipeline_info & info);
vk::raii::RenderPass & get_renderpass(const renderpass_info & info); vk::raii::RenderPass & get_renderpass(const renderpass_info & info);
vk::raii::DescriptorSetLayout layout_0; // Descriptor set 0: per-frame/view data (UBO) and per-instance data (UBO + SSBO) vk::raii::DescriptorSetLayout layout_0; // Descriptor set 0: per-frame/view data (UBO), per-instance data (UBO + SSBO), per-material data (5 combined image samplers and 1 uniform buffer)
vk::raii::DescriptorSetLayout layout_1; // Descriptor set 1: per-material data (5 combined image samplers and 1 uniform buffer)
// Descriptor set 1: per-material data (5 combined image samplers and 1 uniform buffer)
growable_descriptor_pool ds_pool_material;
vk::raii::PipelineLayout pipeline_layout = nullptr; vk::raii::PipelineLayout pipeline_layout = nullptr;
@@ -164,6 +159,7 @@ class scene_renderer
// roughness_factor 1.0 // roughness_factor 1.0
// occlusion_strength 0.0 // occlusion_strength 0.0
// normal_scale 0.0 // normal_scale 0.0
// alpha_cutoff 0.5
std::shared_ptr<renderer::material> default_material; std::shared_ptr<renderer::material> default_material;
struct frame_gpu_data struct frame_gpu_data
@@ -203,8 +199,6 @@ class scene_renderer
per_frame_resources & current_frame(); per_frame_resources & current_frame();
void update_material_descriptor_set(renderer::material & material);
public: public:
static vk::Format find_usable_image_format( static vk::Format find_usable_image_format(
vk::raii::PhysicalDevice physical_device, vk::raii::PhysicalDevice physical_device,
+135 -20
View File
@@ -19,15 +19,17 @@
#include "scene.h" #include "scene.h"
#include "application.h" #include "application.h"
#include "render/scene_loader.h" #include "render/scene_components.h"
#include "utils/contains.h" #include "utils/contains.h"
#include "utils/i18n.h" #include "utils/i18n.h"
#include "utils/overloaded.h" #include "utils/overloaded.h"
#include "utils/ranges.h" #include "utils/ranges.h"
#include <chrono>
#include <entt/core/fwd.hpp>
#include <magic_enum.hpp> #include <magic_enum.hpp>
#include <spdlog/fmt/chrono.h>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <vulkan/vulkan_raii.hpp> #include <vulkan/vulkan_raii.hpp>
#include <vulkan/vulkan_structs.hpp>
#include <openxr/openxr.h> #include <openxr/openxr.h>
// TODO remove constants // TODO remove constants
@@ -37,7 +39,7 @@ std::vector<scene::meta *> scene::scene_registry;
scene::~scene() {} scene::~scene() {}
scene::scene(key, const meta & current_meta, std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats) : scene::scene(key, const meta & current_meta, std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats, scene * parent_scene) :
instance(application::instance().xr_instance), instance(application::instance().xr_instance),
system(application::instance().xr_system_id), system(application::instance().xr_system_id),
session(application::instance().xr_session), session(application::instance().xr_session),
@@ -87,6 +89,20 @@ scene::scene(key, const meta & current_meta, std::span<const vk::Format> support
instance.has_extension(XR_FB_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME); instance.has_extension(XR_FB_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME);
composition_layer_color_scale_bias_supported = instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME); composition_layer_color_scale_bias_supported = instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME);
if (parent_scene)
{
renderer = parent_scene->renderer;
gltf_cache = parent_scene->gltf_cache;
image_cache = parent_scene->image_cache;
}
else
{
// TODO: make argument order more consistent
renderer = std::make_shared<scene_renderer>(device, physical_device, queue, commandpool);
gltf_cache = std::make_shared<gltf_cache_type>(device, physical_device, queue, queue_family_index, renderer->get_default_material());
image_cache = std::make_shared<image_cache_type>(physical_device, device, queue, commandpool);
}
} }
void scene::set_focused(bool status) void scene::set_focused(bool status)
@@ -254,17 +270,18 @@ xr::swapchain & scene::get_swapchain(vk::Format format, int32_t width, int32_t h
} }
spdlog::info("Creating new swapchain: {}, {}x{}, {} sample(s), {} level(s)", magic_enum::enum_name(format), width, height, sample_count, array_size); spdlog::info("Creating new swapchain: {}, {}x{}, {} sample(s), {} level(s)", magic_enum::enum_name(format), width, height, sample_count, array_size);
swapchain_entry new_swapchain{
.format = format,
.width = width,
.height = height,
.sample_count = sample_count,
.array_size = array_size,
.used = true,
.swapchain = xr::swapchain(session, device, format, width, height, sample_count, array_size),
};
spdlog::info("Created swapchain");
return swapchains.emplace_back(swapchain_entry{ return swapchains.emplace_back(std::move(new_swapchain)).swapchain;
.format = format,
.width = width,
.height = height,
.sample_count = sample_count,
.array_size = array_size,
.used = true,
.swapchain = xr::swapchain(session, device, format, width, height, sample_count, array_size),
})
.swapchain;
} }
void scene::clear_swapchains() void scene::clear_swapchains()
@@ -434,18 +451,116 @@ void scene::render_end()
session.end_frame(predicted_display_time, openxr_layers, blend_mode); session.end_frame(predicted_display_time, openxr_layers, blend_mode);
} }
std::pair<entt::entity, components::node &> scene::load_gltf(const std::filesystem::path & path, uint32_t layer_mask) template <typename T>
void copy_components(entt::registry & scene, const entt::registry & prefab, const std::unordered_map<entt::entity, entt::entity> & entity_map)
{ {
auto entity = world.create(); for (const auto & [entity, component]: prefab.view<T>().each())
auto & node = world.emplace<components::node>(entity); {
scene.emplace<T>(entity_map.at(entity), component);
}
}
std::pair<entt::entity, components::node &> scene::add_gltf(std::shared_ptr<entt::registry> gltf, uint32_t layer_mask)
{
auto root = world.create();
auto & node = world.emplace<components::node>(root);
node.layer_mask = layer_mask; node.layer_mask = layer_mask;
assert(renderer); auto prefab_entities = gltf->view<entt::entity>();
scene_loader loader(device, physical_device, queue, queue_family_index, renderer->get_default_material());
loader.add_prefab(world, loader(path), entity); std::vector<entt::entity> scene_entities{prefab_entities.size()};
world.create(scene_entities.begin(), scene_entities.end());
return {entity, node}; std::unordered_map<entt::entity, entt::entity> entity_map; // key: prefab entity, value: scene entity
entity_map.emplace(entt::null, root);
for (auto [prefab_entity, scene_entity]: std::ranges::zip_view(prefab_entities, scene_entities))
entity_map.emplace(prefab_entity, scene_entity);
copy_components<components::node>(world, *gltf, entity_map);
copy_components<components::animation>(world, *gltf, entity_map);
// update links
for (auto [prefab_entity, scene_entity]: entity_map)
{
if (prefab_entity == entt::null)
continue;
auto * node = world.try_get<components::node>(scene_entity);
auto * anim = world.try_get<components::animation>(scene_entity);
if (node)
{
node->parent = entity_map.at(node->parent);
for (auto & joint: node->joints)
{
joint.first = entity_map.at(joint.first);
}
}
if (anim)
{
for (auto & track: anim->tracks)
{
std::visit(utils::overloaded{[&](auto & t) { t.target = entity_map.at(t.target); }}, track);
}
}
}
return {root, node};
}
std::shared_ptr<entt::registry> scene::load_gltf(const std::filesystem::path & path)
{
return gltf_cache->load(path.native(), path);
}
std::shared_ptr<entt::registry> scene::load_gltf(std::span<const std::byte> data)
{
return gltf_cache->load_uncached(data);
}
std::pair<entt::entity, components::node &> scene::add_gltf(const std::filesystem::path & path, uint32_t layer_mask)
{
return add_gltf(load_gltf(path), layer_mask);
}
std::pair<entt::entity, components::node &> scene::add_gltf(std::span<const std::byte> data, uint32_t layer_mask)
{
return add_gltf(load_gltf(data), layer_mask);
}
void scene::remove(entt::entity entity)
{
std::vector to_be_removed{entity};
while (not to_be_removed.empty())
{
entt::entity parent = to_be_removed.back();
to_be_removed.pop_back();
spdlog::info("Destroying entity {}", (int)parent);
world.destroy(parent);
for (auto [e, node]: world.view<components::node>().each())
{
if (node.parent == parent)
to_be_removed.push_back(e);
}
for (auto [e, anim]: world.view<components::animation>().each())
{
if (std::ranges::any_of(anim.tracks,
[&](const auto & track) { return std::visit(
[&](const components::animation_track_base & track) {
return track.target == parent;
},
track); }))
{
to_be_removed.push_back(e);
}
}
}
} }
void scene::on_unfocused() {} void scene::on_unfocused() {}
+28 -13
View File
@@ -19,7 +19,11 @@
#pragma once #pragma once
#include "render/image_loader.h"
#include "render/imgui_impl.h"
#include "render/scene_loader.h" #include "render/scene_loader.h"
#include "render/scene_renderer.h"
#include "utils/cache.h"
#include "xr/actionset.h" #include "xr/actionset.h"
#include "xr/instance.h" #include "xr/instance.h"
#include "xr/session.h" #include "xr/session.h"
@@ -27,15 +31,12 @@
#include "xr/system.h" #include "xr/system.h"
#include <cstdint> #include <cstdint>
#include <entt/entity/registry.hpp>
#include <filesystem> #include <filesystem>
#include <span> #include <span>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include "render/imgui_impl.h"
#include "render/scene_renderer.h"
#include <entt/entity/registry.hpp>
#include <openxr/openxr.h> #include <openxr/openxr.h>
// See http://www.nirfriedman.com/2018/04/29/unforgettable-factory/ // See http://www.nirfriedman.com/2018/04/29/unforgettable-factory/
@@ -98,12 +99,14 @@ protected:
const meta & current_meta; const meta & current_meta;
std::optional<scene_renderer> renderer; std::shared_ptr<scene_renderer> renderer;
public: using gltf_cache_type = utils::cache<std::string, entt::registry, scene_loader>;
std::optional<scene_loader> loader; std::shared_ptr<gltf_cache_type> gltf_cache;
using image_cache_type = utils::cache<std::string, loaded_image, image_loader>;
std::shared_ptr<image_cache_type> image_cache;
protected:
vk::Format swapchain_format; vk::Format swapchain_format;
vk::Format depth_format; vk::Format depth_format;
bool composition_layer_depth_test_supported; bool composition_layer_depth_test_supported;
@@ -196,7 +199,7 @@ protected:
virtual void on_focused(); virtual void on_focused();
public: public:
scene(key, const meta &, std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats); scene(key, const meta &, std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats, scene * parent_scene);
virtual ~scene(); virtual ~scene();
@@ -205,8 +208,14 @@ public:
virtual void on_xr_event(const xr::event &); virtual void on_xr_event(const xr::event &);
entt::registry world; entt::registry world;
std::pair<entt::entity, components::node &> load_gltf(const std::filesystem::path & path, uint32_t layer_mask = -1);
void remove(entt::entity entity); // TODO std::shared_ptr<entt::registry> load_gltf(const std::filesystem::path & path);
std::shared_ptr<entt::registry> load_gltf(std::span<const std::byte> data);
std::pair<entt::entity, components::node &> add_gltf(std::shared_ptr<entt::registry> gltf, uint32_t layer_mask = -1);
std::pair<entt::entity, components::node &> add_gltf(const std::filesystem::path & path, uint32_t layer_mask = -1);
std::pair<entt::entity, components::node &> add_gltf(std::span<const std::byte> data, uint32_t layer_mask = -1);
void remove(entt::entity entity);
}; };
template <typename T> template <typename T>
@@ -224,8 +233,14 @@ class scene_impl : public scene
static inline bool registered = scene_impl<T>::register_scene(); static inline bool registered = scene_impl<T>::register_scene();
scene_impl(std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats = {}) : scene_impl(std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats, scene & parent_scene) :
scene(key{}, T::get_meta_scene(), supported_color_formats, supported_depth_formats) scene(key{}, T::get_meta_scene(), supported_color_formats, supported_depth_formats, &parent_scene)
{
(void)registered;
}
scene_impl(std::span<const vk::Format> supported_color_formats, std::span<const vk::Format> supported_depth_formats) :
scene(key{}, T::get_meta_scene(), supported_color_formats, supported_depth_formats, nullptr)
{ {
(void)registered; (void)registered;
} }
+1 -1
View File
@@ -67,7 +67,7 @@ void hand_model::add_hand(scene & scene,
const std::filesystem::path & gltf_path, const std::filesystem::path & gltf_path,
uint32_t layer_mask) uint32_t layer_mask)
{ {
auto && [entity, node] = scene.load_gltf(gltf_path, layer_mask); auto && [entity, node] = scene.add_gltf(gltf_path, layer_mask);
node.name = gltf_path.stem(); node.name = gltf_path.stem();
+10 -16
View File
@@ -182,7 +182,7 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p
id = std::string(root["profileId"]); id = std::string(root["profileId"]);
std::vector<std::tuple<std::string, entt::entity, entt::registry>> models; std::vector<std::tuple<std::string, entt::entity, std::shared_ptr<entt::registry>>> models;
std::vector<json_visual_response> json_responses; std::vector<json_visual_response> json_responses;
// Fill models with the different models to be loaded and their name ("left" or "right") // Fill models with the different models to be loaded and their name ("left" or "right")
@@ -193,9 +193,7 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p
// std::string user_path = "/user/hand/" + std::string(layout.key); // std::string user_path = "/user/hand/" + std::string(layout.key);
std::filesystem::path asset_path = json_profile.parent_path() / std::string(layout.value["assetPath"]); std::filesystem::path asset_path = json_profile.parent_path() / std::string(layout.value["assetPath"]);
// scene.load_gltf(asset_path); std::shared_ptr<entt::registry> data = std::get<2>(models.emplace_back(layout.key, entt::null, scene.load_gltf(asset_path)));
entt::registry & data = std::get<2>(models.emplace_back(layout.key, entt::null, (*scene.loader)(asset_path)));
for (simdjson::dom::key_value_pair component: simdjson::dom::object(layout.value["components"])) for (simdjson::dom::key_value_pair component: simdjson::dom::object(layout.value["components"]))
{ {
@@ -221,14 +219,14 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p
vr.component_subpath = component_subpath; vr.component_subpath = component_subpath;
// Check if the node exists // Check if the node exists
find_node_by_name(data, vr.target_node); find_node_by_name(*data, vr.target_node);
auto node_property = parse_value_node_property(response.value["valueNodeProperty"]); auto node_property = parse_value_node_property(response.value["valueNodeProperty"]);
switch (node_property) switch (node_property)
{ {
case value_node_property::transform: { case value_node_property::transform: {
auto min_node = data.get<components::node>(find_node_by_name(data, std::string(response.value["minNodeName"]))); auto min_node = data->get<components::node>(find_node_by_name(*data, std::string(response.value["minNodeName"])));
auto max_node = data.get<components::node>(find_node_by_name(data, std::string(response.value["maxNodeName"]))); auto max_node = data->get<components::node>(find_node_by_name(*data, std::string(response.value["maxNodeName"])));
components::details::node_state_transform min{ components::details::node_state_transform min{
min_node.position, min_node.position,
@@ -265,14 +263,10 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p
else else
continue; continue;
entity = scene.world.create(); auto [e, node] = scene.add_gltf(model, layer_mask_controller);
scene.world.emplace<bound_space>(entity, space); node.name = layout;
scene.world.emplace<components::node>(entity, components::node{ entity = e;
.name = layout, scene.world.emplace<bound_space>(e, space);
.layer_mask = layer_mask_controller,
});
scene.loader->add_prefab(scene.world, std::move(model), entity);
spdlog::debug("Created entity {}", layout); spdlog::debug("Created entity {}", layout);
} }
@@ -287,7 +281,7 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p
else else
continue; continue;
auto && [entity, node] = scene.load_gltf(controller_ray_model_name(), layer_mask_ray); auto && [entity, node] = scene.add_gltf(controller_ray_model_name(), layer_mask_ray);
node.name = (std::string)layout.key + "_ray"; node.name = (std::string)layout.key + "_ray";
spdlog::debug("Created entity {}", node.name); spdlog::debug("Created entity {}", node.name);
+18 -13
View File
@@ -26,6 +26,7 @@
#include "imgui.h" #include "imgui.h"
#include "openxr/openxr.h" #include "openxr/openxr.h"
#include "protocol_version.h" #include "protocol_version.h"
#include "render/animation.h"
#include "stream.h" #include "stream.h"
#include "utils/i18n.h" #include "utils/i18n.h"
#include "wivrn_client.h" #include "wivrn_client.h"
@@ -571,7 +572,7 @@ void scenes::lobby::render(const XrFrameState & frame_state)
{ {
auto session = async_session.get(); auto session = async_session.get();
if (session) if (session)
next_scene = stream::create(std::move(session), 1'000'000'000.f / frame_state.predictedDisplayPeriod, server_name); next_scene = stream::create(std::move(session), 1'000'000'000.f / frame_state.predictedDisplayPeriod, server_name, *this);
async_session.reset(); async_session.reset();
} }
@@ -724,6 +725,8 @@ void scenes::lobby::render(const XrFrameState & frame_state)
input->apply(world, world_space, frame_state.predictedDisplayTime, hide_left_controller, hide_right_controller, ray_limits); input->apply(world, world_space, frame_state.predictedDisplayTime, hide_left_controller, hide_right_controller, ray_limits);
renderer::animate(world, frame_state.predictedDisplayPeriod * 1.0e-9);
assert(renderer); assert(renderer);
world.get<components::node>(lobby_entity).visible = not application::get_config().passthrough_enabled; world.get<components::node>(lobby_entity).visible = not application::get_config().passthrough_enabled;
@@ -796,10 +799,7 @@ void scenes::lobby::on_focused()
// assert(std::ranges::all_of(views, [width](const XrViewConfigurationView & view) { return view.recommendedImageRectWidth == width; })); // assert(std::ranges::all_of(views, [width](const XrViewConfigurationView & view) { return view.recommendedImageRectWidth == width; }));
// assert(std::ranges::all_of(views, [height](const XrViewConfigurationView & view) { return view.recommendedImageRectHeight == height; })); // assert(std::ranges::all_of(views, [height](const XrViewConfigurationView & view) { return view.recommendedImageRectHeight == height; }));
renderer.emplace(device, physical_device, queue, commandpool); lobby_entity = add_gltf("ground.glb", layer_lobby).first;
loader.emplace(device, physical_device, queue, queue_family_index, renderer->get_default_material());
lobby_entity = load_gltf("ground.glb", layer_lobby).first;
std::string profile = controller_name(); std::string profile = controller_name();
input.emplace( input.emplace(
@@ -830,8 +830,8 @@ void scenes::lobby::on_focused()
offset_orientation = glm::degrees(glm::eulerAngles(input->offset[xr::spaces::grip_left].second)); offset_orientation = glm::degrees(glm::eulerAngles(input->offset[xr::spaces::grip_left].second));
ray_offset = input->offset[xr::spaces::aim_left].first.z; ray_offset = input->offset[xr::spaces::aim_left].first.z;
xyz_axes_left_controller = load_gltf("xyz-arrows.glb", layer_controllers).first; xyz_axes_left_controller = add_gltf("xyz-arrows.glb", layer_controllers).first;
xyz_axes_right_controller = load_gltf("xyz-arrows.glb", layer_controllers).first; xyz_axes_right_controller = add_gltf("xyz-arrows.glb", layer_controllers).first;
#endif #endif
recenter_left_action = get_action("recenter_left").first; recenter_left_action = get_action("recenter_left").first;
@@ -906,9 +906,17 @@ void scenes::lobby::on_focused()
.z_index = constants::lobby::zindex_recenter_tip, .z_index = constants::lobby::zindex_recenter_tip,
}}; }};
swapchain_imgui = xr::swapchain(session, device, swapchain_format, 3000, 1300); xr::swapchain swapchain_imgui(session, device, swapchain_format, 3000, 1300);
imgui_ctx.emplace(physical_device, device, queue_family_index, queue, imgui_inputs, swapchain_imgui, vps); imgui_ctx.emplace(
physical_device,
device,
queue_family_index,
queue,
imgui_inputs,
std::move(swapchain_imgui),
vps,
image_cache);
auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
auto tm = std::localtime(&t); auto tm = std::localtime(&t);
@@ -937,17 +945,14 @@ void scenes::lobby::on_unfocused()
about_picture = 0; about_picture = 0;
imgui_ctx.reset(); imgui_ctx.reset();
world.clear(); // Must be cleared before the renderer so that the descriptor sets are freed before their pools world.clear();
input.reset(); input.reset();
left_hand.reset(); left_hand.reset();
right_hand.reset(); right_hand.reset();
face_tracker.emplace<std::monostate>(); face_tracker.emplace<std::monostate>();
loader.reset();
renderer.reset();
clear_swapchains(); clear_swapchains();
swapchain_imgui = xr::swapchain();
multicast.reset(); multicast.reset();
} }
+1 -3
View File
@@ -80,7 +80,6 @@ class lobby : public scene_impl<lobby>
uint32_t width; uint32_t width;
uint32_t height; uint32_t height;
xr::swapchain swapchain_imgui;
XrViewConfigurationView stream_view; XrViewConfigurationView stream_view;
#if WIVRN_CLIENT_DEBUG_MENU #if WIVRN_CLIENT_DEBUG_MENU
@@ -100,8 +99,7 @@ class lobby : public scene_impl<lobby>
XrAction recenter_left_action = XR_NULL_HANDLE; XrAction recenter_left_action = XR_NULL_HANDLE;
XrAction recenter_right_action = XR_NULL_HANDLE; XrAction recenter_right_action = XR_NULL_HANDLE;
// std::optional<glm::vec3> gui_recenter_position;
// std::optional<float> gui_recenter_distance;
// Which controller is used for recentering, position of the pointed point in the GUI, in GUI axes, and distance between the controller and the pointed point during recentering // Which controller is used for recentering, position of the pointed point in the GUI, in GUI axes, and distance between the controller and the pointed point during recentering
std::optional<std::tuple<xr::spaces, glm::vec3, float>> recentering_context; std::optional<std::tuple<xr::spaces, glm::vec3, float>> recentering_context;
bool recenter_gui = true; bool recenter_gui = true;
+11 -15
View File
@@ -151,8 +151,8 @@ static const std::array supported_depth_formats{
vk::Format::eX8D24UnormPack32, vk::Format::eX8D24UnormPack32,
}; };
scenes::stream::stream(std::string server_name) : scenes::stream::stream(std::string server_name, scene & parent_scene) :
scene_impl<stream>(supported_color_formats, supported_depth_formats), scene_impl<stream>(supported_color_formats, supported_depth_formats, parent_scene),
apps{*this, std::move(server_name)}, apps{*this, std::move(server_name)},
blitters{blitter(device, 0), blitter(device, 1)} blitters{blitter(device, 0), blitter(device, 1)}
{ {
@@ -186,9 +186,9 @@ static from_headset::visibility_mask_changed::masks get_visibility_mask(xr::inst
return res; return res;
} }
std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_session> network_session, float guessed_fps, std::string server_name) std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_session> network_session, float guessed_fps, std::string server_name, scene & parent_scene)
{ {
std::shared_ptr<stream> self{new stream{std::move(server_name)}}; std::shared_ptr<stream> self{new stream{std::move(server_name), parent_scene}};
self->network_session = std::move(network_session); self->network_session = std::move(network_session);
self->network_session->send_control([&]() { self->network_session->send_control([&]() {
@@ -390,6 +390,7 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
}); });
self->wifi = application::get_wifi_lock().get_wifi_lock(); self->wifi = application::get_wifi_lock().get_wifi_lock();
return self; return self;
} }
@@ -402,9 +403,6 @@ void scenes::stream::on_focused()
width = views[0].recommendedImageRectWidth; width = views[0].recommendedImageRectWidth;
height = views[0].recommendedImageRectHeight; height = views[0].recommendedImageRectHeight;
renderer.emplace(device, physical_device, queue, commandpool);
loader.emplace(device, physical_device, queue, queue_family_index, renderer->get_default_material());
std::string profile = controller_name(); std::string profile = controller_name();
input.emplace( input.emplace(
*this, *this,
@@ -448,7 +446,7 @@ void scenes::stream::on_focused()
}, },
}; };
swapchain_imgui = xr::swapchain( xr::swapchain swapchain_imgui(
session, session,
device, device,
swapchain_format, swapchain_format,
@@ -468,8 +466,9 @@ void scenes::stream::on_focused()
queue_family_index, queue_family_index,
queue, queue,
imgui_inputs, imgui_inputs,
swapchain_imgui, std::move(swapchain_imgui),
std::vector{vp}); std::vector{vp},
image_cache);
if (application::get_config().enable_stream_gui) if (application::get_config().enable_stream_gui)
{ {
@@ -492,17 +491,14 @@ void scenes::stream::on_focused()
void scenes::stream::on_unfocused() void scenes::stream::on_unfocused()
{ {
renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets;
world.clear(); // Must be cleared before the renderer so that the descriptor sets are freed before their pools world.clear();
input.reset(); input.reset();
loader.reset();
renderer.reset();
clear_swapchains(); clear_swapchains();
left_hand.reset(); left_hand.reset();
right_hand.reset(); right_hand.reset();
imgui_ctx.reset(); imgui_ctx.reset();
swapchain_imgui = xr::swapchain();
} }
scenes::stream::~stream() scenes::stream::~stream()
+3 -3
View File
@@ -110,7 +110,6 @@ private:
state state_ = state::initializing; state state_ = state::initializing;
xr::swapchain swapchain; xr::swapchain swapchain;
xr::swapchain swapchain_imgui;
std::optional<audio> audio_handle; std::optional<audio> audio_handle;
@@ -172,7 +171,7 @@ private:
XrTime running_application_req = 0; XrTime running_application_req = 0;
thread_safe<to_headset::running_applications> running_applications; thread_safe<to_headset::running_applications> running_applications;
stream(std::string server_name); stream(std::string server_name, scene & parent_scene);
public: public:
~stream(); ~stream();
@@ -180,7 +179,8 @@ public:
static std::shared_ptr<stream> create( static std::shared_ptr<stream> create(
std::unique_ptr<wivrn_session> session, std::unique_ptr<wivrn_session> session,
float guessed_fps, float guessed_fps,
std::string server_name); std::string server_name,
scene & parent_scene);
void render(const XrFrameState &) override; void render(const XrFrameState &) override;
void on_focused() override; void on_focused() override;
+20 -11
View File
@@ -30,7 +30,7 @@ const float fog_min_dist = 20.0;
const float fog_max_dist = 35.0; const float fog_max_dist = 35.0;
const vec4 fog_color = vec4(0.0, 0.25, 0.5, 1.0); const vec4 fog_color = vec4(0.0, 0.25, 0.5, 1.0);
layout(set = 0, binding = 0) uniform scene_ssbo layout(set = 0, binding = 0) uniform scene_ubo
{ {
mat4 view; mat4 view;
mat4 proj; mat4 proj;
@@ -39,7 +39,7 @@ layout(set = 0, binding = 0) uniform scene_ssbo
vec4 light_color; vec4 light_color;
} scene; } scene;
layout(set = 0, binding = 1) uniform mesh_ssbo layout(set = 0, binding = 1) uniform mesh_ubo
{ {
mat4 model; mat4 model;
mat4 modelview; mat4 modelview;
@@ -47,18 +47,18 @@ layout(set = 0, binding = 1) uniform mesh_ssbo
vec4 clipping_plane[nb_clipping]; vec4 clipping_plane[nb_clipping];
} mesh; } mesh;
layout(set = 0, binding = 2) uniform joints_ssbo layout(set = 0, binding = 2) uniform joints_ubo
{ {
mat4 joint_matrices[32]; mat4 joint_matrices[32];
} joints; } joints;
#ifdef FRAG_SHADER #ifdef FRAG_SHADER
layout(set = 1, binding = 0) uniform sampler2D base_color; layout(set = 0, binding = 3) uniform sampler2D base_color;
layout(set = 1, binding = 1) uniform sampler2D metallic_roughness; layout(set = 0, binding = 4) uniform sampler2D metallic_roughness;
layout(set = 1, binding = 2) uniform sampler2D occlusion; layout(set = 0, binding = 5) uniform sampler2D occlusion;
layout(set = 1, binding = 3) uniform sampler2D emissive; layout(set = 0, binding = 6) uniform sampler2D emissive;
layout(set = 1, binding = 4) uniform sampler2D normal_map; layout(set = 0, binding = 7) uniform sampler2D normal_map;
layout(set = 1, binding = 5) uniform material_ubo layout(set = 0, binding = 8) uniform material_ubo
{ {
vec4 base_color_factor; vec4 base_color_factor;
vec4 base_emissive_factor; vec4 base_emissive_factor;
@@ -66,6 +66,7 @@ layout(set = 1, binding = 5) uniform material_ubo
float roughness_factor; float roughness_factor;
float occlusion_strength; float occlusion_strength;
float normal_scale; float normal_scale;
float alpha_cutoff;
int base_color_texcoord; int base_color_texcoord;
int metallic_roughness_texcoord; int metallic_roughness_texcoord;
@@ -79,7 +80,7 @@ layout(set = 1, binding = 5) uniform material_ubo
#ifdef VERT_SHADER #ifdef VERT_SHADER
layout(location = 0) in vec3 in_position; layout(location = 0) in vec3 in_position;
layout(location = 1) in vec3 in_normal; layout(location = 1) in vec3 in_normal;
layout(location = 2) in vec3 in_tangent; layout(location = 2) in vec4 in_tangent;
layout(location = 3) in vec2 in_texcoord[2]; layout(location = 3) in vec2 in_texcoord[2];
layout(location = 5) in vec4 in_color; layout(location = 5) in vec4 in_color;
layout(location = 6) in vec4 in_joints; layout(location = 6) in vec4 in_joints;
@@ -212,9 +213,17 @@ void main()
ivec2 tmp = ivec2(gl_FragCoord.xy) % 4; ivec2 tmp = ivec2(gl_FragCoord.xy) % 4;
float dither_thd = 1.0f - dither_pattern[tmp.x][tmp.y]; float dither_thd = 1.0f - dither_pattern[tmp.x][tmp.y];
out_color = bc + one_over_d_linear_to_srgb(bc) * vec4(dither_thd, dither_thd, dither_thd, dither_thd) / 255.0f; out_color = bc + one_over_d_linear_to_srgb(bc) * vec4(dither_thd, dither_thd, dither_thd, 0) / 255.0f;
} }
else else
out_color = bc; out_color = bc;
if (alpha_cutout)
{
if (out_color.a <= material.alpha_cutoff)
out_color.a = 0.0;
else
out_color.a = 1.0;
}
} }
#endif #endif
+64
View File
@@ -0,0 +1,64 @@
/*
* 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/thread_safe.h"
#include <memory>
#include <unordered_map>
namespace utils
{
template <typename Key, typename Asset, typename Loader>
class cache
{
Loader loader;
thread_safe<std::unordered_map<Key, std::shared_ptr<Asset>>> entries;
public:
template <typename... Args>
cache(Args &&... args) :
loader(std::forward<Args>(args)...)
{}
template <typename... Args>
std::shared_ptr<Asset> load(const Key & key, Args &&... args)
{
auto _ = entries.lock();
auto iter = _->find(key);
if (iter != _->end())
return iter->second;
return _->emplace(key, loader(std::forward<Args>(args)...)).first->second;
}
template <typename... Args>
std::shared_ptr<Asset> load_uncached(Args &&... args)
{
return loader(std::forward<Args>(args)...);
}
void clear()
{
auto _ = entries.lock();
_->clear();
}
};
} // namespace utils