Add rendering engine
This commit is contained in:
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 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 <vector>
|
||||
#include <vulkan/vulkan.hpp>
|
||||
#include <fastgltf/types.hpp>
|
||||
#include <fastgltf/tools.hpp>
|
||||
#include "vk/allocation.h"
|
||||
|
||||
class gpu_buffer
|
||||
{
|
||||
std::vector<std::byte> bytes;
|
||||
vk::PhysicalDeviceLimits limits;
|
||||
fastgltf::Asset & asset;
|
||||
vk::BufferUsageFlags usage;
|
||||
|
||||
size_t add(size_t alignment, const void * data_to_add, size_t size)
|
||||
{
|
||||
size_t offset = ((bytes.size() + alignment - 1) / alignment) * alignment;
|
||||
|
||||
bytes.resize(offset + size);
|
||||
|
||||
memcpy(&bytes[offset], data_to_add, size);
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
requires requires(T t) {
|
||||
{
|
||||
t.data()
|
||||
} -> std::convertible_to<const void *>;
|
||||
{
|
||||
t.size()
|
||||
} -> std::convertible_to<size_t>;
|
||||
}
|
||||
size_t add(size_t alignment, const T & data_to_add)
|
||||
{
|
||||
return add(alignment, data_to_add.data(), data_to_add.size() * sizeof(data_to_add.data()[0]));
|
||||
}
|
||||
|
||||
public:
|
||||
gpu_buffer(vk::PhysicalDeviceProperties properties, fastgltf::Asset & asset) :
|
||||
limits(properties.limits), asset(asset), usage(0) {}
|
||||
|
||||
template <typename T>
|
||||
size_t add_uniform(const T & data_to_add)
|
||||
{
|
||||
usage |= vk::BufferUsageFlagBits::eUniformBuffer;
|
||||
|
||||
size_t alignment = std::max(limits.minUniformBufferOffsetAlignment, alignof(T));
|
||||
return add(alignment, &data_to_add, sizeof(data_to_add));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
size_t add_vertices(const T & data_to_add)
|
||||
{
|
||||
usage |= vk::BufferUsageFlagBits::eVertexBuffer;
|
||||
|
||||
size_t alignment = std::max<size_t>(4, alignof(T));
|
||||
return add(alignment, data_to_add);
|
||||
}
|
||||
|
||||
size_t add_indices(const fastgltf::Accessor & accessor)
|
||||
{
|
||||
usage |= vk::BufferUsageFlagBits::eIndexBuffer;
|
||||
|
||||
switch (accessor.componentType)
|
||||
{
|
||||
case fastgltf::ComponentType::Byte:
|
||||
case fastgltf::ComponentType::UnsignedByte: {
|
||||
std::vector<uint8_t> indices(accessor.count);
|
||||
using index_t = std::remove_cvref_t<decltype(*indices.data())>;
|
||||
fastgltf::copyFromAccessor<index_t>(asset, accessor, indices.data());
|
||||
return add(4, indices);
|
||||
}
|
||||
|
||||
case fastgltf::ComponentType::Short:
|
||||
case fastgltf::ComponentType::UnsignedShort: {
|
||||
std::vector<uint16_t> indices(accessor.count);
|
||||
using index_t = std::remove_cvref_t<decltype(*indices.data())>;
|
||||
fastgltf::copyFromAccessor<index_t>(asset, accessor, indices.data());
|
||||
return add(4, indices);
|
||||
}
|
||||
|
||||
case fastgltf::ComponentType::Int:
|
||||
case fastgltf::ComponentType::UnsignedInt: {
|
||||
std::vector<uint32_t> indices(accessor.count);
|
||||
using index_t = std::remove_cvref_t<decltype(*indices.data())>;
|
||||
fastgltf::copyFromAccessor<index_t>(asset, accessor, indices.data());
|
||||
return add(4, indices);
|
||||
}
|
||||
|
||||
default:
|
||||
throw std::runtime_error("Invalid index type");
|
||||
}
|
||||
}
|
||||
|
||||
buffer_allocation copy_to_gpu()
|
||||
{
|
||||
buffer_allocation gpu_buffer{
|
||||
vk::BufferCreateInfo{
|
||||
.size = bytes.size(),
|
||||
.usage = usage},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO}};
|
||||
|
||||
memcpy(gpu_buffer.map(), bytes.data(), bytes.size());
|
||||
gpu_buffer.unmap();
|
||||
|
||||
return gpu_buffer;
|
||||
}
|
||||
|
||||
size_t size() const
|
||||
{
|
||||
return bytes.size();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 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 "growable_descriptor_pool.h"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
growable_descriptor_pool::growable_descriptor_pool(vk::raii::Device & device, sizes size_, int descriptorsets_per_pool) :
|
||||
device(device), descriptorsets_per_pool(descriptorsets_per_pool)
|
||||
{
|
||||
std::vector<vk::DescriptorPoolSize> tmp;
|
||||
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eSampler, .descriptorCount = (uint32_t)size_.sampler});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eCombinedImageSampler, .descriptorCount = (uint32_t)size_.combined_image_sampler});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eSampledImage, .descriptorCount = (uint32_t)size_.sampled_image});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eStorageImage, .descriptorCount = (uint32_t)size_.storage_image});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eUniformTexelBuffer, .descriptorCount = (uint32_t)size_.uniform_texel_buffer});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eStorageTexelBuffer, .descriptorCount = (uint32_t)size_.storage_texel_buffer});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eUniformBuffer, .descriptorCount = (uint32_t)size_.uniform_buffer});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eStorageBuffer, .descriptorCount = (uint32_t)size_.storage_buffer});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eUniformBufferDynamic, .descriptorCount = (uint32_t)size_.uniform_buffer_dynamic});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eStorageBufferDynamic, .descriptorCount = (uint32_t)size_.storage_buffer_dynamic});
|
||||
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eInputAttachment, .descriptorCount = (uint32_t)size_.input_attachment});
|
||||
|
||||
for (auto & i: tmp)
|
||||
{
|
||||
// Only use the descriptor types that have a descriptorCount above 0
|
||||
if (i.descriptorCount > 0)
|
||||
size.push_back(i);
|
||||
}
|
||||
|
||||
if (size.empty())
|
||||
throw std::invalid_argument("size");
|
||||
|
||||
if (descriptorsets_per_pool <= 0)
|
||||
throw std::invalid_argument("descriptorsets_per_pool");
|
||||
}
|
||||
|
||||
std::shared_ptr<vk::raii::DescriptorSet> growable_descriptor_pool::allocate(vk::DescriptorSetLayout layout)
|
||||
{
|
||||
vk::DescriptorSetAllocateInfo alloc_info{
|
||||
.descriptorSetCount = 1,
|
||||
.pSetLayouts = &layout,
|
||||
};
|
||||
|
||||
for (vk::raii::DescriptorPool & i: pools)
|
||||
{
|
||||
// TODO: don't use exceptions as control flow
|
||||
try
|
||||
{
|
||||
alloc_info.descriptorPool = *i;
|
||||
return std::make_shared<vk::raii::DescriptorSet>(std::move(device.allocateDescriptorSets(alloc_info)[0]));
|
||||
}
|
||||
catch (vk::OutOfPoolMemoryError &)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
vk::DescriptorPoolCreateInfo pool_info{
|
||||
.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet,
|
||||
.maxSets = (uint32_t)descriptorsets_per_pool};
|
||||
|
||||
pool_info.setPoolSizes(size);
|
||||
|
||||
alloc_info.descriptorPool = *pools.emplace_back(device, pool_info);
|
||||
|
||||
return std::make_shared<vk::raii::DescriptorSet>(std::move(device.allocateDescriptorSets(alloc_info)[0]));
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 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 <vector>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
class growable_descriptor_pool
|
||||
{
|
||||
public:
|
||||
struct sizes
|
||||
{
|
||||
int sampler = 0;
|
||||
int combined_image_sampler = 0;
|
||||
int sampled_image = 0;
|
||||
int storage_image = 0;
|
||||
int uniform_texel_buffer = 0;
|
||||
int storage_texel_buffer = 0;
|
||||
int uniform_buffer = 0;
|
||||
int storage_buffer = 0;
|
||||
int uniform_buffer_dynamic = 0;
|
||||
int storage_buffer_dynamic = 0;
|
||||
int input_attachment = 0;
|
||||
};
|
||||
|
||||
private:
|
||||
vk::raii::Device & device;
|
||||
std::vector<vk::DescriptorPoolSize> size;
|
||||
int descriptorsets_per_pool;
|
||||
|
||||
std::vector<vk::raii::DescriptorPool> pools;
|
||||
|
||||
public:
|
||||
growable_descriptor_pool(vk::raii::Device & device, sizes size, int descriptorsets_per_pool);
|
||||
|
||||
std::shared_ptr<vk::raii::DescriptorSet> allocate(vk::DescriptorSetLayout layout);
|
||||
|
||||
std::shared_ptr<vk::raii::DescriptorSet> allocate(vk::raii::DescriptorSetLayout& layout)
|
||||
{
|
||||
return allocate(*layout);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,344 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.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 "image_loader.h"
|
||||
|
||||
#include "vulkan/vulkan_enums.hpp"
|
||||
#include "vulkan/vulkan_handles.hpp"
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <variant>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#define STBI_ONLY_JPEG
|
||||
#define STBI_ONLY_PNG
|
||||
|
||||
#ifdef __ARM_NEON
|
||||
#define STBI_NEON
|
||||
#endif
|
||||
|
||||
#include "stb_image.h"
|
||||
|
||||
using stbi_ptr = std::unique_ptr<void, decltype([](void * pixels) { stbi_image_free(pixels); })>;
|
||||
|
||||
namespace
|
||||
{
|
||||
template <typename T>
|
||||
constexpr vk::Format formats[4] = {vk::Format::eUndefined, vk::Format::eUndefined, vk::Format::eUndefined, vk::Format::eUndefined};
|
||||
|
||||
template <>
|
||||
constexpr vk::Format formats<uint8_t>[] = {
|
||||
vk::Format::eR8Unorm,
|
||||
vk::Format::eR8G8Unorm,
|
||||
vk::Format::eUndefined,
|
||||
vk::Format::eR8G8B8A8Unorm,
|
||||
};
|
||||
|
||||
template <>
|
||||
constexpr vk::Format formats<uint16_t>[] = {
|
||||
vk::Format::eR16Unorm,
|
||||
vk::Format::eR16G16Unorm,
|
||||
vk::Format::eUndefined,
|
||||
vk::Format::eR16G16B16A16Unorm,
|
||||
};
|
||||
|
||||
template <>
|
||||
constexpr vk::Format formats<float>[] = {
|
||||
vk::Format::eR32Sfloat,
|
||||
vk::Format::eR32G32Sfloat,
|
||||
vk::Format::eUndefined,
|
||||
vk::Format::eR32G32B32A32Sfloat,
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
vk::Format get_format(int num_components)
|
||||
{
|
||||
assert(num_components > 0 && num_components <= 4);
|
||||
|
||||
return formats<T>[num_components - 1];
|
||||
}
|
||||
|
||||
vk::Format get_format_srgb(int num_components)
|
||||
{
|
||||
switch (num_components)
|
||||
{
|
||||
case 1:
|
||||
return vk::Format::eR8Srgb;
|
||||
case 2:
|
||||
return vk::Format::eR8G8Srgb;
|
||||
case 3:
|
||||
return vk::Format::eUndefined;
|
||||
case 4:
|
||||
return vk::Format::eR8G8B8A8Srgb;
|
||||
|
||||
default:
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
int bytes_per_pixel(vk::Format format)
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case vk::Format::eR8Srgb:
|
||||
case vk::Format::eR8Unorm:
|
||||
return 1;
|
||||
case vk::Format::eR8G8Srgb:
|
||||
case vk::Format::eR8G8Unorm:
|
||||
return 2;
|
||||
case vk::Format::eR8G8B8A8Srgb:
|
||||
case vk::Format::eR8G8B8A8Unorm:
|
||||
return 4;
|
||||
|
||||
case vk::Format::eR16Unorm:
|
||||
return 2;
|
||||
case vk::Format::eR16G16Unorm:
|
||||
return 4;
|
||||
case vk::Format::eR16G16B16A16Unorm:
|
||||
return 8;
|
||||
|
||||
case vk::Format::eR32Sfloat:
|
||||
return 4;
|
||||
case vk::Format::eR32G32Sfloat:
|
||||
return 8;
|
||||
case vk::Format::eR32G32B32A32Sfloat:
|
||||
return 16;
|
||||
|
||||
default:
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void image_loader::do_load(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const void * pixels, vk::Extent3D extent, vk::Format format)
|
||||
{
|
||||
assert(format != vk::Format::eUndefined);
|
||||
|
||||
this->format = format;
|
||||
this->extent = extent;
|
||||
if (extent.depth > 1)
|
||||
{
|
||||
image_type = vk::ImageType::e3D;
|
||||
image_view_type = vk::ImageViewType::e3D;
|
||||
}
|
||||
else
|
||||
{
|
||||
image_type = vk::ImageType::e2D;
|
||||
image_view_type = vk::ImageViewType::e2D;
|
||||
}
|
||||
num_mipmaps = std::floor(std::log2(std::max(extent.width, extent.height))) + 1;
|
||||
|
||||
size_t byte_size = extent.width * extent.height * extent.depth * bytes_per_pixel(format);
|
||||
|
||||
// Copy to staging buffer
|
||||
staging_buffer = buffer_allocation{
|
||||
vk::BufferCreateInfo{
|
||||
.size = byte_size,
|
||||
.usage = vk::BufferUsageFlagBits::eTransferSrc},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
}};
|
||||
|
||||
memcpy(staging_buffer.map(), pixels, byte_size);
|
||||
staging_buffer.unmap();
|
||||
|
||||
// Allocate image
|
||||
image = image_allocation{
|
||||
vk::ImageCreateInfo{
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = format,
|
||||
.extent = extent,
|
||||
.mipLevels = num_mipmaps,
|
||||
.arrayLayers = 1,
|
||||
.samples = vk::SampleCountFlagBits::e1,
|
||||
.tiling = vk::ImageTiling::eOptimal,
|
||||
.usage = vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eSampled,
|
||||
.initialLayout = vk::ImageLayout::eUndefined},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = 0,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
}};
|
||||
|
||||
// Transition all mipmap levels layout to eTransferDstOptimal
|
||||
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
|
||||
.srcAccessMask = vk::AccessFlagBits::eNone,
|
||||
.dstAccessMask = vk::AccessFlagBits::eTransferWrite,
|
||||
.oldLayout = vk::ImageLayout::eUndefined,
|
||||
.newLayout = vk::ImageLayout::eTransferDstOptimal,
|
||||
.image = image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = num_mipmaps,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
|
||||
// Copy image data
|
||||
cb.copyBufferToImage(staging_buffer, image, vk::ImageLayout::eTransferDstOptimal, vk::BufferImageCopy{
|
||||
.bufferOffset = 0,
|
||||
.bufferRowLength = 0,
|
||||
.bufferImageHeight = 0,
|
||||
.imageSubresource = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.mipLevel = 0,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
.imageOffset = {0, 0, 0},
|
||||
.imageExtent = extent,
|
||||
});
|
||||
|
||||
// Create mipmaps
|
||||
int width = extent.width;
|
||||
int height = extent.height;
|
||||
for (uint32_t level = 1; level < num_mipmaps; level++)
|
||||
{
|
||||
int next_width = width > 1 ? width / 2 : 1;
|
||||
int next_height = height > 1 ? height / 2 : 1;
|
||||
|
||||
// Transition source image layout to eTransferSrcOptimal
|
||||
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
|
||||
.srcAccessMask = vk::AccessFlagBits::eTransferWrite,
|
||||
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
|
||||
.oldLayout = vk::ImageLayout::eTransferDstOptimal,
|
||||
.newLayout = vk::ImageLayout::eTransferSrcOptimal,
|
||||
.image = image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = level - 1,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
|
||||
// Blit level n-1 to level n
|
||||
cb.blitImage(image, vk::ImageLayout::eTransferSrcOptimal, image, vk::ImageLayout::eTransferDstOptimal, vk::ImageBlit{
|
||||
.srcSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = level - 1, .baseArrayLayer = 0, .layerCount = 1},
|
||||
.srcOffsets = std::array{
|
||||
vk::Offset3D{0, 0, 0},
|
||||
vk::Offset3D{width, height, 1},
|
||||
},
|
||||
.dstSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = level, .baseArrayLayer = 0, .layerCount = 1},
|
||||
.dstOffsets = std::array{
|
||||
vk::Offset3D{0, 0, 0},
|
||||
vk::Offset3D{next_width, next_height, 1},
|
||||
},
|
||||
},
|
||||
vk::Filter::eLinear);
|
||||
|
||||
// Transition source image layout to eShaderReadOnlyOptimal
|
||||
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
|
||||
.srcAccessMask = vk::AccessFlagBits::eTransferRead,
|
||||
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
|
||||
.oldLayout = vk::ImageLayout::eTransferSrcOptimal,
|
||||
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
|
||||
.image = image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = level - 1,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
|
||||
width = next_width;
|
||||
height = next_height;
|
||||
}
|
||||
|
||||
// Transition the last level to eShaderReadOnlyOptimal
|
||||
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
|
||||
.srcAccessMask = vk::AccessFlagBits::eTransferWrite,
|
||||
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
|
||||
.oldLayout = vk::ImageLayout::eTransferDstOptimal,
|
||||
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
|
||||
.image = image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = num_mipmaps - 1,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
|
||||
// Create the image view
|
||||
image_view = vk::raii::ImageView{device, vk::ImageViewCreateInfo{
|
||||
.image = image,
|
||||
.viewType = image_view_type,
|
||||
.format = format,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = num_mipmaps,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
}};
|
||||
}
|
||||
|
||||
image_loader::image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const void * pixels, vk::Extent3D extent, vk::Format format)
|
||||
{
|
||||
do_load(device, cb, pixels, extent, format);
|
||||
}
|
||||
|
||||
image_loader::image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, std::span<const std::byte> bytes, bool srgb)
|
||||
{
|
||||
const stbi_uc * image_data = (const stbi_uc *)bytes.data();
|
||||
size_t image_size = bytes.size();
|
||||
|
||||
int w, h, num_channels, channels_in_file;
|
||||
stbi_ptr pixels;
|
||||
|
||||
if (!stbi_info_from_memory(image_data, image_size, &w, &h, &num_channels))
|
||||
throw std::runtime_error("Unsupported image format");
|
||||
|
||||
assert(num_channels >= 1 && num_channels <= 4);
|
||||
|
||||
if (num_channels == 3)
|
||||
num_channels = 4;
|
||||
|
||||
if (stbi_is_hdr_from_memory(image_data, image_size))
|
||||
{
|
||||
pixels = stbi_ptr(stbi_loadf_from_memory(image_data, image_size, &w, &h, &channels_in_file, num_channels));
|
||||
format = get_format<float>(num_channels);
|
||||
}
|
||||
else if (stbi_is_16_bit_from_memory(image_data, image_size))
|
||||
{
|
||||
pixels = stbi_ptr(stbi_load_16_from_memory(image_data, image_size, &w, &h, &channels_in_file, num_channels));
|
||||
format = get_format<uint16_t>(num_channels);
|
||||
}
|
||||
else
|
||||
{
|
||||
pixels = stbi_ptr(stbi_load_from_memory(image_data, image_size, &w, &h, &channels_in_file, num_channels));
|
||||
format = srgb ? get_format_srgb(num_channels) : get_format<uint8_t>(num_channels);
|
||||
}
|
||||
|
||||
extent.width = w;
|
||||
extent.height = h;
|
||||
extent.depth = 1;
|
||||
|
||||
do_load(device, cb, pixels.get(), extent, format);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.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 "vk/allocation.h"
|
||||
#include <cstddef>
|
||||
#include <glm/vec2.hpp>
|
||||
#include <glm/vec3.hpp>
|
||||
#include <glm/vec4.hpp>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <tuple>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
struct image_loader
|
||||
{
|
||||
image_allocation image;
|
||||
vk::raii::ImageView image_view = nullptr;
|
||||
|
||||
vk::Format format;
|
||||
vk::Extent3D extent;
|
||||
vk::ImageType image_type;
|
||||
vk::ImageViewType image_view_type;
|
||||
|
||||
uint32_t num_mipmaps;
|
||||
|
||||
buffer_allocation staging_buffer;
|
||||
|
||||
// Load a PNG/JPEG file
|
||||
image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, std::span<const std::byte> bytes, bool srgb);
|
||||
|
||||
// Load raw pixel data
|
||||
image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const void * pixels, vk::Extent3D extent, vk::Format format);
|
||||
|
||||
template <typename T>
|
||||
image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, std::span<T> pixels, vk::Extent3D extent, vk::Format format) :
|
||||
image_loader(device, cb, pixels.data(), extent, format)
|
||||
{}
|
||||
|
||||
template <typename T, size_t N>
|
||||
image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const std::array<T, N> & pixels, vk::Extent3D extent, vk::Format format) :
|
||||
image_loader(device, cb, pixels.data(), extent, format)
|
||||
{}
|
||||
|
||||
private:
|
||||
void do_load(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const void * pixels, vk::Extent3D extent, vk::Format format);
|
||||
};
|
||||
@@ -0,0 +1,953 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.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 "render/scene_data.h"
|
||||
|
||||
#include "image_loader.h"
|
||||
#include "render/gpu_buffer.h"
|
||||
#include "utils/fmt_glm.h"
|
||||
#include "utils/ranges.h"
|
||||
#include <boost/pfr/core.hpp>
|
||||
#include <concepts>
|
||||
#include <fastgltf/base64.hpp>
|
||||
#include <fastgltf/glm_element_traits.hpp>
|
||||
#include <fastgltf/parser.hpp>
|
||||
#include <fastgltf/tools.hpp>
|
||||
#include <fastgltf/types.hpp>
|
||||
#include <fastgltf/util.hpp>
|
||||
#include <fstream>
|
||||
#include <glm/gtc/type_ptr.hpp>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <stdexcept>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
#include <vk_mem_alloc.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#include "application.h"
|
||||
#include "asset.h"
|
||||
|
||||
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;
|
||||
|
||||
scene_data::vertex::description scene_data::vertex::describe()
|
||||
{
|
||||
scene_data::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;
|
||||
}
|
||||
|
||||
// Conversion functions gltf -> vulkan
|
||||
namespace
|
||||
{
|
||||
fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory)
|
||||
{
|
||||
fastgltf::Parser parser(fastgltf::Extensions::KHR_texture_basisu);
|
||||
|
||||
auto gltf_options =
|
||||
fastgltf::Options::DontRequireValidAssetMember |
|
||||
fastgltf::Options::AllowDouble |
|
||||
fastgltf::Options::LoadGLBBuffers |
|
||||
// fastgltf::Options::LoadExternalBuffers |
|
||||
// fastgltf::Options::LoadExternalImages |
|
||||
fastgltf::Options::DecomposeNodeMatrices;
|
||||
|
||||
fastgltf::Expected<fastgltf::Asset> expected_asset{fastgltf::Error::None};
|
||||
|
||||
switch (fastgltf::determineGltfFileType(&buffer))
|
||||
{
|
||||
case fastgltf::GltfType::GLB:
|
||||
expected_asset = parser.loadBinaryGLTF(&buffer, directory, gltf_options);
|
||||
break;
|
||||
|
||||
case fastgltf::GltfType::glTF:
|
||||
expected_asset = parser.loadGLTF(&buffer, directory, gltf_options);
|
||||
break;
|
||||
|
||||
case fastgltf::GltfType::Invalid:
|
||||
throw std::runtime_error("Unrecognized file type");
|
||||
}
|
||||
|
||||
if (auto error = expected_asset.error(); error != fastgltf::Error::None)
|
||||
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
|
||||
|
||||
return std::move(expected_asset.get());
|
||||
}
|
||||
|
||||
std::pair<vk::Filter, vk::SamplerMipmapMode> convert(fastgltf::Filter filter)
|
||||
{
|
||||
switch (filter)
|
||||
{
|
||||
case fastgltf::Filter::Nearest:
|
||||
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};
|
||||
|
||||
case fastgltf::Filter::NearestMipMapLinear:
|
||||
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eLinear};
|
||||
|
||||
case fastgltf::Filter::LinearMipMapLinear:
|
||||
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eLinear};
|
||||
}
|
||||
|
||||
throw std::invalid_argument("filter");
|
||||
}
|
||||
|
||||
vk::SamplerAddressMode convert(fastgltf::Wrap wrap)
|
||||
{
|
||||
switch (wrap)
|
||||
{
|
||||
case fastgltf::Wrap::ClampToEdge:
|
||||
return vk::SamplerAddressMode::eClampToEdge;
|
||||
|
||||
case fastgltf::Wrap::MirroredRepeat:
|
||||
return vk::SamplerAddressMode::eMirroredRepeat;
|
||||
|
||||
case fastgltf::Wrap::Repeat:
|
||||
return vk::SamplerAddressMode::eRepeat;
|
||||
}
|
||||
|
||||
throw std::invalid_argument("wrap");
|
||||
}
|
||||
|
||||
sampler_info convert(fastgltf::Sampler & sampler)
|
||||
{
|
||||
sampler_info info;
|
||||
|
||||
info.mag_filter = convert(sampler.magFilter.value_or(fastgltf::Filter::Linear)).first;
|
||||
|
||||
std::tie(info.min_filter, info.min_filter_mipmap) = convert(sampler.minFilter.value_or(fastgltf::Filter::LinearMipMapLinear));
|
||||
|
||||
info.wrapS = convert(sampler.wrapS);
|
||||
info.wrapT = convert(sampler.wrapT);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
vk::PrimitiveTopology convert(fastgltf::PrimitiveType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case fastgltf::PrimitiveType::Points:
|
||||
return vk::PrimitiveTopology::ePointList;
|
||||
|
||||
case fastgltf::PrimitiveType::Lines:
|
||||
return vk::PrimitiveTopology::eLineList;
|
||||
|
||||
case fastgltf::PrimitiveType::LineLoop:
|
||||
throw std::runtime_error("Unimplemented");
|
||||
|
||||
case fastgltf::PrimitiveType::LineStrip:
|
||||
return vk::PrimitiveTopology::eLineStrip;
|
||||
|
||||
case fastgltf::PrimitiveType::Triangles:
|
||||
return vk::PrimitiveTopology::eTriangleList;
|
||||
|
||||
case fastgltf::PrimitiveType::TriangleStrip:
|
||||
return vk::PrimitiveTopology::eTriangleStrip;
|
||||
|
||||
case fastgltf::PrimitiveType::TriangleFan:
|
||||
return vk::PrimitiveTopology::eTriangleFan;
|
||||
}
|
||||
|
||||
throw std::invalid_argument("type");
|
||||
}
|
||||
|
||||
glm::vec4 convert(const std::array<float, 4> & v)
|
||||
{
|
||||
return {v[0], v[1], v[2], v[3]};
|
||||
}
|
||||
|
||||
glm::vec3 convert(const std::array<float, 3> & v)
|
||||
{
|
||||
return {v[0], v[1], v[2]};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
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<scene_data::vertex> & vertices,
|
||||
T scene_data::vertex::*attribute)
|
||||
{
|
||||
using U = T::value_type;
|
||||
constexpr size_t N = std::tuple_size_v<T>;
|
||||
|
||||
for (size_t i = 0; i < N; i++)
|
||||
{
|
||||
auto it = primitive.findAttribute(attribute_name + std::to_string(i));
|
||||
|
||||
if (it == primitive.attributes.end())
|
||||
continue;
|
||||
|
||||
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
|
||||
|
||||
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;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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<scene_data::vertex> & vertices,
|
||||
T scene_data::vertex::*attribute)
|
||||
{
|
||||
auto it = primitive.findAttribute(attribute_name);
|
||||
|
||||
if (it == primitive.attributes.end())
|
||||
return;
|
||||
|
||||
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
|
||||
|
||||
if (vertices.size() < accessor.count)
|
||||
vertices.resize(accessor.count, {});
|
||||
|
||||
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](T value, std::size_t idx) {
|
||||
vertices[idx].*attribute = value;
|
||||
});
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr bool starts_with(std::span<const std::byte> data, std::span<const uint8_t> prefix)
|
||||
{
|
||||
return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size());
|
||||
}
|
||||
|
||||
static fastgltf::MimeType guess_mime_type(std::span<const std::byte> image_data)
|
||||
{
|
||||
const uint8_t png_magic[] = {0xFF, 0xD8, 0xFF};
|
||||
const uint8_t jpeg_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
|
||||
|
||||
if (starts_with(image_data, png_magic))
|
||||
return fastgltf::MimeType::PNG;
|
||||
else if (starts_with(image_data, jpeg_magic))
|
||||
return fastgltf::MimeType::JPEG;
|
||||
else
|
||||
return fastgltf::MimeType::None;
|
||||
}
|
||||
|
||||
static std::pair<scene_data::image, buffer_allocation> do_load_image(
|
||||
vk::raii::Device & device,
|
||||
vk::raii::CommandBuffer & cb,
|
||||
fastgltf::MimeType image_type,
|
||||
std::span<const std::byte> image_data,
|
||||
bool srgb)
|
||||
{
|
||||
std::pair<scene_data::image, buffer_allocation> output;
|
||||
|
||||
cb.begin(vk::CommandBufferBeginInfo{.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
|
||||
|
||||
if (image_type == fastgltf::MimeType::GltfBuffer || image_type == fastgltf::MimeType::None)
|
||||
image_type = guess_mime_type(image_data);
|
||||
|
||||
switch (image_type)
|
||||
{
|
||||
case fastgltf::MimeType::JPEG:
|
||||
case fastgltf::MimeType::PNG: {
|
||||
image_loader loader(device, cb, image_data, srgb);
|
||||
output.first.image_view = std::move(loader.image_view);
|
||||
output.first.image_ = std::move(loader.image);
|
||||
output.second = std::move(loader.staging_buffer);
|
||||
|
||||
spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps);
|
||||
}
|
||||
break;
|
||||
|
||||
case fastgltf::MimeType::KTX2:
|
||||
// TODO
|
||||
|
||||
case fastgltf::MimeType::DDS:
|
||||
// TODO
|
||||
|
||||
default:
|
||||
throw std::runtime_error("Invalid image MIME type: " + std::to_string((int)image_type));
|
||||
}
|
||||
|
||||
cb.end();
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
class loader_context
|
||||
{
|
||||
std::filesystem::path base_directory;
|
||||
fastgltf::Asset & gltf;
|
||||
vk::raii::Device & device;
|
||||
vk::raii::Queue & queue;
|
||||
vk::raii::CommandPool & cb_pool;
|
||||
|
||||
std::vector<asset> loaded_assets;
|
||||
asset & load_from_asset(const std::filesystem::path & path)
|
||||
{
|
||||
return loaded_assets.emplace_back(path);
|
||||
}
|
||||
|
||||
public:
|
||||
loader_context(std::filesystem::path base_directory,
|
||||
fastgltf::Asset & gltf,
|
||||
vk::raii::Device & device,
|
||||
vk::raii::Queue & queue,
|
||||
vk::raii::CommandPool & cb_pool) :
|
||||
base_directory(base_directory),
|
||||
gltf(gltf),
|
||||
device(device),
|
||||
queue(queue),
|
||||
cb_pool(cb_pool)
|
||||
{
|
||||
}
|
||||
|
||||
fastgltf::span<const std::byte> load(const fastgltf::URI& uri)
|
||||
{
|
||||
auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path());
|
||||
std::span<const std::byte> bytes;
|
||||
|
||||
bytes = load_from_asset(path);
|
||||
|
||||
return fastgltf::span<const std::byte>(bytes.data(), bytes.size());
|
||||
}
|
||||
|
||||
fastgltf::span<const std::byte> load(const fastgltf::sources::URI& uri)
|
||||
{
|
||||
return load(uri.uri);
|
||||
}
|
||||
|
||||
template<typename T, std::size_t Extent>
|
||||
fastgltf::span<T, fastgltf::dynamic_extent> subspan(fastgltf::span<T, Extent> span, size_t offset, size_t count = fastgltf::dynamic_extent)
|
||||
{
|
||||
assert(offset < span.size());
|
||||
assert(count == fastgltf::dynamic_extent || count <= span.size() - offset);
|
||||
|
||||
if (count == fastgltf::dynamic_extent)
|
||||
count = span.size() - offset;
|
||||
|
||||
return fastgltf::span<T>{span.data() + offset, count};
|
||||
}
|
||||
|
||||
fastgltf::sources::ByteView visit_source(fastgltf::DataSource & source)
|
||||
{
|
||||
using return_type = fastgltf::sources::ByteView;
|
||||
|
||||
return std::visit(fastgltf::visitor{
|
||||
[&](std::monostate) -> return_type {
|
||||
throw std::runtime_error("Invalid source");
|
||||
},
|
||||
[&](fastgltf::sources::Fallback) -> return_type {
|
||||
throw std::runtime_error("Invalid source");
|
||||
},
|
||||
[&](const fastgltf::sources::BufferView & buffer_view) -> return_type {
|
||||
fastgltf::BufferView & view = gltf.bufferViews.at(buffer_view.bufferViewIndex);
|
||||
|
||||
fastgltf::Buffer & buffer = gltf.buffers.at(view.bufferIndex);
|
||||
|
||||
auto buffer2 = visit_source(buffer.data);
|
||||
|
||||
return {subspan(buffer2.bytes, view.byteOffset, view.byteLength), buffer_view.mimeType};
|
||||
},
|
||||
[&](const fastgltf::sources::URI & uri) -> return_type {
|
||||
if (!uri.uri.isLocalPath())
|
||||
throw std::runtime_error("Non local paths are not supported"); // TODO ?
|
||||
|
||||
fastgltf::span<const std::byte> data = load(uri);
|
||||
|
||||
// Don't use the MIME type from fastgltf, it's not initialized for URIs
|
||||
return {subspan(data, uri.fileByteOffset), fastgltf::MimeType::None};
|
||||
},
|
||||
[&](const fastgltf::sources::Vector & vector) -> return_type {
|
||||
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(vector.bytes.data()), vector.bytes.size()};
|
||||
return {data, vector.mimeType};
|
||||
},
|
||||
[&](const fastgltf::sources::CustomBuffer & custom_buffer) -> return_type {
|
||||
throw std::runtime_error("Unimplemented source CustomBuffer");
|
||||
// TODO ?
|
||||
},
|
||||
[&](fastgltf::sources::ByteView & byte_view) -> return_type {
|
||||
return {byte_view.bytes, byte_view.mimeType};
|
||||
}},
|
||||
source);
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<scene_data::image>> load_all_images()
|
||||
{
|
||||
// Determine which image is sRGB
|
||||
std::vector<bool> srgb;
|
||||
srgb.resize(gltf.images.size(), false);
|
||||
for (const fastgltf::Material & gltf_material: gltf.materials)
|
||||
{
|
||||
if (gltf_material.pbrData.baseColorTexture)
|
||||
srgb.at(gltf_material.pbrData.baseColorTexture->textureIndex) = true;
|
||||
|
||||
if (gltf_material.emissiveTexture)
|
||||
srgb.at(gltf_material.emissiveTexture->textureIndex) = true;
|
||||
}
|
||||
|
||||
// Load images
|
||||
std::vector<std::shared_ptr<scene_data::image>> images;
|
||||
images.reserve(gltf.images.size());
|
||||
|
||||
// Create command buffers and fences
|
||||
int num_images_in_flight = 3;
|
||||
std::vector<vk::raii::CommandBuffer> command_buffers = device.allocateCommandBuffers({
|
||||
.commandPool = *cb_pool,
|
||||
.level = vk::CommandBufferLevel::ePrimary,
|
||||
.commandBufferCount = (uint32_t)num_images_in_flight,
|
||||
});
|
||||
|
||||
std::vector<std::pair<vk::raii::Fence, buffer_allocation>> fences;
|
||||
for (int i = 0; i < num_images_in_flight; ++i)
|
||||
fences.emplace_back(
|
||||
device.createFence(vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}),
|
||||
buffer_allocation{});
|
||||
|
||||
// TODO: use a single command buffer?
|
||||
for (const auto [index, gltf_image]: utils::enumerate(gltf.images))
|
||||
{
|
||||
auto & cb = command_buffers[index % num_images_in_flight];
|
||||
auto & fence = fences[index % num_images_in_flight].first;
|
||||
|
||||
auto [image_data, mime_type] = visit_source(gltf_image.data);
|
||||
auto [image, resources] = do_load_image(device, cb, mime_type, image_data, srgb[index]);
|
||||
|
||||
// Wait for the previous submit to finish before overwriting fences[...].second
|
||||
device.waitForFences(*fence, true, 1'000'000'000); // TODO check for timeout
|
||||
device.resetFences(*fence);
|
||||
|
||||
fences[index % num_images_in_flight].second = std::move(resources);
|
||||
images.emplace_back(std::make_shared<scene_data::image>(std::move(image)));
|
||||
|
||||
vk::SubmitInfo info;
|
||||
info.setCommandBuffers(*cb);
|
||||
|
||||
queue.submit(info, *fence);
|
||||
}
|
||||
|
||||
std::vector<vk::Fence> fences2;
|
||||
for (auto & i: fences)
|
||||
fences2.push_back(*i.first);
|
||||
|
||||
device.waitForFences(fences2, true, 1'000'000'000); // TODO check for timeout
|
||||
fences.clear();
|
||||
|
||||
return images;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<scene_data::texture>> load_all_textures(std::vector<std::shared_ptr<scene_data::image>> & images)
|
||||
{
|
||||
std::vector<std::shared_ptr<scene_data::texture>> textures;
|
||||
textures.reserve(gltf.textures.size());
|
||||
for (const fastgltf::Texture & gltf_texture: gltf.textures)
|
||||
{
|
||||
auto & texture_ref = *textures.emplace_back(std::make_shared<scene_data::texture>());
|
||||
|
||||
if (gltf_texture.samplerIndex)
|
||||
{
|
||||
fastgltf::Sampler & sampler = gltf.samplers.at(*gltf_texture.samplerIndex);
|
||||
texture_ref.sampler = convert(sampler);
|
||||
}
|
||||
|
||||
if (gltf_texture.imageIndex)
|
||||
{
|
||||
texture_ref.image_ = images.at(*gltf_texture.imageIndex);
|
||||
}
|
||||
// else if (gltf_texture.basisuImageIndex)
|
||||
// {
|
||||
// // TODO
|
||||
// }
|
||||
// else if (gltf_texture.ddsImageIndex)
|
||||
// {
|
||||
// // TODO
|
||||
// }
|
||||
// else if (gltf_texture.webpImageIndex)
|
||||
// {
|
||||
// // TODO
|
||||
// }
|
||||
else
|
||||
{
|
||||
throw std::runtime_error("Unsupported image type");
|
||||
}
|
||||
}
|
||||
|
||||
return textures;
|
||||
}
|
||||
|
||||
void load_all_buffers()
|
||||
{
|
||||
for (fastgltf::Buffer & buffer: gltf.buffers)
|
||||
{
|
||||
if (std::holds_alternative<fastgltf::sources::URI>(buffer.data))
|
||||
{
|
||||
fastgltf::sources::URI uri = std::get<fastgltf::sources::URI>(buffer.data);
|
||||
|
||||
// Don't use the MIME type from fastgltf, it's not initialized for URIs
|
||||
buffer.data = fastgltf::sources::ByteView(load(uri), fastgltf::MimeType::None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<scene_data::material>> load_all_materials(std::vector<std::shared_ptr<scene_data::texture>> & textures, gpu_buffer & staging_buffer, const scene_data::material & default_material)
|
||||
{
|
||||
std::vector<std::shared_ptr<scene_data::material>> materials;
|
||||
materials.reserve(gltf.materials.size());
|
||||
for (const fastgltf::Material & gltf_material: gltf.materials)
|
||||
{
|
||||
// Copy the default material
|
||||
auto & material_ref = *materials.emplace_back(std::make_shared<scene_data::material>(default_material));
|
||||
|
||||
scene_data::material::gpu_data & material_data = material_ref.staging;
|
||||
|
||||
material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor);
|
||||
material_data.base_emissive_factor = glm::vec4(convert(gltf_material.emissiveFactor), 0);
|
||||
material_data.metallic_factor = gltf_material.pbrData.metallicFactor;
|
||||
material_data.roughness_factor = gltf_material.pbrData.roughnessFactor;
|
||||
|
||||
if (gltf_material.pbrData.baseColorTexture)
|
||||
{
|
||||
material_ref.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex);
|
||||
material_data.base_color_texcoord = gltf_material.pbrData.baseColorTexture->texCoordIndex;
|
||||
}
|
||||
|
||||
if (gltf_material.pbrData.metallicRoughnessTexture)
|
||||
{
|
||||
material_ref.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex);
|
||||
material_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex;
|
||||
}
|
||||
|
||||
if (gltf_material.occlusionTexture)
|
||||
{
|
||||
material_ref.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex);
|
||||
material_data.occlusion_texcoord = gltf_material.occlusionTexture->texCoordIndex;
|
||||
material_data.occlusion_strength = gltf_material.occlusionTexture->strength;
|
||||
}
|
||||
|
||||
if (gltf_material.emissiveTexture)
|
||||
{
|
||||
material_ref.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex);
|
||||
material_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex;
|
||||
}
|
||||
|
||||
if (gltf_material.normalTexture)
|
||||
{
|
||||
material_ref.normal_texture = textures.at(gltf_material.normalTexture->textureIndex);
|
||||
material_data.normal_texcoord = gltf_material.normalTexture->texCoordIndex;
|
||||
material_data.normal_scale = gltf_material.normalTexture->scale;
|
||||
}
|
||||
|
||||
material_ref.offset = staging_buffer.add_uniform(material_data);
|
||||
}
|
||||
|
||||
return materials;
|
||||
}
|
||||
|
||||
std::vector<scene_data::mesh> load_all_meshes(std::vector<std::shared_ptr<scene_data::material>> & materials, gpu_buffer & staging_buffer)
|
||||
{
|
||||
std::vector<scene_data::mesh> meshes;
|
||||
meshes.reserve(gltf.meshes.size());
|
||||
for (const fastgltf::Mesh & gltf_mesh: gltf.meshes)
|
||||
{
|
||||
auto & mesh_ref = meshes.emplace_back();
|
||||
|
||||
mesh_ref.primitives.reserve(gltf_mesh.primitives.size());
|
||||
|
||||
for (const fastgltf::Primitive & gltf_primitive: gltf_mesh.primitives)
|
||||
{
|
||||
auto & primitive_ref = mesh_ref.primitives.emplace_back();
|
||||
|
||||
if (gltf_primitive.indicesAccessor)
|
||||
{
|
||||
fastgltf::Accessor & indices_accessor = gltf.accessors.at(*gltf_primitive.indicesAccessor);
|
||||
|
||||
primitive_ref.indexed = true;
|
||||
primitive_ref.index_offset = staging_buffer.add_indices(indices_accessor);
|
||||
primitive_ref.index_count = indices_accessor.count;
|
||||
|
||||
switch (indices_accessor.componentType)
|
||||
{
|
||||
case fastgltf::ComponentType::Byte:
|
||||
case fastgltf::ComponentType::UnsignedByte:
|
||||
primitive_ref.index_type = vk::IndexType::eUint8EXT;
|
||||
break;
|
||||
|
||||
case fastgltf::ComponentType::Short:
|
||||
case fastgltf::ComponentType::UnsignedShort:
|
||||
primitive_ref.index_type = vk::IndexType::eUint16;
|
||||
break;
|
||||
|
||||
case fastgltf::ComponentType::Int:
|
||||
case fastgltf::ComponentType::UnsignedInt:
|
||||
primitive_ref.index_type = vk::IndexType::eUint32;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw std::runtime_error("Invalid index type");
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
primitive_ref.indexed = false;
|
||||
}
|
||||
|
||||
std::vector<scene_data::vertex> vertices;
|
||||
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "POSITION", vertices, &scene_data::vertex::position);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "NORMAL", vertices, &scene_data::vertex::normal);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "TANGENT", vertices, &scene_data::vertex::tangent);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "TEXCOORD_", vertices, &scene_data::vertex::texcoord);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "COLOR", vertices, &scene_data::vertex::color);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "JOINTS_", vertices, &scene_data::vertex::joints);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "WEIGHTS_", vertices, &scene_data::vertex::weights);
|
||||
|
||||
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::eClockwise; // TBC
|
||||
primitive_ref.topology = convert(gltf_primitive.type);
|
||||
|
||||
if (gltf_primitive.materialIndex)
|
||||
primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex);
|
||||
}
|
||||
}
|
||||
|
||||
return meshes;
|
||||
}
|
||||
|
||||
std::vector<scene_data::scene_object> load_all_objects()
|
||||
{
|
||||
std::vector<scene_data::scene_object> unsorted_objects;
|
||||
unsorted_objects.resize(gltf.nodes.size(), {.parent_id = scene_data::scene_object::root_id });
|
||||
|
||||
for (const auto & [index, gltf_node]: utils::enumerate(gltf.nodes))
|
||||
{
|
||||
if (gltf_node.meshIndex)
|
||||
unsorted_objects[index].mesh_id = *gltf_node.meshIndex;
|
||||
|
||||
for (size_t child: gltf_node.children)
|
||||
{
|
||||
unsorted_objects[child].parent_id = index;
|
||||
}
|
||||
|
||||
auto TRS = std::get<fastgltf::Node::TRS>(gltf_node.transform);
|
||||
|
||||
unsorted_objects[index].translation = glm::make_vec3(TRS.translation.data());
|
||||
unsorted_objects[index].rotation = glm::make_quat(TRS.rotation.data());
|
||||
unsorted_objects[index].scale = glm::make_vec3(TRS.scale.data());
|
||||
unsorted_objects[index].visible = true;
|
||||
unsorted_objects[index].name = gltf_node.name;
|
||||
}
|
||||
|
||||
return unsorted_objects;
|
||||
}
|
||||
|
||||
std::vector<scene_data::scene_object> topological_sort(const std::vector<scene_data::scene_object> & unsorted_objects)
|
||||
{
|
||||
std::vector<scene_data::scene_object> sorted_objects;
|
||||
std::vector<size_t> new_index;
|
||||
std::vector<bool> already_sorted;
|
||||
|
||||
sorted_objects.reserve(unsorted_objects.size());
|
||||
already_sorted.resize(unsorted_objects.size(), false);
|
||||
new_index.resize(unsorted_objects.size(), scene_data::scene_object::root_id);
|
||||
|
||||
bool loop_detected = true;
|
||||
|
||||
while (sorted_objects.size() < unsorted_objects.size())
|
||||
{
|
||||
for (size_t i = 0; i < unsorted_objects.size(); i++)
|
||||
{
|
||||
if (already_sorted[i])
|
||||
continue;
|
||||
|
||||
if (unsorted_objects[i].parent_id == scene_data::scene_object::root_id)
|
||||
{
|
||||
sorted_objects.push_back(unsorted_objects[i]);
|
||||
already_sorted[i] = true;
|
||||
new_index[i] = sorted_objects.size() - 1;
|
||||
loop_detected = false;
|
||||
}
|
||||
else if (already_sorted[unsorted_objects[i].parent_id])
|
||||
{
|
||||
sorted_objects.emplace_back(unsorted_objects[i]).parent_id = new_index[unsorted_objects[i].parent_id];
|
||||
already_sorted[i] = true;
|
||||
new_index[i] = sorted_objects.size() - 1;
|
||||
loop_detected = false;
|
||||
}
|
||||
}
|
||||
|
||||
assert(!loop_detected);
|
||||
}
|
||||
|
||||
assert(sorted_objects.size() == unsorted_objects.size());
|
||||
for(size_t i = 0; i < sorted_objects.size(); i++)
|
||||
{
|
||||
assert(sorted_objects[i].parent_id == scene_data::scene_object::root_id || sorted_objects[i].parent_id < i);
|
||||
}
|
||||
|
||||
return sorted_objects;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
scene_data scene_loader::operator()(const std::filesystem::path & gltf_path)
|
||||
{
|
||||
vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
|
||||
vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{
|
||||
.flags = vk::CommandPoolCreateFlagBits::eTransient,
|
||||
.queueFamilyIndex = queue_family_index,
|
||||
}};
|
||||
|
||||
scene_data data;
|
||||
|
||||
asset asset_file(gltf_path);
|
||||
fastgltf::GltfDataBuffer data_buffer;
|
||||
data_buffer.copyBytes(reinterpret_cast<const uint8_t*>(asset_file.data()), asset_file.size());
|
||||
|
||||
fastgltf::Asset asset = load_gltf_asset(data_buffer, gltf_path.parent_path());
|
||||
loader_context ctx(gltf_path.parent_path(), asset, device, queue, cb_pool);
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None)
|
||||
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
|
||||
#endif
|
||||
|
||||
// Load all buffers from URIs
|
||||
ctx.load_all_buffers();
|
||||
|
||||
gpu_buffer staging_buffer(physical_device_properties, asset);
|
||||
|
||||
// Load all images
|
||||
auto images = ctx.load_all_images();
|
||||
|
||||
// Load all textures
|
||||
auto textures = ctx.load_all_textures(images);
|
||||
|
||||
// Load all materials
|
||||
auto materials = ctx.load_all_materials(textures, staging_buffer, *default_material);
|
||||
|
||||
// Load all meshes
|
||||
data.meshes = ctx.load_all_meshes(materials, staging_buffer);
|
||||
|
||||
data.scene_objects = ctx.topological_sort(ctx.load_all_objects());
|
||||
|
||||
// Copy the staging buffer to the GPU
|
||||
spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size());
|
||||
auto buffer = std::make_shared<buffer_allocation>(staging_buffer.copy_to_gpu());
|
||||
|
||||
for (auto & i: materials)
|
||||
i->buffer = buffer;
|
||||
|
||||
for (auto & i: data.meshes)
|
||||
i.buffer = buffer;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
scene_data & scene_data::import(scene_data && other, scene_object_handle parent)
|
||||
{
|
||||
assert(parent.scene == this || parent.id == scene_object::root_id);
|
||||
|
||||
size_t mesh_offset = meshes.size();
|
||||
size_t scene_objects_offset = scene_objects.size();
|
||||
|
||||
for (auto & i: other.meshes)
|
||||
meshes.push_back(std::move(i));
|
||||
|
||||
for (auto i: other.scene_objects)
|
||||
{
|
||||
assert(!i.mesh_id || *i.mesh_id < other.meshes.size());
|
||||
|
||||
if (i.mesh_id)
|
||||
*i.mesh_id += mesh_offset;
|
||||
|
||||
if (i.parent_id == scene_object::root_id)
|
||||
{
|
||||
i.parent_id = parent.id;
|
||||
}
|
||||
else
|
||||
{
|
||||
assert(i.parent_id < other.scene_objects.size());
|
||||
i.parent_id += scene_objects_offset;
|
||||
}
|
||||
|
||||
scene_objects.push_back(i);
|
||||
}
|
||||
|
||||
other.meshes.clear();
|
||||
other.scene_objects.clear();
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
scene_data & scene_data::import(scene_data && other)
|
||||
{
|
||||
return import(std::move(other), {});
|
||||
}
|
||||
|
||||
scene_object_handle scene_data::new_node()
|
||||
{
|
||||
size_t id = scene_objects.size();
|
||||
|
||||
scene_objects.push_back(scene_object{
|
||||
.parent_id = scene_object::root_id,
|
||||
.translation = {0, 0, 0},
|
||||
.rotation = {1, 0, 0, 0},
|
||||
.scale = {1, 1, 1},
|
||||
.visible = true
|
||||
});
|
||||
|
||||
return {id, this};
|
||||
}
|
||||
|
||||
scene_object_handle scene_data::find_node(std::string_view name)
|
||||
{
|
||||
for(auto&& [index, node]: utils::enumerate(scene_objects))
|
||||
{
|
||||
if (node.name == name)
|
||||
{
|
||||
return {index, this};
|
||||
}
|
||||
}
|
||||
|
||||
// TODO custom exception
|
||||
throw std::runtime_error("Node " + std::string(name) + " not found");
|
||||
}
|
||||
|
||||
scene_object_handle scene_data::find_node(scene_object_handle root, std::string_view name)
|
||||
{
|
||||
assert(root.id < scene_objects.size());
|
||||
assert(root.scene == this);
|
||||
|
||||
std::vector<bool> flag(scene_objects.size(), false);
|
||||
|
||||
flag[root.id] = true;
|
||||
|
||||
for(size_t index = root.id; index < scene_objects.size(); index++)
|
||||
{
|
||||
size_t parent = scene_objects[index].parent_id;
|
||||
|
||||
if (parent == scene_object::root_id)
|
||||
continue;
|
||||
|
||||
if (!flag[parent])
|
||||
continue;
|
||||
|
||||
if (scene_objects[index].name == name)
|
||||
return {index, this};
|
||||
|
||||
flag[index] = true;
|
||||
}
|
||||
|
||||
// TODO custom exception
|
||||
throw std::runtime_error("Node " + std::string(name) + " not found");
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.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 <array>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <glm/ext/quaternion_float.hpp>
|
||||
#include <glm/mat4x4.hpp>
|
||||
#include <glm/vec2.hpp>
|
||||
#include <glm/vec3.hpp>
|
||||
#include <glm/vec4.hpp>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utils/magic_hash.h>
|
||||
#include <vector>
|
||||
#include <vk/allocation.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
struct sampler_info
|
||||
{
|
||||
vk::Filter mag_filter = vk::Filter::eLinear;
|
||||
vk::Filter min_filter = vk::Filter::eLinear;
|
||||
vk::SamplerMipmapMode min_filter_mipmap = vk::SamplerMipmapMode::eLinear;
|
||||
vk::SamplerAddressMode wrapS = vk::SamplerAddressMode::eRepeat;
|
||||
vk::SamplerAddressMode wrapT = vk::SamplerAddressMode::eRepeat;
|
||||
|
||||
bool operator==(const sampler_info & other) const noexcept = default;
|
||||
};
|
||||
|
||||
namespace std
|
||||
{
|
||||
template <>
|
||||
struct hash<sampler_info> : utils::magic_hash<sampler_info>
|
||||
{};
|
||||
} // namespace std
|
||||
|
||||
class scene_object_handle;
|
||||
|
||||
struct scene_data
|
||||
{
|
||||
struct image
|
||||
{
|
||||
image_allocation image_;
|
||||
vk::raii::ImageView image_view = nullptr;
|
||||
};
|
||||
|
||||
struct texture
|
||||
{
|
||||
std::shared_ptr<image> image_{};
|
||||
sampler_info sampler;
|
||||
};
|
||||
|
||||
struct material
|
||||
{
|
||||
struct gpu_data
|
||||
{
|
||||
glm::vec4 base_color_factor = glm::vec4(1, 1, 1, 1);
|
||||
glm::vec4 base_emissive_factor = glm::vec4(0, 0, 0, 0);
|
||||
float metallic_factor = 1;
|
||||
float roughness_factor = 1;
|
||||
float occlusion_strength = 0;
|
||||
float normal_scale = 0;
|
||||
|
||||
uint32_t base_color_texcoord = 0;
|
||||
uint32_t metallic_roughness_texcoord = 0;
|
||||
uint32_t occlusion_texcoord = 0;
|
||||
uint32_t emissive_texcoord = 0;
|
||||
uint32_t normal_texcoord = 0;
|
||||
|
||||
// TODO: add fastgltf::TextureTransform?
|
||||
};
|
||||
|
||||
std::shared_ptr<texture> base_color_texture;
|
||||
std::shared_ptr<texture> metallic_roughness_texture;
|
||||
std::shared_ptr<texture> occlusion_texture;
|
||||
std::shared_ptr<texture> emissive_texture;
|
||||
std::shared_ptr<texture> normal_texture;
|
||||
|
||||
// Disable back face culling with this material
|
||||
bool double_sided = true;
|
||||
|
||||
// TODO transparency
|
||||
// fastgltf::AlphaMode alphaMode;
|
||||
// float alpha_cutoff;
|
||||
|
||||
gpu_data staging;
|
||||
|
||||
// Resources used by this material
|
||||
std::shared_ptr<buffer_allocation> buffer;
|
||||
size_t offset;
|
||||
|
||||
// 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;
|
||||
};
|
||||
|
||||
struct vertex
|
||||
{
|
||||
glm::vec3 position;
|
||||
glm::vec3 normal;
|
||||
glm::vec3 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();
|
||||
};
|
||||
|
||||
struct primitive
|
||||
{
|
||||
bool indexed;
|
||||
uint32_t index_count;
|
||||
uint32_t vertex_count;
|
||||
vk::IndexType index_type;
|
||||
vk::DeviceSize index_offset;
|
||||
vk::DeviceSize vertex_offset;
|
||||
|
||||
// See also material::double_sided
|
||||
vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone;
|
||||
vk::FrontFace front_face = vk::FrontFace::eClockwise;
|
||||
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
|
||||
|
||||
std::shared_ptr<material> material_;
|
||||
};
|
||||
|
||||
struct mesh
|
||||
{
|
||||
std::vector<primitive> primitives;
|
||||
std::shared_ptr<buffer_allocation> buffer;
|
||||
};
|
||||
|
||||
struct scene_object
|
||||
{
|
||||
static constexpr size_t root_id = size_t(-1);
|
||||
|
||||
size_t parent_id;
|
||||
std::optional<size_t> mesh_id;
|
||||
|
||||
glm::vec3 translation;
|
||||
glm::quat rotation;
|
||||
glm::vec3 scale;
|
||||
|
||||
std::string name;
|
||||
bool visible;
|
||||
|
||||
// std::vector<glm::mat4> bones_transform; // TODO: bones
|
||||
};
|
||||
|
||||
// TODO: lights
|
||||
// TODO: skybox
|
||||
|
||||
std::vector<scene_data::mesh> meshes;
|
||||
std::vector<scene_data::scene_object> scene_objects;
|
||||
|
||||
scene_data() = default;
|
||||
scene_data(const scene_data &) = delete;
|
||||
scene_data(scene_data &&) = default;
|
||||
scene_data & operator=(const scene_data &) = delete;
|
||||
scene_data & operator=(scene_data &&) = default;
|
||||
|
||||
scene_data& import(scene_data && other, scene_object_handle parent);
|
||||
scene_data& import(scene_data && other);
|
||||
|
||||
scene_object_handle new_node();
|
||||
scene_object_handle find_node(std::string_view name);
|
||||
scene_object_handle find_node(scene_object_handle parent, std::string_view name);
|
||||
};
|
||||
|
||||
class scene_loader
|
||||
{
|
||||
vk::raii::Device & device;
|
||||
vk::raii::PhysicalDevice physical_device;
|
||||
vk::raii::Queue & queue;
|
||||
uint32_t queue_family_index;
|
||||
std::shared_ptr<scene_data::material> default_material;
|
||||
|
||||
public:
|
||||
scene_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, uint32_t queue_family_index, std::shared_ptr<scene_data::material> default_material) :
|
||||
device(device),
|
||||
physical_device(physical_device),
|
||||
queue(queue),
|
||||
queue_family_index(queue_family_index),
|
||||
default_material(default_material)
|
||||
{}
|
||||
|
||||
scene_data operator()(const std::filesystem::path & gltf_path);
|
||||
};
|
||||
|
||||
class scene_object_handle
|
||||
{
|
||||
friend struct scene_data;
|
||||
size_t id = scene_data::scene_object::root_id;
|
||||
scene_data * scene = nullptr;
|
||||
|
||||
public:
|
||||
scene_object_handle() = default;
|
||||
scene_object_handle(size_t id, scene_data * scene) : id(id), scene(scene) {}
|
||||
scene_object_handle(const scene_object_handle&) = default;
|
||||
scene_object_handle& operator=(const scene_object_handle&) = default;
|
||||
|
||||
scene_data::scene_object& operator*()
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_objects.size());
|
||||
return scene->scene_objects[id];
|
||||
}
|
||||
|
||||
const scene_data::scene_object& operator*() const
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_objects.size());
|
||||
return scene->scene_objects[id];
|
||||
}
|
||||
|
||||
scene_data::scene_object* operator->()
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_objects.size());
|
||||
return &scene->scene_objects[id];
|
||||
}
|
||||
|
||||
const scene_data::scene_object* operator->() const
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_objects.size());
|
||||
return &scene->scene_objects[id];
|
||||
}
|
||||
};
|
||||
+742
-806
File diff suppressed because it is too large
Load Diff
+184
-187
@@ -1,187 +1,184 @@
|
||||
// #pragma once
|
||||
//
|
||||
// #include <memory>
|
||||
// #include <span>
|
||||
// #include <vector>
|
||||
// #include <vulkan/vulkan.h>
|
||||
//
|
||||
// #include "glm/vec2.hpp"
|
||||
// #include "glm/vec3.hpp"
|
||||
// #include "tiny_gltf.h"
|
||||
// #include "vk/buffer.h"
|
||||
// #include "vk/command_pool.h"
|
||||
// #include "vk/device_memory.h"
|
||||
// #include "vk/image.h"
|
||||
// #include "vk/pipeline.h"
|
||||
// #include "vk/renderpass.h"
|
||||
//
|
||||
// class scene_renderer
|
||||
//
|
||||
// {
|
||||
// public:
|
||||
// class shader
|
||||
// {
|
||||
// friend class scene_renderer;
|
||||
//
|
||||
// std::vector<VkDescriptorSetLayout> descriptor_set_layouts;
|
||||
// std::vector<VkDescriptorPool> descriptor_pools;
|
||||
// VkShaderModule vertex_shader{};
|
||||
// VkShaderModule fragment_shader{};
|
||||
// VkPipelineLayout pipeline_layout{};
|
||||
//
|
||||
// struct pipeline_info
|
||||
// {
|
||||
// VkPrimitiveTopology topology;
|
||||
// std::vector<VkVertexInputBindingDescription> vertex_bindings;
|
||||
// std::vector<VkVertexInputAttributeDescription> vertex_attributes;
|
||||
// };
|
||||
//
|
||||
// std::vector<std::pair<pipeline_info, VkPipeline>> pipelines;
|
||||
//
|
||||
// shader() = default;
|
||||
// shader(const shader &) = delete;
|
||||
// shader(shader &&) = delete;
|
||||
// };
|
||||
//
|
||||
// class image
|
||||
// {
|
||||
// friend class scene_renderer;
|
||||
//
|
||||
// VkDeviceMemory memory{};
|
||||
// VkSampler sampler{};
|
||||
// VkImage vk_image{};
|
||||
// VkImageView image_view{};
|
||||
// VkDescriptorSet descriptor_set{};
|
||||
//
|
||||
// image() = default;
|
||||
// image(const image &) = delete;
|
||||
// image(image &&) = delete;
|
||||
// };
|
||||
//
|
||||
// class buffer
|
||||
// {
|
||||
// friend class scene_renderer;
|
||||
//
|
||||
// VkDeviceMemory memory{};
|
||||
// VkBuffer vk_buffer{};
|
||||
//
|
||||
// buffer() = default;
|
||||
// buffer(const buffer &) = delete;
|
||||
// buffer(buffer &&) = delete;
|
||||
// };
|
||||
//
|
||||
// struct mesh_primitive
|
||||
// {
|
||||
// struct vertex
|
||||
// {
|
||||
// glm::vec3 position;
|
||||
// glm::vec3 normal;
|
||||
// glm::vec2 texcoord;
|
||||
// };
|
||||
//
|
||||
// VkPrimitiveTopology topology;
|
||||
//
|
||||
// VkPipeline pipeline;
|
||||
//
|
||||
// std::weak_ptr<buffer> indices;
|
||||
// size_t indices_offset;
|
||||
// size_t indices_count;
|
||||
//
|
||||
// std::weak_ptr<buffer> vertices;
|
||||
// size_t vertices_offset;
|
||||
// };
|
||||
//
|
||||
// class model
|
||||
// {
|
||||
// friend class scene_renderer;
|
||||
//
|
||||
// tinygltf::Model gltf_model;
|
||||
// std::vector<std::weak_ptr<image>> images;
|
||||
// std::vector<std::weak_ptr<buffer>> buffers;
|
||||
// };
|
||||
//
|
||||
// class model_instance
|
||||
// {
|
||||
// friend class scene_renderer;
|
||||
//
|
||||
// model * gltf_model;
|
||||
//
|
||||
// void * ubo;
|
||||
// };
|
||||
//
|
||||
// private:
|
||||
// VkDevice device;
|
||||
// VkPhysicalDevice physical_device;
|
||||
// VkPhysicalDeviceProperties physical_device_properties;
|
||||
// VkQueue queue;
|
||||
// vk::command_pool command_pool;
|
||||
//
|
||||
// tinygltf::TinyGLTF gltf_loader;
|
||||
//
|
||||
// // Staging buffer
|
||||
// size_t staging_buffer_size = 0;
|
||||
// vk::buffer staging_buffer;
|
||||
// vk::device_memory staging_memory;
|
||||
// VkFence staging_fence{};
|
||||
// void reserve(size_t size);
|
||||
//
|
||||
// void load_buffer(VkBuffer b, const void * data, size_t size);
|
||||
//
|
||||
// template <typename T>
|
||||
// void load_buffer(VkBuffer b, std::span<T> data)
|
||||
// {
|
||||
// load_buffer(b, data.data(), data.size() * sizeof(T));
|
||||
// }
|
||||
//
|
||||
// void load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
|
||||
//
|
||||
// // Scene data
|
||||
// std::vector<std::shared_ptr<shader>> shaders;
|
||||
// std::vector<std::shared_ptr<image>> images;
|
||||
// std::vector<std::shared_ptr<buffer>> buffers;
|
||||
// std::vector<std::shared_ptr<mesh_primitive>> primitives;
|
||||
// std::vector<std::shared_ptr<model>> models;
|
||||
// std::vector<model_instance> instances;
|
||||
//
|
||||
// // Destination images
|
||||
// std::vector<VkImage> output_images;
|
||||
// std::vector<VkImageView> output_image_views;
|
||||
// std::vector<VkFramebuffer> output_framebuffers;
|
||||
// VkExtent2D output_size{};
|
||||
// VkFormat output_format{};
|
||||
//
|
||||
// // Render pass
|
||||
// vk::renderpass renderpass;
|
||||
//
|
||||
// void cleanup();
|
||||
// void cleanup_output_images();
|
||||
// void cleanup_shader(shader *);
|
||||
// void cleanup_buffer(buffer *);
|
||||
// void cleanup_image(image *);
|
||||
//
|
||||
// public:
|
||||
// scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue);
|
||||
// ~scene_renderer();
|
||||
// scene_renderer(const scene_renderer &) = delete;
|
||||
// scene_renderer(scene_renderer &&) = delete;
|
||||
//
|
||||
// void set_output_images(std::vector<VkImage> output_images, VkExtent2D output_size, VkFormat output_format);
|
||||
//
|
||||
// std::weak_ptr<shader> create_shader(std::string name,
|
||||
// std::vector<std::vector<VkDescriptorSetLayoutBinding>> uniform_bindings);
|
||||
//
|
||||
// VkPipeline get_shader_pipeline(std::weak_ptr<shader> shader, VkPrimitiveTopology topology, std::span<VkVertexInputBindingDescription> vertex_bindings, std::span<VkVertexInputAttributeDescription> vertex_attributes);
|
||||
//
|
||||
// std::weak_ptr<image> create_image(void * data, VkExtent2D size, VkFormat format);
|
||||
//
|
||||
// std::weak_ptr<buffer> create_buffer(const void * data, size_t size, VkBufferUsageFlags usage);
|
||||
//
|
||||
// template <typename T>
|
||||
// // requires(std::contiguous_iterator<typename T::iterator>)
|
||||
// std::weak_ptr<buffer> create_buffer(const T & data, VkBufferUsageFlags usage)
|
||||
// {
|
||||
// return create_buffer(data.data(), data.size() * sizeof(T), usage);
|
||||
// }
|
||||
//
|
||||
// model * load_gltf(const std::string & filename);
|
||||
// };
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 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 <vulkan/vulkan.hpp>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <glm/mat4x4.hpp>
|
||||
#include <glm/vec2.hpp>
|
||||
#include <glm/vec3.hpp>
|
||||
#include <glm/vec4.hpp>
|
||||
#include <span>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "vk/allocation.h"
|
||||
|
||||
#include "render/growable_descriptor_pool.h"
|
||||
#include "render/scene_data.h"
|
||||
|
||||
struct pipeline_info
|
||||
{
|
||||
std::string shader_name;
|
||||
|
||||
vk::CullModeFlags cull_mode = vk::CullModeFlagBits::eNone;
|
||||
vk::FrontFace front_face = vk::FrontFace::eClockwise;
|
||||
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
|
||||
|
||||
bool operator==(const pipeline_info & other) const noexcept = default;
|
||||
};
|
||||
|
||||
namespace std
|
||||
{
|
||||
template <>
|
||||
struct hash<pipeline_info> : utils::magic_hash<pipeline_info>
|
||||
{};
|
||||
} // namespace std
|
||||
|
||||
class scene_renderer
|
||||
{
|
||||
public:
|
||||
// vk::raii::Instance& instance;
|
||||
vk::raii::Device & device;
|
||||
// vk::raii::PhysicalDevice physical_device;
|
||||
vk::PhysicalDeviceProperties physical_device_properties;
|
||||
vk::raii::Queue & queue;
|
||||
|
||||
// Scene format
|
||||
const vk::Extent2D output_size;
|
||||
const vk::Format output_format;
|
||||
const vk::Format depth_format;
|
||||
|
||||
// Destination images
|
||||
struct output_image
|
||||
{
|
||||
vk::raii::Framebuffer framebuffer = nullptr;
|
||||
vk::raii::ImageView image_view = nullptr;
|
||||
|
||||
image_allocation depth_buffer;
|
||||
vk::raii::ImageView depth_view = nullptr;
|
||||
};
|
||||
|
||||
// Initialization functions
|
||||
output_image create_output_image_data(vk::Image output);
|
||||
vk::raii::RenderPass create_renderpass();
|
||||
vk::raii::PipelineLayout create_pipeline_layout(std::span<vk::DescriptorSetLayout> layouts);
|
||||
vk::raii::Pipeline create_pipeline(const pipeline_info & info);
|
||||
|
||||
std::shared_ptr<scene_data::texture> create_default_texture(vk::raii::CommandBuffer & cb, std::vector<buffer_allocation>& staging_buffers, std::initializer_list<float> pixel);
|
||||
std::shared_ptr<scene_data::material> create_default_material(vk::raii::CommandPool & cb_pool);
|
||||
|
||||
// Caches
|
||||
std::unordered_map<VkImage, output_image> output_images;
|
||||
std::unordered_map<pipeline_info, vk::raii::Pipeline> pipelines;
|
||||
|
||||
output_image & get_output_image_data(vk::Image output);
|
||||
vk::raii::Pipeline & get_pipeline(const pipeline_info & info);
|
||||
|
||||
// Descriptor set 0: per-frame/view data (uniform buffer) and per-instance data (dynamic uniform buffer)
|
||||
growable_descriptor_pool ds_pool_frame;
|
||||
vk::raii::DescriptorSetLayout descriptor_set_frame = nullptr;
|
||||
|
||||
// Descriptor set 1: per-material data (5 combined image samplers and 1 uniform buffer)
|
||||
growable_descriptor_pool ds_pool_material;
|
||||
vk::raii::DescriptorSetLayout descriptor_set_material = nullptr;
|
||||
|
||||
vk::raii::PipelineLayout pipeline_layout = nullptr;
|
||||
|
||||
// Texture samplers
|
||||
std::unordered_map<sampler_info, std::shared_ptr<vk::raii::Sampler>> samplers;
|
||||
vk::Sampler get_sampler(const sampler_info & info);
|
||||
|
||||
// Render pass
|
||||
vk::raii::RenderPass renderpass = nullptr;
|
||||
|
||||
// Default material and textures
|
||||
// This material has 1x1 textures with the following values:
|
||||
// base_color (1.0, 1.0, 1.0, 1.0)
|
||||
// metallic_roughness (1.0, 1.0)
|
||||
// occlusion (1.0)
|
||||
// emissive (0.0, 0.0, 0.0)
|
||||
// normal (0.5, 0.5, 1.0)
|
||||
// And:
|
||||
// base_color_factor (1.0, 1.0, 1.0, 1.0)
|
||||
// base_emissive_factor (0.0, 0.0, 0.0)
|
||||
// metallic_factor 1.0
|
||||
// roughness_factor 1.0
|
||||
// occlusion_strength 0.0
|
||||
// normal_scale 0.0
|
||||
std::shared_ptr<scene_data::material> default_material;
|
||||
|
||||
struct frame_gpu_data
|
||||
{
|
||||
glm::mat4 view;
|
||||
glm::mat4 proj;
|
||||
glm::vec4 light_position;
|
||||
glm::vec4 ambient_color;
|
||||
glm::vec4 light_color;
|
||||
};
|
||||
|
||||
struct instance_gpu_data
|
||||
{
|
||||
glm::mat4 model;
|
||||
glm::mat4 modelview;
|
||||
glm::mat4 modelviewproj;
|
||||
};
|
||||
|
||||
struct per_frame_resources
|
||||
{
|
||||
vk::raii::Fence fence = nullptr;
|
||||
vk::raii::CommandBuffer cb = nullptr;
|
||||
std::vector<std::shared_ptr<void>> resources;
|
||||
|
||||
|
||||
// Uniform buffer for per-view and per-instance data
|
||||
// host visible, host coherent
|
||||
buffer_allocation staging_buffer;
|
||||
// device local
|
||||
// buffer_allocation uniform_buffer;
|
||||
};
|
||||
|
||||
std::vector<per_frame_resources> frame_resources;
|
||||
int current_frame;
|
||||
|
||||
per_frame_resources& start_frame();
|
||||
|
||||
void update_material_descriptor_set(scene_data::material& material);
|
||||
|
||||
public:
|
||||
scene_renderer(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool, vk::Extent2D output_size, vk::Format output_format, std::span<vk::Format> depth_formats, int frames_in_flight = 3);
|
||||
|
||||
~scene_renderer();
|
||||
|
||||
struct frame_info
|
||||
{
|
||||
vk::Image destination;
|
||||
glm::mat4 projection;
|
||||
glm::mat4 view;
|
||||
};
|
||||
|
||||
void render(scene_data & scene, std::span<frame_info> info);
|
||||
|
||||
std::shared_ptr<scene_data::material> get_default_material()
|
||||
{
|
||||
return default_material;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
#include <vulkan/vulkan_handles.hpp>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#ifdef __ANDROID__
|
||||
#include <android/font.h>
|
||||
#include <android/font_matcher.h>
|
||||
#include <android/system_fonts.h>
|
||||
@@ -74,8 +74,7 @@ std::error_category & freetype_error_category()
|
||||
// static hb_feature_t CligOn = { CligTag, 1, 0, std::numeric_limits<unsigned int>::max() };
|
||||
// }
|
||||
|
||||
|
||||
text_rasterizer::text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, vk::raii::CommandPool& command_pool, vk::raii::Queue& queue) :
|
||||
text_rasterizer::text_rasterizer(vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, vk::raii::CommandPool & command_pool, vk::raii::Queue & queue) :
|
||||
device(device),
|
||||
physical_device(physical_device),
|
||||
command_pool(command_pool),
|
||||
@@ -84,7 +83,7 @@ text_rasterizer::text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDev
|
||||
{
|
||||
std::string font_filename;
|
||||
|
||||
#ifdef XR_USE_PLATFORM_ANDROID
|
||||
#ifdef __ANDROID__
|
||||
{
|
||||
std::u16string ws = u"hello";
|
||||
AFontMatcher * font_matcher = AFontMatcher_create();
|
||||
@@ -142,39 +141,41 @@ text_rasterizer::text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDev
|
||||
image_allocation text_rasterizer::create_image(vk::Extent2D size)
|
||||
{
|
||||
image_allocation alloc{vk::ImageCreateInfo{
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = text::format,
|
||||
.extent = {
|
||||
.width = size.width,
|
||||
.height = size.height,
|
||||
.depth = 1,
|
||||
},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = vk::SampleCountFlagBits::e1,
|
||||
.tiling = vk::ImageTiling::eOptimal,
|
||||
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
|
||||
.sharingMode = vk::SharingMode::eExclusive,
|
||||
.initialLayout = vk::ImageLayout::eUndefined,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = 0,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
}};
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = text::format,
|
||||
.extent = {
|
||||
.width = size.width,
|
||||
.height = size.height,
|
||||
.depth = 1,
|
||||
},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = vk::SampleCountFlagBits::e1,
|
||||
.tiling = vk::ImageTiling::eOptimal,
|
||||
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
|
||||
.sharingMode = vk::SharingMode::eExclusive,
|
||||
.initialLayout = vk::ImageLayout::eUndefined,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = 0,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
}};
|
||||
|
||||
application::set_debug_reports_name<vk::Image>(alloc, "text_rasterizer image");
|
||||
return alloc;
|
||||
}
|
||||
|
||||
buffer_allocation text_rasterizer::create_buffer(size_t size)
|
||||
{
|
||||
buffer_allocation alloc{vk::BufferCreateInfo{
|
||||
.size = size,
|
||||
.usage = vk::BufferUsageFlagBits::eTransferSrc,
|
||||
},
|
||||
VmaAllocationCreateInfo {
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
}};
|
||||
.size = size,
|
||||
.usage = vk::BufferUsageFlagBits::eTransferSrc,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
}};
|
||||
application::set_debug_reports_name<vk::Buffer>(alloc, "text_rasterizer buffer");
|
||||
|
||||
return alloc;
|
||||
}
|
||||
@@ -297,53 +298,50 @@ text text_rasterizer::render(std::string_view s)
|
||||
memcpy(mapped, rendered_text.data(), rendered_text.size());
|
||||
|
||||
vk::raii::CommandBuffers cmdbufs(device, {
|
||||
.commandPool = *command_pool,
|
||||
.level = vk::CommandBufferLevel::ePrimary,
|
||||
.commandBufferCount = 1,
|
||||
});
|
||||
vk::raii::CommandBuffer& cmdbuf = cmdbufs[0];
|
||||
application::set_debug_reports_name((VkCommandBuffer)*cmdbuf, "text_rasterizer command buffer");
|
||||
.commandPool = *command_pool,
|
||||
.level = vk::CommandBufferLevel::ePrimary,
|
||||
.commandBufferCount = 1,
|
||||
});
|
||||
vk::raii::CommandBuffer & cmdbuf = cmdbufs[0];
|
||||
application::set_debug_reports_name(*cmdbuf, "text_rasterizer command buffer");
|
||||
|
||||
cmdbuf.begin({});
|
||||
|
||||
|
||||
vk::ImageMemoryBarrier barrier{
|
||||
.srcAccessMask = vk::AccessFlagBits::eNone,
|
||||
.dstAccessMask = vk::AccessFlagBits::eTransferWrite,
|
||||
.oldLayout = vk::ImageLayout::eUndefined,
|
||||
.newLayout = vk::ImageLayout::eTransferDstOptimal,
|
||||
.image = return_value.image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
.srcAccessMask = vk::AccessFlagBits::eNone,
|
||||
.dstAccessMask = vk::AccessFlagBits::eTransferWrite,
|
||||
.oldLayout = vk::ImageLayout::eUndefined,
|
||||
.newLayout = vk::ImageLayout::eTransferDstOptimal,
|
||||
.image = return_value.image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
};
|
||||
cmdbuf.pipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags{}, {}, {}, barrier);
|
||||
|
||||
|
||||
vk::BufferImageCopy copy_info{
|
||||
.bufferOffset = 0,
|
||||
.bufferRowLength = 0,
|
||||
.bufferImageHeight = 0,
|
||||
.imageSubresource = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.mipLevel = 0,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
.imageOffset = {0, 0, 0},
|
||||
.imageExtent = {
|
||||
.width = uint32_t(x_max - x_min),
|
||||
.height = uint32_t(y_max - y_min),
|
||||
.depth = 1,
|
||||
},
|
||||
.bufferOffset = 0,
|
||||
.bufferRowLength = 0,
|
||||
.bufferImageHeight = 0,
|
||||
.imageSubresource = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.mipLevel = 0,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
.imageOffset = {0, 0, 0},
|
||||
.imageExtent = {
|
||||
.width = uint32_t(x_max - x_min),
|
||||
.height = uint32_t(y_max - y_min),
|
||||
.depth = 1,
|
||||
},
|
||||
};
|
||||
cmdbuf.copyBufferToImage(staging_buffer, return_value.image, vk::ImageLayout::eTransferDstOptimal, copy_info);
|
||||
|
||||
|
||||
barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
|
||||
barrier.dstAccessMask = vk::AccessFlagBits::eMemoryRead;
|
||||
barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022-2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022-2023 Patrick Nicolas <patricknicolas@laposte.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
|
||||
@@ -21,12 +20,12 @@
|
||||
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#include "vk/allocation.h"
|
||||
#include <freetype/freetype.h>
|
||||
#include <ft2build.h>
|
||||
#include <hb.h>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include "vk/allocation.h"
|
||||
|
||||
struct text
|
||||
{
|
||||
@@ -45,10 +44,10 @@ struct text
|
||||
|
||||
class text_rasterizer
|
||||
{
|
||||
vk::raii::Device& device;
|
||||
vk::raii::PhysicalDevice& physical_device;
|
||||
vk::raii::CommandPool& command_pool;
|
||||
vk::raii::Queue& queue;
|
||||
vk::raii::Device & device;
|
||||
vk::raii::PhysicalDevice & physical_device;
|
||||
vk::raii::CommandPool & command_pool;
|
||||
vk::raii::Queue & queue;
|
||||
vk::raii::Fence fence;
|
||||
|
||||
FT_Library freetype{};
|
||||
@@ -62,7 +61,7 @@ class text_rasterizer
|
||||
vk::raii::DeviceMemory allocate_memory(vk::Buffer buffer, vk::MemoryPropertyFlags flags);
|
||||
|
||||
public:
|
||||
text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, vk::raii::CommandPool& command_pool, vk::raii::Queue& queue);
|
||||
text_rasterizer(vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, vk::raii::CommandPool & command_pool, vk::raii::Queue & queue);
|
||||
~text_rasterizer();
|
||||
|
||||
text render(std::string_view s);
|
||||
|
||||
Reference in New Issue
Block a user