diff --git a/CMakeLists.txt b/CMakeLists.txt index 7487cbfe..b500f82b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,12 +116,12 @@ endif() # Common dependencies FetchContent_Declare(boostpfr URL https://github.com/boostorg/pfr/archive/refs/tags/2.0.3.tar.gz) - # Client dependencies -FetchContent_Declare(fastgltf URL https://github.com/spnda/fastgltf/archive/refs/tags/v0.6.0.tar.gz) +FetchContent_Declare(fastgltf URL https://github.com/spnda/fastgltf/archive/refs/tags/v0.6.1.tar.gz) FetchContent_Declare(glm URL https://github.com/g-truc/glm/archive/refs/tags/0.9.9.8.tar.gz) FetchContent_Declare(openxr_loader URL https://github.com/KhronosGroup/OpenXR-SDK/archive/refs/tags/release-1.0.32.tar.gz) FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/refs/tags/v1.11.0.tar.gz) +FetchContent_Declare(stb URL https://github.com/nothings/stb/archive/refs/heads/master.zip) # Server dependencies FetchContent_Declare(monado diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 0c5a66fc..cc1ef33b 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -1,4 +1,4 @@ -FetchContent_MakeAvailable(spdlog glm fastgltf imgui) +FetchContent_MakeAvailable(spdlog glm fastgltf imgui stb) include(FreetypeHarfbuzz) include(CompileGLSL) @@ -14,6 +14,9 @@ add_library(imgui OBJECT target_include_directories(imgui PUBLIC ${imgui_SOURCE_DIR}) +add_library(stb INTERFACE) +target_include_directories(stb INTERFACE ${stb_SOURCE_DIR}) + if(ANDROID) add_library(wivrn MODULE) @@ -62,7 +65,6 @@ if(ANDROID) target_sources(wivrn PRIVATE ${PLATFORM_SOURCE}) else() add_executable(wivrn) - target_compile_definitions(wivrn PRIVATE -DXR_USE_PLATFORM_XLIB) find_package(OpenXR REQUIRED) target_link_libraries(wivrn OpenXR::openxr_loader OpenXR::headers PkgConfig::LIBAV) @@ -110,7 +112,7 @@ file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "*.glsl") target_sources(wivrn PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS}) wivrn_compile_glsl(wivrn ${VULKAN_SHADERS}) -target_link_libraries(wivrn Vulkan::Vulkan spdlog::spdlog glm::glm fastgltf FreetypeHarfbuzz imgui) +target_link_libraries(wivrn Vulkan::Vulkan spdlog::spdlog glm::glm fastgltf FreetypeHarfbuzz imgui stb fastgltf_simdjson) target_compile_definitions(wivrn PRIVATE -DXR_USE_GRAPHICS_API_VULKAN) target_compile_definitions(wivrn PRIVATE -DVMA_STATS_STRING_ENABLED=0) target_compile_options(wivrn PRIVATE -fdiagnostics-color -Wall -Wextra -pedantic) # -Werror diff --git a/client/application.cpp b/client/application.cpp index 3a740bb7..b055938f 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -25,12 +25,12 @@ #include "spdlog/common.h" #include "spdlog/spdlog.h" #include "utils/check.h" -#include "vk/vk.h" #include "xr/xr.h" #include #include "utils/contains.h" #include #include +#include #include #include #include @@ -45,7 +45,7 @@ #include "utils/backtrace.h" #endif -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ #include #include @@ -244,7 +244,7 @@ static XrActionType guess_action_type(const std::string & name) return XR_ACTION_TYPE_FLOAT_INPUT; } -#ifndef XR_USE_PLATFORM_ANDROID +#ifndef __ANDROID__ static std::filesystem::path get_config_base_dir() { const char * xdg_config_home = std::getenv("XDG_CONFIG_HOME"); @@ -379,7 +379,7 @@ void application::initialize_vulkan() } #endif -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ device_extensions.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME); device_extensions.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME); device_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME); @@ -633,7 +633,7 @@ void application::initialize() extensions.push_back(i.c_str()); } -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ xr_instance = xr::instance(app_info.name, app_info.native_app->activity->vm, app_info.native_app->activity->clazz, extensions); #else @@ -675,7 +675,7 @@ void application::initialize() if (swapchain_format == vk::Format::eUndefined) throw std::runtime_error("No supported swapchain format"); - spdlog::info("Using format {}", string_VkFormat(swapchain_format)); + spdlog::info("Using format {}", vk::to_string(swapchain_format)); // XrViewConfigurationProperties view_props = xr_system_id.view_configuration_properties(viewconfig); @@ -717,32 +717,34 @@ std::pair application::get_action(const std::string & re application::application(application_info info) : app_info(std::move(info)) { -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ // https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html setup_jni(); - jni::object<""> act(app_info.native_app->activity->clazz); - auto app = act.call>("getApplication"); - auto ctx = app.call>("getApplicationContext"); - - // Get the intent, to handle wivrn://uri - auto intent = act.call>("getIntent"); - std::string data_string; - if (auto data_string_jni = intent.call("getDataString")) { - data_string = data_string_jni; - } + jni::object<""> act(app_info.native_app->activity->clazz); + auto app = act.call>("getApplication"); + auto ctx = app.call>("getApplicationContext"); - spdlog::info("dataString = {}", data_string); - if (data_string.starts_with("wivrn://")) - { - server_address = data_string.substr(strlen("wivrn://")); - } + // Get the intent, to handle wivrn://uri + auto intent = act.call>("getIntent"); + std::string data_string; + if (auto data_string_jni = intent.call("getDataString")) + { + data_string = data_string_jni; + } - auto files_dir = ctx.call>("getFilesDir"); - if (auto files_dir_path = files_dir.call("getAbsolutePath")) - { - config_path = files_dir_path; + spdlog::info("dataString = {}", data_string); + if (data_string.starts_with("wivrn://")) + { + server_address = data_string.substr(strlen("wivrn://")); + } + + auto files_dir = ctx.call>("getFilesDir"); + if (auto files_dir_path = files_dir.call("getAbsolutePath")) + { + config_path = files_dir_path; + } } app_info.native_app->userData = this; @@ -786,6 +788,24 @@ application::application(application_info info) : }; initializeLoader((const XrLoaderInitInfoBaseHeaderKHR *)&loaderInitInfoAndroid); } + + + { + spdlog::info("trying stuff"); + AAssetDir * dir = AAssetManager_openDir(asset_manager(), ""); + const char * filename; + while((filename = AAssetDir_getNextFileName(dir)) != nullptr) + { + spdlog::info("Found asset file: {}", filename); + } + + dir = AAssetManager_openDir(asset_manager(), "assets"); + while((filename = AAssetDir_getNextFileName(dir)) != nullptr) + { + spdlog::info("Found asset file: assets/{}", filename); + } + }; + #else config_path = get_config_base_dir() / "wivrn"; #endif @@ -797,14 +817,15 @@ application::application(application_info info) : { initialize(); } - catch (...) + catch (std::exception& e) { + spdlog::error("Error during initialization: {}", e.what()); cleanup(); throw; } } -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ void application::setup_jni() { jni::jni_thread::setup_thread(app_info.native_app->activity->vm); @@ -848,9 +869,15 @@ void application::set_wifi_locks(bool enabled) void application::cleanup() { - // The Vulkan device and instance are destroyed by the OpenXR runtime + if (allocator) + { + // vmaDestroyAllocator(allocator); + // allocator = nullptr; + } + +#ifdef __ANDROID__ + -#ifdef XR_USE_PLATFORM_ANDROID jni::jni_thread::detach(); #endif } @@ -895,7 +922,7 @@ void application::loop() } } -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ void application::run() { std::thread application_thread{[&]() { @@ -1096,7 +1123,7 @@ void application::session_state_changed(XrSessionState new_state, XrTime timesta case XR_SESSION_STATE_FOCUSED: session_visible = true; session_focused = true; -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ set_wifi_locks(true); #endif break; @@ -1106,7 +1133,7 @@ void application::session_state_changed(XrSessionState new_state, XrTime timesta session_focused = false; xr_session.end_session(); session_running = false; -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ set_wifi_locks(false); #endif break; diff --git a/client/application.h b/client/application.h index f8cd063f..7f5d2cc7 100644 --- a/client/application.h +++ b/client/application.h @@ -19,12 +19,11 @@ #pragma once -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ #include #endif #include "spdlog/spdlog.h" -#include "vk/vk.h" #include "xr/xr.h" #include #include @@ -47,7 +46,7 @@ struct application_info XrViewConfigurationType viewconfig = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO; XrVersion min_vulkan_version = XR_MAKE_VERSION(1, 1, 0); -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ android_app * native_app; #endif }; @@ -57,7 +56,7 @@ class application : public singleton friend class scene; application_info app_info; -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ ANativeWindow * native_window = nullptr; bool resumed = false; #endif @@ -150,10 +149,15 @@ public: application(const application &) = delete; ~application(); -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ void setup_jni(); void set_wifi_locks(bool enabled); + + static AAssetManager* asset_manager() + { + return instance().app_info.native_app->activity->assetManager; + } #endif static bool is_session_running() @@ -259,12 +263,22 @@ public: #endif } - static void set_debug_reports_name(void * object, std::string name) + template + static void set_debug_reports_name(const T& object, std::string name) { -#ifndef NDEBUG - printf("set_debug_reports_name %p, %s\n", object, name.c_str()); - instance().debug_report_object_name[(uint64_t)object] = std::move(name); -#endif +// #ifndef NDEBUG + // if (instance().debug_utils_found) + const vk::DebugUtilsObjectNameInfoEXT name_info { + .objectType = T::objectType, + .objectHandle = (uint64_t)(typename T::NativeType)object, + .pObjectName = name.c_str(), + }; + + instance().vk_device.setDebugUtilsObjectNameEXT(name_info); + + // printf("set_debug_reports_name %p, %s\n", object, name.c_str()); + // instance().debug_report_object_name[(uint64_t)object] = std::move(name); +// #endif } static XrTime now() diff --git a/client/asset.cpp b/client/asset.cpp new file mode 100644 index 00000000..da250a57 --- /dev/null +++ b/client/asset.cpp @@ -0,0 +1,80 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * Copyright (C) 2024 Patrick Nicolas + * + * 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 . + */ + +#include "asset.h" +#include "application.h" +#include +#include + +#ifdef __ANDROID__ +#include + +asset::asset(std::filesystem::path path) +{ + spdlog::debug("Loading Android asset {}", path.string()); + android_asset = AAssetManager_open(application::asset_manager(), path.c_str(), AASSET_MODE_BUFFER); + + if (!android_asset) + throw std::runtime_error("Cannot open Android asset " + path.string()); + + bytes = std::span{reinterpret_cast(AAsset_getBuffer(android_asset)), (size_t)AAsset_getLength64(android_asset)}; +} + +asset::asset(asset && other) : + android_asset(other.android_asset) +{ + other.android_asset = nullptr; +} + +asset & asset::operator=(asset && other) +{ + std::swap(android_asset, other.android_asset); + return *this; +} + +asset::~asset() +{ + if (android_asset) + AAsset_close(android_asset); +} + +#else + +asset::asset(std::filesystem::path path) +{ + // TODO mmap + // TODO: load only once if it is already loaded + + spdlog::debug("Loading file asset {}", path.string()); + + if (path.is_relative()) + path = "assets" / path; + + std::ifstream file(path, std::ios::binary | std::ios::ate); + file.exceptions(std::ios_base::badbit | std::ios_base::failbit); + + size_t size = file.tellg(); + file.seekg(0); + + bytes.resize(size); + + file.read(reinterpret_cast(bytes.data()), size); +} + +#endif diff --git a/client/asset.h b/client/asset.h new file mode 100644 index 00000000..48711d70 --- /dev/null +++ b/client/asset.h @@ -0,0 +1,77 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * Copyright (C) 2024 Patrick Nicolas + * + * 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 . + */ + +#pragma once + +#include +#include +#include +#include + +#ifdef __ANDROID__ +struct AAsset; +#endif + + +class asset +{ + +#ifdef __ANDROID__ + AAsset * android_asset = nullptr; + std::span bytes; +#else + std::vector bytes; +#endif + +public: + asset() = default; + asset(std::filesystem::path path); + +#ifdef __ANDROID__ + asset(asset && other); + asset & operator=(asset && other); + ~asset(); +#else + asset(asset && other) = default; + asset & operator=(asset && other) = default; +#endif + + asset(const asset &) = delete; + asset & operator=(const asset &) = delete; + + const std::byte * data() const + { + return bytes.data(); + } + + size_t size() const + { + return bytes.size(); + } + + operator std::span() const + { + return bytes; + } + + operator std::string() const + { + return std::string(reinterpret_cast(data()), size()); + } +}; diff --git a/client/audio/audio.h b/client/audio/audio.h index 473e3b42..3b0a0c81 100644 --- a/client/audio/audio.h +++ b/client/audio/audio.h @@ -21,7 +21,7 @@ #include "wivrn_packets.h" -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ #include "android/audio.h" using audio = ::wivrn::android::audio; #else diff --git a/client/decoder/shard_accumulator.h b/client/decoder/shard_accumulator.h index b632225b..cd3fa5fc 100644 --- a/client/decoder/shard_accumulator.h +++ b/client/decoder/shard_accumulator.h @@ -23,7 +23,7 @@ #include #include -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ #include "decoder/android/android_decoder.h" using decoder_impl = ::wivrn::android::decoder; #else diff --git a/client/hardware.cpp b/client/hardware.cpp index ebeb8d63..9caf0cab 100644 --- a/client/hardware.cpp +++ b/client/hardware.cpp @@ -24,7 +24,7 @@ #include -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ #include "utils/wrap_lambda.h" #include @@ -44,7 +44,7 @@ static std::string get_property(const char * property) model guess_model() { -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ const auto device = get_property("ro.product.device"); if (device == "monterey") return model::oculus_quest; diff --git a/client/main.cpp b/client/main.cpp index 548ab4ef..4225635c 100644 --- a/client/main.cpp +++ b/client/main.cpp @@ -27,7 +27,7 @@ #include #include -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ #include "spdlog/sinks/android_sink.h" #include #include @@ -35,7 +35,7 @@ #include "spdlog/sinks/stdout_color_sinks.h" #endif -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ void real_main(android_app * native_app) #else void real_main() @@ -44,7 +44,7 @@ void real_main() try { application_info info; -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ info.native_app = native_app; #endif info.name = "WiVRn"; @@ -117,7 +117,7 @@ void real_main() spdlog::error("Caught unknown exception"); } -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ ANativeActivity_finish(native_app->activity); // Read all pending events. @@ -136,7 +136,7 @@ void real_main() #endif } -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ void android_main(android_app * native_app) __attribute__((visibility("default"))); void android_main(android_app * native_app) { diff --git a/client/render/gpu_buffer.h b/client/render/gpu_buffer.h new file mode 100644 index 00000000..4a817911 --- /dev/null +++ b/client/render/gpu_buffer.h @@ -0,0 +1,136 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 . + */ + +#pragma once + +#include +#include +#include +#include +#include "vk/allocation.h" + +class gpu_buffer +{ + std::vector 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 + requires requires(T t) { + { + t.data() + } -> std::convertible_to; + { + t.size() + } -> std::convertible_to; + } + 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 + 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 + size_t add_vertices(const T & data_to_add) + { + usage |= vk::BufferUsageFlagBits::eVertexBuffer; + + size_t alignment = std::max(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 indices(accessor.count); + using index_t = std::remove_cvref_t; + fastgltf::copyFromAccessor(asset, accessor, indices.data()); + return add(4, indices); + } + + case fastgltf::ComponentType::Short: + case fastgltf::ComponentType::UnsignedShort: { + std::vector indices(accessor.count); + using index_t = std::remove_cvref_t; + fastgltf::copyFromAccessor(asset, accessor, indices.data()); + return add(4, indices); + } + + case fastgltf::ComponentType::Int: + case fastgltf::ComponentType::UnsignedInt: { + std::vector indices(accessor.count); + using index_t = std::remove_cvref_t; + fastgltf::copyFromAccessor(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(); + } +}; diff --git a/client/render/growable_descriptor_pool.cpp b/client/render/growable_descriptor_pool.cpp new file mode 100644 index 00000000..12afcda9 --- /dev/null +++ b/client/render/growable_descriptor_pool.cpp @@ -0,0 +1,84 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 . + */ + +#include "growable_descriptor_pool.h" + +#include + +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 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 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(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(std::move(device.allocateDescriptorSets(alloc_info)[0])); +} diff --git a/client/render/growable_descriptor_pool.h b/client/render/growable_descriptor_pool.h new file mode 100644 index 00000000..bbdd5559 --- /dev/null +++ b/client/render/growable_descriptor_pool.h @@ -0,0 +1,58 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 . + */ + +#pragma once + +#include +#include + +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 size; + int descriptorsets_per_pool; + + std::vector pools; + +public: + growable_descriptor_pool(vk::raii::Device & device, sizes size, int descriptorsets_per_pool); + + std::shared_ptr allocate(vk::DescriptorSetLayout layout); + + std::shared_ptr allocate(vk::raii::DescriptorSetLayout& layout) + { + return allocate(*layout); + } +}; diff --git a/client/render/image_loader.cpp b/client/render/image_loader.cpp new file mode 100644 index 00000000..957720f9 --- /dev/null +++ b/client/render/image_loader.cpp @@ -0,0 +1,344 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * 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 . + */ + +#include "image_loader.h" + +#include "vulkan/vulkan_enums.hpp" +#include "vulkan/vulkan_handles.hpp" +#include +#include +#include +#include +#include + +#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; + +namespace +{ +template +constexpr vk::Format formats[4] = {vk::Format::eUndefined, vk::Format::eUndefined, vk::Format::eUndefined, vk::Format::eUndefined}; + +template <> +constexpr vk::Format formats[] = { + vk::Format::eR8Unorm, + vk::Format::eR8G8Unorm, + vk::Format::eUndefined, + vk::Format::eR8G8B8A8Unorm, +}; + +template <> +constexpr vk::Format formats[] = { + vk::Format::eR16Unorm, + vk::Format::eR16G16Unorm, + vk::Format::eUndefined, + vk::Format::eR16G16B16A16Unorm, +}; + +template <> +constexpr vk::Format formats[] = { + vk::Format::eR32Sfloat, + vk::Format::eR32G32Sfloat, + vk::Format::eUndefined, + vk::Format::eR32G32B32A32Sfloat, +}; + +template +vk::Format get_format(int num_components) +{ + assert(num_components > 0 && num_components <= 4); + + return formats[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 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(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(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(num_channels); + } + + extent.width = w; + extent.height = h; + extent.depth = 1; + + do_load(device, cb, pixels.get(), extent, format); +} diff --git a/client/render/image_loader.h b/client/render/image_loader.h new file mode 100644 index 00000000..1ba88d55 --- /dev/null +++ b/client/render/image_loader.h @@ -0,0 +1,64 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * 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 . + */ + +#pragma once + +#include "vk/allocation.h" +#include +#include +#include +#include +#include +#include +#include +#include + +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 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 + image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, std::span pixels, vk::Extent3D extent, vk::Format format) : + image_loader(device, cb, pixels.data(), extent, format) + {} + + template + image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const std::array & 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); +}; diff --git a/client/render/scene_data.cpp b/client/render/scene_data.cpp new file mode 100644 index 00000000..80aa9d4c --- /dev/null +++ b/client/render/scene_data.cpp @@ -0,0 +1,953 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * 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 . + */ + +#include "render/scene_data.h" + +#include "image_loader.h" +#include "render/gpu_buffer.h" +#include "utils/fmt_glm.h" +#include "utils/ranges.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "application.h" +#include "asset.h" + +template +constexpr vk::Format vk_attribute_format = vk::Format::eUndefined; +template <> +constexpr vk::Format vk_attribute_format = vk::Format::eR32Sfloat; +template <> +constexpr vk::Format vk_attribute_format = vk::Format::eR32G32Sfloat; +template <> +constexpr vk::Format vk_attribute_format = vk::Format::eR32G32B32Sfloat; +template <> +constexpr vk::Format vk_attribute_format = vk::Format::eR32G32B32A32Sfloat; +template +constexpr vk::Format vk_attribute_format> = vk_attribute_format; + +template +constexpr size_t nb_attributes = 1; +template +constexpr size_t nb_attributes> = N; + +template +struct remove_array +{ + using type = T; +}; +template +struct remove_array> +{ + using type = T; +}; +template +using remove_array_t = remove_array::type; + +template +struct is_array : std::false_type +{ +}; + +template +struct is_array> : std::true_type +{ +}; + +template +constexpr bool is_array_v = is_array::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; \ + for (size_t i = 0; i < nb_attributes; i++) \ + { \ + attribute.offset = offsetof(vertex, member) + i * sizeof(remove_array_t); \ + desc.attributes.push_back(attribute); \ + attribute.location++; \ + if (is_array_v) \ + { \ + 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 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 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 & v) +{ + return {v[0], v[1], v[2], v[3]}; +} + +glm::vec3 convert(const std::array & v) +{ + return {v[0], v[1], v[2]}; +} +} // namespace + +template + requires is_array_v +void copy_vertex_attributes( + const fastgltf::Asset & asset, + const fastgltf::Primitive & primitive, + std::string attribute_name, + std::vector & vertices, + T scene_data::vertex::*attribute) +{ + using U = T::value_type; + constexpr size_t N = std::tuple_size_v; + + 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(asset, accessor, [&](U value, std::size_t idx) { + (vertices[idx].*attribute)[i] = value; + }); + } +} + +template + requires(!is_array_v) +void copy_vertex_attributes( + const fastgltf::Asset & asset, + const fastgltf::Primitive & primitive, + std::string attribute_name, + std::vector & 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(asset, accessor, [&](T value, std::size_t idx) { + vertices[idx].*attribute = value; + }); +} + +namespace +{ +constexpr bool starts_with(std::span data, std::span prefix) +{ + return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size()); +} + +static fastgltf::MimeType guess_mime_type(std::span 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 do_load_image( + vk::raii::Device & device, + vk::raii::CommandBuffer & cb, + fastgltf::MimeType image_type, + std::span image_data, + bool srgb) +{ + std::pair 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 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 load(const fastgltf::URI& uri) + { + auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path()); + std::span bytes; + + bytes = load_from_asset(path); + + return fastgltf::span(bytes.data(), bytes.size()); + } + + fastgltf::span load(const fastgltf::sources::URI& uri) + { + return load(uri.uri); + } + + template + fastgltf::span subspan(fastgltf::span 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{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 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 data{reinterpret_cast(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> load_all_images() + { + // Determine which image is sRGB + std::vector 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> images; + images.reserve(gltf.images.size()); + + // Create command buffers and fences + int num_images_in_flight = 3; + std::vector command_buffers = device.allocateCommandBuffers({ + .commandPool = *cb_pool, + .level = vk::CommandBufferLevel::ePrimary, + .commandBufferCount = (uint32_t)num_images_in_flight, + }); + + std::vector> 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(std::move(image))); + + vk::SubmitInfo info; + info.setCommandBuffers(*cb); + + queue.submit(info, *fence); + } + + std::vector 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> load_all_textures(std::vector> & images) + { + std::vector> textures; + textures.reserve(gltf.textures.size()); + for (const fastgltf::Texture & gltf_texture: gltf.textures) + { + auto & texture_ref = *textures.emplace_back(std::make_shared()); + + 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(buffer.data)) + { + fastgltf::sources::URI uri = std::get(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> load_all_materials(std::vector> & textures, gpu_buffer & staging_buffer, const scene_data::material & default_material) + { + std::vector> 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(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 load_all_meshes(std::vector> & materials, gpu_buffer & staging_buffer) + { + std::vector 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 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 load_all_objects() + { + std::vector 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(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 topological_sort(const std::vector & unsorted_objects) + { + std::vector sorted_objects; + std::vector new_index; + std::vector 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(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(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 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"); +} diff --git a/client/render/scene_data.h b/client/render/scene_data.h new file mode 100644 index 00000000..0937181b --- /dev/null +++ b/client/render/scene_data.h @@ -0,0 +1,260 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * 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 . + */ + +#pragma once + +#include "utils/magic_hash.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 : utils::magic_hash +{}; +} // 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_{}; + 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 base_color_texture; + std::shared_ptr metallic_roughness_texture; + std::shared_ptr occlusion_texture; + std::shared_ptr emissive_texture; + std::shared_ptr 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; + size_t offset; + + // Bindings 0-4: textures + // Binding 5: uniform buffer + std::shared_ptr 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 texcoord; + glm::vec4 color; + std::array joints; + std::array weights; + + struct description + { + vk::VertexInputBindingDescription binding; + std::vector attributes; + std::vector 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_; + }; + + struct mesh + { + std::vector primitives; + std::shared_ptr buffer; + }; + + struct scene_object + { + static constexpr size_t root_id = size_t(-1); + + size_t parent_id; + std::optional mesh_id; + + glm::vec3 translation; + glm::quat rotation; + glm::vec3 scale; + + std::string name; + bool visible; + + // std::vector bones_transform; // TODO: bones + }; + + // TODO: lights + // TODO: skybox + + std::vector meshes; + std::vector 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 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 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]; + } +}; diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index 505c4f3a..3d24b69b 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -1,806 +1,742 @@ -// #include "scene_renderer.h" -// #include "application.h" -// #include "spdlog/spdlog.h" -// #include "utils/strings.h" -// -// namespace -// { -// VkFormat gltf_to_vkformat(int component, int bits, int pixel_type, bool srgb) -// { -// switch (pixel_type) -// { -// case TINYGLTF_COMPONENT_TYPE_BYTE: -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: -// assert(bits == 8); -// break; -// -// case TINYGLTF_COMPONENT_TYPE_SHORT: -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: -// -// assert(bits == 32); -// break; -// -// case TINYGLTF_COMPONENT_TYPE_INT: -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: -// case TINYGLTF_COMPONENT_TYPE_FLOAT: -// assert(bits == 32); -// break; -// -// case TINYGLTF_COMPONENT_TYPE_DOUBLE: -// assert(bits == 64); -// default: -// break; -// } -// -// switch (component) -// { -// case 1: -// switch (pixel_type) -// { -// case TINYGLTF_COMPONENT_TYPE_BYTE: -// return VK_FORMAT_R8_SNORM; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: -// return srgb ? VK_FORMAT_R8_SRGB : VK_FORMAT_R8_UNORM; -// -// case TINYGLTF_COMPONENT_TYPE_SHORT: -// return VK_FORMAT_R16_SNORM; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: -// return VK_FORMAT_R16_UNORM; -// -// case TINYGLTF_COMPONENT_TYPE_INT: -// return VK_FORMAT_R32_SINT; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: -// return VK_FORMAT_R32_UINT; -// -// case TINYGLTF_COMPONENT_TYPE_FLOAT: -// return VK_FORMAT_R32_SFLOAT; -// -// case TINYGLTF_COMPONENT_TYPE_DOUBLE: -// return VK_FORMAT_R64_SFLOAT; -// -// default: -// return VK_FORMAT_UNDEFINED; -// } -// case 2: -// switch (pixel_type) -// { -// case TINYGLTF_COMPONENT_TYPE_BYTE: -// return VK_FORMAT_R8G8_SNORM; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: -// return srgb ? VK_FORMAT_R8G8_SRGB : VK_FORMAT_R8G8_UNORM; -// -// case TINYGLTF_COMPONENT_TYPE_SHORT: -// return VK_FORMAT_R16G16_SNORM; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: -// return VK_FORMAT_R16G16_UNORM; -// -// case TINYGLTF_COMPONENT_TYPE_INT: -// return VK_FORMAT_R32G32_SINT; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: -// return VK_FORMAT_R32G32_UINT; -// -// case TINYGLTF_COMPONENT_TYPE_FLOAT: -// return VK_FORMAT_R32G32_SFLOAT; -// -// case TINYGLTF_COMPONENT_TYPE_DOUBLE: -// return VK_FORMAT_R64G64_SFLOAT; -// -// default: -// return VK_FORMAT_UNDEFINED; -// } -// case 3: -// switch (pixel_type) -// { -// case TINYGLTF_COMPONENT_TYPE_BYTE: -// return VK_FORMAT_R8G8B8_SNORM; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: -// return srgb ? VK_FORMAT_R8G8B8_SRGB : VK_FORMAT_R8G8B8_UNORM; -// -// case TINYGLTF_COMPONENT_TYPE_SHORT: -// return VK_FORMAT_R16G16B16_SNORM; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: -// return VK_FORMAT_R16G16B16_UNORM; -// -// case TINYGLTF_COMPONENT_TYPE_INT: -// return VK_FORMAT_R32G32B32_SINT; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: -// return VK_FORMAT_R32G32B32_UINT; -// -// case TINYGLTF_COMPONENT_TYPE_FLOAT: -// return VK_FORMAT_R32G32B32_SFLOAT; -// -// case TINYGLTF_COMPONENT_TYPE_DOUBLE: -// return VK_FORMAT_R64G64B64_SFLOAT; -// -// default: -// return VK_FORMAT_UNDEFINED; -// } -// case 4: -// switch (pixel_type) -// { -// case TINYGLTF_COMPONENT_TYPE_BYTE: -// return VK_FORMAT_R8G8B8A8_SNORM; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: -// return srgb ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM; -// -// case TINYGLTF_COMPONENT_TYPE_SHORT: -// return VK_FORMAT_R16G16B16A16_SNORM; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: -// return VK_FORMAT_R16G16B16A16_UNORM; -// -// case TINYGLTF_COMPONENT_TYPE_INT: -// return VK_FORMAT_R32G32B32A32_SINT; -// -// case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: -// return VK_FORMAT_R32G32B32A32_UINT; -// -// case TINYGLTF_COMPONENT_TYPE_FLOAT: -// return VK_FORMAT_R32G32B32A32_SFLOAT; -// -// case TINYGLTF_COMPONENT_TYPE_DOUBLE: -// return VK_FORMAT_R64G64B64A64_SFLOAT; -// -// default: -// return VK_FORMAT_UNDEFINED; -// } -// default: -// return VK_FORMAT_UNDEFINED; -// } -// } -// -// int bytes_per_pixel(VkFormat format) -// { -// switch (format) -// { -// case VK_FORMAT_R8_SINT: -// case VK_FORMAT_R8_UINT: -// case VK_FORMAT_R8_SNORM: -// case VK_FORMAT_R8_UNORM: -// case VK_FORMAT_R8_SSCALED: -// case VK_FORMAT_R8_USCALED: -// case VK_FORMAT_R8_SRGB: -// return 1; -// -// case VK_FORMAT_R16_SINT: -// case VK_FORMAT_R16_UINT: -// case VK_FORMAT_R16_SNORM: -// case VK_FORMAT_R16_UNORM: -// case VK_FORMAT_R16_SSCALED: -// case VK_FORMAT_R16_USCALED: -// return 2; -// -// case VK_FORMAT_R32_SINT: -// case VK_FORMAT_R32_UINT: -// case VK_FORMAT_R32_SFLOAT: -// return 4; -// -// case VK_FORMAT_R64_SFLOAT: -// return 8; -// -// case VK_FORMAT_R8G8_SINT: -// case VK_FORMAT_R8G8_UINT: -// case VK_FORMAT_R8G8_SNORM: -// case VK_FORMAT_R8G8_UNORM: -// case VK_FORMAT_R8G8_SSCALED: -// case VK_FORMAT_R8G8_USCALED: -// case VK_FORMAT_R8G8_SRGB: -// return 2; -// -// case VK_FORMAT_R16G16_SINT: -// case VK_FORMAT_R16G16_UINT: -// case VK_FORMAT_R16G16_SNORM: -// case VK_FORMAT_R16G16_UNORM: -// case VK_FORMAT_R16G16_SSCALED: -// case VK_FORMAT_R16G16_USCALED: -// return 4; -// -// case VK_FORMAT_R32G32_SINT: -// case VK_FORMAT_R32G32_UINT: -// case VK_FORMAT_R32G32_SFLOAT: -// return 8; -// -// case VK_FORMAT_R64G64_SFLOAT: -// return 16; -// -// case VK_FORMAT_R8G8B8_SINT: -// case VK_FORMAT_R8G8B8_UINT: -// case VK_FORMAT_R8G8B8_SNORM: -// case VK_FORMAT_R8G8B8_UNORM: -// case VK_FORMAT_R8G8B8_SSCALED: -// case VK_FORMAT_R8G8B8_USCALED: -// case VK_FORMAT_R8G8B8_SRGB: -// return 3; -// -// case VK_FORMAT_R16G16B16_SINT: -// case VK_FORMAT_R16G16B16_UINT: -// case VK_FORMAT_R16G16B16_SNORM: -// case VK_FORMAT_R16G16B16_UNORM: -// case VK_FORMAT_R16G16B16_SSCALED: -// case VK_FORMAT_R16G16B16_USCALED: -// return 6; -// -// case VK_FORMAT_R32G32B32_SINT: -// case VK_FORMAT_R32G32B32_UINT: -// case VK_FORMAT_R32G32B32_SFLOAT: -// return 12; -// -// case VK_FORMAT_R64G64B64_SFLOAT: -// return 24; -// -// case VK_FORMAT_R8G8B8A8_SINT: -// case VK_FORMAT_R8G8B8A8_UINT: -// case VK_FORMAT_R8G8B8A8_SNORM: -// case VK_FORMAT_R8G8B8A8_UNORM: -// case VK_FORMAT_R8G8B8A8_SSCALED: -// case VK_FORMAT_R8G8B8A8_USCALED: -// case VK_FORMAT_R8G8B8A8_SRGB: -// return 4; -// -// case VK_FORMAT_R16G16B16A16_SINT: -// case VK_FORMAT_R16G16B16A16_UINT: -// case VK_FORMAT_R16G16B16A16_SNORM: -// case VK_FORMAT_R16G16B16A16_UNORM: -// case VK_FORMAT_R16G16B16A16_SSCALED: -// case VK_FORMAT_R16G16B16A16_USCALED: -// return 8; -// -// case VK_FORMAT_R32G32B32A32_SINT: -// case VK_FORMAT_R32G32B32A32_UINT: -// case VK_FORMAT_R32G32B32A32_SFLOAT: -// return 16; -// -// case VK_FORMAT_R64G64B64A64_SFLOAT: -// return 32; -// -// default: -// return 0; -// } -// } -// } // namespace -// -// scene_renderer::scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue) : -// device(device), physical_device(physical_device), queue(queue) -// { -// try -// { -// vkGetPhysicalDeviceProperties(physical_device, &physical_device_properties); -// -// command_pool = vk::command_pool(device, application::queue_family_index()); -// -// VkFenceCreateInfo fence_info{ -// .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, -// }; -// CHECK_VK(vkCreateFence(device, &fence_info, nullptr, &staging_fence)); -// } -// catch (...) -// { -// if (device && staging_fence) -// vkDestroyFence(device, staging_fence, nullptr); -// -// throw; -// } -// } -// -// scene_renderer::~scene_renderer() -// { -// if (device && staging_fence) -// vkDestroyFence(device, staging_fence, nullptr); -// } -// -// void scene_renderer::reserve(size_t size) -// { -// if (size > staging_buffer_size) -// { -// VkBufferCreateInfo buffer_info{}; -// buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; -// buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; -// buffer_info.size = size; -// buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; -// -// staging_buffer = vk::buffer(device, buffer_info); -// staging_memory = -// vk::device_memory(device, physical_device, staging_buffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); -// staging_buffer_size = size; -// staging_memory.map_memory(); -// } -// } -// -// void scene_renderer::load_buffer(VkBuffer b, const void * data, size_t size) -// { -// reserve(size); -// -// memcpy(staging_memory.data(), data, size); -// -// VkCommandBuffer staging_command_buffer = command_pool.allocate_command_buffer(); -// try -// { -// CHECK_VK(vkResetCommandBuffer(staging_command_buffer, 0)); -// VkCommandBufferBeginInfo begin_info{}; -// begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; -// CHECK_VK(vkBeginCommandBuffer(staging_command_buffer, &begin_info)); -// -// VkBufferCopy copy_info{.srcOffset = 0, .dstOffset = 0, .size = size}; -// vkCmdCopyBuffer(staging_command_buffer, staging_buffer, b, 1, ©_info); -// -// CHECK_VK(vkEndCommandBuffer(staging_command_buffer)); -// -// VkSubmitInfo submit_info{}; -// submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; -// submit_info.commandBufferCount = 1; -// submit_info.pCommandBuffers = &staging_command_buffer; -// CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, staging_fence)); -// -// CHECK_VK(vkWaitForFences(device, 1, &staging_fence, VK_TRUE, -1)); -// CHECK_VK(vkResetFences(device, 1, &staging_fence)); -// } -// catch (...) -// { -// command_pool.free_command_buffer(staging_command_buffer); -// throw; -// } -// -// command_pool.free_command_buffer(staging_command_buffer); -// } -// -// void scene_renderer::load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout) -// { -// reserve(size.height * size.width * bytes_per_pixel(format)); -// -// VkCommandBuffer staging_command_buffer = command_pool.allocate_command_buffer(); -// -// try -// { -// CHECK_VK(vkResetCommandBuffer(staging_command_buffer, 0)); -// VkCommandBufferBeginInfo begin_info{}; -// begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; -// CHECK_VK(vkBeginCommandBuffer(staging_command_buffer, &begin_info)); -// -// VkImageMemoryBarrier barrier{ -// .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, -// .srcAccessMask = 0, -// .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, -// .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, -// .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, -// .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, -// .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, -// .image = i, -// .subresourceRange = -// { -// .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, -// .baseMipLevel = 0, -// .levelCount = mipmap_count, -// .baseArrayLayer = 0, -// .layerCount = 1, -// }, -// }; -// vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); -// -// VkBufferImageCopy copy_info{.bufferOffset = 0, -// .bufferRowLength = 0, -// .bufferImageHeight = 0, -// .imageSubresource = -// VkImageSubresourceLayers{ -// .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, -// .mipLevel = 0, -// .baseArrayLayer = 0, -// .layerCount = 1, -// }, -// .imageOffset = {0, 0, 0}, -// .imageExtent = {size.width, size.height, 1}}; -// vkCmdCopyBufferToImage(staging_command_buffer, staging_buffer, i, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_info); -// -// VkOffset3D size_src = {(int32_t)size.width, (int32_t)size.height, 1}; -// for (uint32_t mipmap = 1; mipmap < mipmap_count; mipmap++) -// { -// barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; -// barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; -// barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; -// barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; -// barrier.subresourceRange.baseMipLevel = mipmap - 1; -// barrier.subresourceRange.levelCount = 1; -// vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); -// -// VkOffset3D size_dst = {std::max(1, size_src.x / 2), std::max(1, size_src.y / 2), 1}; -// VkImageBlit blit_info{ -// .srcSubresource = -// { -// .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, -// .mipLevel = mipmap - 1, -// .baseArrayLayer = 0, -// .layerCount = 1, -// }, -// .srcOffsets = {{0, 0, 0}, size_src}, -// .dstSubresource = -// { -// .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, -// .mipLevel = mipmap, -// .baseArrayLayer = 0, -// .layerCount = 1, -// }, -// .dstOffsets = {{0, 0, 0}, size_dst}, -// }; -// vkCmdBlitImage(staging_command_buffer, i, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, i, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit_info, VK_FILTER_LINEAR); -// -// barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; -// barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; -// barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; -// barrier.newLayout = final_layout; -// barrier.subresourceRange.baseMipLevel = mipmap - 1; -// vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); -// -// size_src = size_dst; -// } -// -// barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; -// barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; -// barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; -// barrier.newLayout = final_layout; -// barrier.subresourceRange.baseMipLevel = mipmap_count - 1; -// vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); -// -// CHECK_VK(vkEndCommandBuffer(staging_command_buffer)); -// -// VkSubmitInfo submit_info{}; -// submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; -// submit_info.commandBufferCount = 1; -// submit_info.pCommandBuffers = &staging_command_buffer; -// CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, staging_fence)); -// -// CHECK_VK(vkWaitForFences(device, 1, &staging_fence, VK_TRUE, -1)); -// CHECK_VK(vkResetFences(device, 1, &staging_fence)); -// } -// catch (...) -// { -// command_pool.free_command_buffer(staging_command_buffer); -// throw; -// } -// -// command_pool.free_command_buffer(staging_command_buffer); -// } -// -// void scene_renderer::cleanup() -// { -// shaders.clear(); -// images.clear(); -// buffers.clear(); -// -// cleanup_output_images(); -// } -// -// void scene_renderer::cleanup_output_images() -// { -// output_images.clear(); -// -// for (VkImageView image_view: output_image_views) -// vkDestroyImageView(device, image_view, nullptr); -// output_image_views.clear(); -// -// for (VkFramebuffer framebuffer: output_framebuffers) -// vkDestroyFramebuffer(device, framebuffer, nullptr); -// output_framebuffers.clear(); -// } -// -// void scene_renderer::set_output_images(std::vector output_images_, VkExtent2D output_size_, VkFormat output_format_) -// { -// output_images = std::move(output_images_); -// output_size = output_size_; -// output_format = output_format_; -// -// // Create renderpass -// VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; -// -// vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{ -// .format = output_format, -// .samples = VK_SAMPLE_COUNT_1_BIT, -// .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, -// .storeOp = VK_ATTACHMENT_STORE_OP_STORE, -// .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, -// .finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, -// }}, -// .subpasses = {VkSubpassDescription{ -// .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, -// .colorAttachmentCount = 1, -// .pColorAttachments = &color_ref, -// }}, -// .dependencies = {}}; -// -// renderpass = vk::renderpass(device, renderpass_info); -// -// // Create image views and framebuffers -// output_image_views.reserve(output_images.size()); -// output_framebuffers.reserve(output_images.size()); -// for (VkImage image: output_images) -// { -// VkImageViewCreateInfo iv_info{ -// .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, -// .image = image, -// .viewType = VK_IMAGE_VIEW_TYPE_2D, -// .format = output_format, -// .components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}, -// .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, -// .baseMipLevel = 0, -// .levelCount = 1, -// .baseArrayLayer = 0, -// .layerCount = 1}}; -// -// VkImageView image_view; -// CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view)); -// output_image_views.push_back(image_view); -// -// VkFramebufferCreateInfo fb_create_info{ -// .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, -// .renderPass = renderpass, -// .attachmentCount = 1, -// .pAttachments = &image_view, -// .width = output_size.width, -// .height = output_size.height, -// .layers = 1, -// }; -// -// VkFramebuffer framebuffer; -// CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &framebuffer)); -// output_framebuffers.push_back(framebuffer); -// } -// } -// -// void scene_renderer::cleanup_shader(shader * s) -// { -// for (auto & i: s->descriptor_set_layouts) -// vkDestroyDescriptorSetLayout(device, i, nullptr); -// for (auto & i: s->descriptor_pools) -// vkDestroyDescriptorPool(device, i, nullptr); -// for (auto & i: s->pipelines) -// vkDestroyPipeline(device, i.second, nullptr); -// -// if (s->pipeline_layout) -// vkDestroyPipelineLayout(device, s->pipeline_layout, nullptr); -// if (s->fragment_shader) -// vkDestroyShaderModule(device, s->fragment_shader, nullptr); -// if (s->vertex_shader) -// vkDestroyShaderModule(device, s->vertex_shader, nullptr); -// } -// -// std::weak_ptr -// scene_renderer::create_shader(std::string name, std::vector> uniform_bindings) -// { -// auto s = std::shared_ptr(new shader, [&](shader * s) { cleanup_shader(s); }); -// -// // Create graphics pipeline -// s->vertex_shader = vk::shader(device, name + ".vert").release(); -// s->fragment_shader = vk::shader(device, name + ".frag").release(); -// -// s->descriptor_set_layouts.reserve(uniform_bindings.size()); -// for (std::vector & bindings: uniform_bindings) -// { -// VkDescriptorSetLayoutCreateInfo layout_info{ -// .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, -// .bindingCount = (uint32_t)uniform_bindings.size(), -// .pBindings = bindings.data(), -// }; -// -// VkDescriptorSetLayout descriptor_set_layout; -// CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &descriptor_set_layout)); -// s->descriptor_set_layouts.push_back(descriptor_set_layout); -// } -// -// VkPipelineLayoutCreateInfo pipeline_layout_create_info{ -// .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, -// .setLayoutCount = (uint32_t)s->descriptor_set_layouts.size(), -// .pSetLayouts = s->descriptor_set_layouts.data(), -// }; -// -// CHECK_VK(vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &s->pipeline_layout)); -// -// return shaders.emplace_back(s); -// } -// -// VkPipeline scene_renderer::get_shader_pipeline(std::weak_ptr weak_shader, VkPrimitiveTopology topology, std::span vertex_bindings, std::span vertex_attributes) -// { -// auto shader = weak_shader.lock(); -// if (!shader) -// return VK_NULL_HANDLE; -// -// for (auto & i: shader->pipelines) -// { -// if (topology != i.first.topology) -// continue; -// -// if (vertex_bindings.size() != i.first.vertex_bindings.size()) -// continue; -// -// if (memcmp(vertex_bindings.data(), i.first.vertex_bindings.data(), vertex_bindings.size() * sizeof(VkVertexInputBindingDescription))) -// continue; -// -// if (vertex_attributes.size() != i.first.vertex_attributes.size()) -// continue; -// -// if (memcmp(vertex_attributes.data(), i.first.vertex_attributes.data(), vertex_attributes.size() * sizeof(VkVertexInputAttributeDescription))) -// continue; -// -// return i.second; -// } -// -// shader::pipeline_info info{ -// .topology = topology, -// .vertex_bindings = {vertex_bindings.begin(), vertex_bindings.end()}, -// .vertex_attributes = {vertex_attributes.begin(), vertex_attributes.end()}, -// }; -// -// VkPipelineColorBlendAttachmentState pcbas{ -// .colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT}; -// -// vk::pipeline::graphics_info pipeline_info{ -// .shader_stages = -// {{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = shader->vertex_shader, .pName = "main"}, -// {.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = shader->fragment_shader, .pName = "main"}}, -// .vertex_input_bindings = info.vertex_bindings, -// .vertex_input_attributes = info.vertex_attributes, -// .InputAssemblyState = {.topology = topology}, -// .viewports = {VkViewport{.x = 0, -// .y = 0, -// .width = (float)output_size.width, -// .height = (float)output_size.height, -// .minDepth = 0, -// .maxDepth = 1}}, -// .scissors = {VkRect2D{ -// .offset = {0, 0}, -// .extent = output_size, -// }}, -// .RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1}, -// .MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}, -// .ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas}, -// .dynamic_states = {}, -// .renderPass = renderpass, -// .subpass = 0, -// }; -// -// vk::pipeline pipeline(device, pipeline_info, shader->pipeline_layout); -// -// return shader->pipelines.emplace_back(info, pipeline.release()).second; -// } -// -// void scene_renderer::cleanup_image(scene_renderer::image * i) -// { -// if (i->image_view) -// vkDestroyImageView(device, i->image_view, nullptr); -// -// if (i->vk_image) -// vkDestroyImage(device, i->vk_image, nullptr); -// -// if (i->memory) -// vkFreeMemory(device, i->memory, nullptr); -// } -// -// std::weak_ptr scene_renderer::create_image(void * data, VkExtent2D size, VkFormat format) -// { -// auto i = std::shared_ptr(new image, [&](image * i) { cleanup_image(i); }); -// -// uint32_t mipmaps = std::log2(std::max(size.width, size.height)) + 1; -// -// VkImageCreateInfo image_info{ -// .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, -// .flags = 0, -// .imageType = VK_IMAGE_TYPE_2D, -// .format = format, -// .extent = {size.width, size.height, 1}, -// .mipLevels = mipmaps, -// .arrayLayers = 1, -// .samples = VK_SAMPLE_COUNT_1_BIT, -// .tiling = VK_IMAGE_TILING_OPTIMAL, -// .usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, -// .sharingMode = VK_SHARING_MODE_EXCLUSIVE, -// .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, -// }; -// -// i->vk_image = vk::image(device, image_info).release(); -// i->memory = -// vk::device_memory(device, physical_device, i->vk_image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release(); -// -// load_image(i->vk_image, data, size, format, mipmaps); -// -// VkImageViewCreateInfo image_view_info{ -// .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, -// .flags = 0, -// .image = i->vk_image, -// .viewType = VK_IMAGE_VIEW_TYPE_2D, -// .format = format, -// .components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}, -// .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, -// .baseMipLevel = 0, -// .levelCount = mipmaps, -// .baseArrayLayer = 0, -// .layerCount = 1}}; -// CHECK_VK(vkCreateImageView(device, &image_view_info, nullptr, &i->image_view)); -// -// return images.emplace_back(i); -// } -// -// void scene_renderer::cleanup_buffer(scene_renderer::buffer * b) -// { -// if (b->vk_buffer) -// vkDestroyBuffer(device, b->vk_buffer, nullptr); -// if (b->memory) -// vkFreeMemory(device, b->memory, nullptr); -// } -// -// std::weak_ptr scene_renderer::create_buffer(const void * data, size_t size, VkBufferUsageFlags usage) -// { -// auto b = std::shared_ptr(new buffer, [&](buffer * b) { cleanup_buffer(b); }); -// -// VkBufferCreateInfo buffer_info{ -// .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, -// .size = size, -// .usage = usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT, -// .sharingMode = VK_SHARING_MODE_EXCLUSIVE, -// }; -// -// b->vk_buffer = vk::buffer(device, buffer_info).release(); -// b->memory = -// vk::device_memory(device, physical_device, b->vk_buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release(); -// -// load_buffer(b->vk_buffer, data, size); -// -// return buffers.emplace_back(b); -// } -// -// scene_renderer::model * scene_renderer::load_gltf(const std::string & filename) -// { -// std::string err, warn; -// -// auto m = std::make_unique(); -// -// bool success = false; -// -// if (filename.ends_with(".glb")) -// success = gltf_loader.LoadBinaryFromFile(&m->gltf_model, &err, &warn, filename); -// else if (filename.ends_with(".gltf")) -// success = gltf_loader.LoadASCIIFromFile(&m->gltf_model, &err, &warn, filename); -// else -// err = "Wrong file extension, must be .gltf or .glb"; -// -// if (warn != "") -// spdlog::warn("Loading {}: {}", filename, utils::trim(warn)); -// -// if (err != "") -// spdlog::error("Loading {}: {}", filename, utils::trim(err)); -// -// if (!success) -// throw std::runtime_error("GLTF error: " + utils::trim(err)); -// -// for (tinygltf::Buffer & i: m->gltf_model.buffers) -// { -// m->buffers.push_back( -// create_buffer(i.data, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT)); -// } -// -// std::vector srgb(m->gltf_model.images.size(), false); -// for (tinygltf::Material & i: m->gltf_model.materials) -// { -// if (i.emissiveTexture.index >= 0 && i.emissiveTexture.index < (int)srgb.size()) -// srgb[i.emissiveTexture.index] = true; -// -// if (i.pbrMetallicRoughness.baseColorTexture.index >= 0 && -// i.pbrMetallicRoughness.baseColorTexture.index < (int)srgb.size()) -// srgb[i.pbrMetallicRoughness.baseColorTexture.index] = true; -// } -// -// int n = 0; -// for (tinygltf::Image & i: m->gltf_model.images) -// { -// VkFormat format = gltf_to_vkformat(i.component, i.bits, i.pixel_type, srgb[n++]); -// m->images.push_back(create_image(i.image.data(), {(uint32_t)i.width, (uint32_t)i.height}, format)); -// } -// -// return models.emplace_back(std::move(m)).get(); -// } +/* + * WiVRn VR streaming + * Copyright (C) 2023-2024 Guillaume Meunier + * + * 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 . + */ + +#include "render/scene_renderer.h" + +#include "render/growable_descriptor_pool.h" +#include "render/image_loader.h" +#include "render/scene_data.h" +#include "utils/alignment.h" +#include "utils/ranges.h" +#include "vk/allocation.h" +#include "vk/pipeline.h" +#include "vk/shader.h" +#include +#include +#include +#include +#include +#include +#include +#include + +extern const std::map> shaders; + +static vk::Format find_usable_image_format( + vk::raii::PhysicalDevice physical_device, + std::span formats, + vk::Extent3D min_extent, + vk::ImageUsageFlags usage, + vk::ImageType type = vk::ImageType::e2D, + vk::ImageTiling tiling = vk::ImageTiling::eOptimal, + vk::ImageCreateFlags flags = {}) +{ + for (vk::Format format: formats) + { + try + { + vk::ImageFormatProperties prop = physical_device.getImageFormatProperties(format, type, tiling, usage, flags); + + if (prop.maxExtent.width < min_extent.width) + continue; + if (prop.maxExtent.height < min_extent.height) + continue; + if (prop.maxExtent.depth < min_extent.depth) + continue; + + return format; + } + catch (vk::FormatNotSupportedError &) + { + continue; + } + } + + return vk::Format::eUndefined; +} + +std::shared_ptr scene_renderer::create_default_texture(vk::raii::CommandBuffer & cb, std::vector& staging_buffers, std::initializer_list pixel) +{ + vk::Format format; + + switch (pixel.size()) + { + case 1: + format = vk::Format::eR32Sfloat; + break; + case 2: + format = vk::Format::eR32G32Sfloat; + break; + case 4: + format = vk::Format::eR32G32B32A32Sfloat; + break; + default: + assert(false); + __builtin_unreachable(); + } + + std::array pixel2; + std::copy(pixel.begin(), pixel.end(), pixel2.begin()); + + image_loader loader(device, cb, pixel2, vk::Extent3D{1, 1, 1}, format); + + auto base_color_image = std::make_shared(std::move(loader.image), std::move(loader.image_view)); + + staging_buffers.push_back(std::move(loader.staging_buffer)); + return std::make_shared(base_color_image, sampler_info{}); +} + +std::shared_ptr scene_renderer::create_default_material(vk::raii::CommandPool & cb_pool) +{ + auto default_material = std::make_shared(); + + auto cb = std::move(device.allocateCommandBuffers(vk::CommandBufferAllocateInfo{ + .commandPool = *cb_pool, + .level = vk::CommandBufferLevel::ePrimary, + .commandBufferCount = 1, + })[0]); + + auto fence = device.createFence(vk::FenceCreateInfo{}); + + cb.begin(vk::CommandBufferBeginInfo{.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); + + std::vector staging_buffers; + default_material->base_color_texture = create_default_texture(cb, staging_buffers, {1, 1, 1, 1}); + default_material->metallic_roughness_texture = create_default_texture(cb, staging_buffers, {1, 1}); + default_material->occlusion_texture = create_default_texture(cb, staging_buffers, {1}); + default_material->emissive_texture = create_default_texture(cb, staging_buffers, {0, 0, 0, 0}); + default_material->normal_texture = create_default_texture(cb, staging_buffers, {0.5, 0.5, 1, 1}); + + cb.end(); + + vk::SubmitInfo info; + info.setCommandBuffers(*cb); + + queue.submit(info, *fence); + + device.waitForFences(*fence, true, 1'000'000'000); // TODO check for timeout + + return default_material; +} + +vk::FrontFace reverse(vk::FrontFace face) +{ + if (face == vk::FrontFace::eCounterClockwise) + return vk::FrontFace::eClockwise; + else + return vk::FrontFace::eCounterClockwise; +} + +scene_renderer::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 depth_formats, int frames_in_flight) : + device(device), + physical_device_properties(physical_device.getProperties()), + queue(queue), + output_size(output_size), + output_format(output_format), + depth_format(find_usable_image_format(physical_device, depth_formats, {output_size.width, output_size.height, 1}, vk::ImageUsageFlagBits::eDepthStencilAttachment)), + ds_pool_frame(device, { + .uniform_buffer = frames_in_flight, + .uniform_buffer_dynamic = frames_in_flight, + }, + frames_in_flight), + ds_pool_material(device, {.combined_image_sampler = 500, .uniform_buffer = 100}, 100) +{ + // Create the default material + default_material = create_default_material(cb_pool); + + // Create Vulkan resources + frame_resources.resize(frames_in_flight); + + std::vector command_buffers = device.allocateCommandBuffers({ + .commandPool = *cb_pool, + .level = vk::CommandBufferLevel::ePrimary, + .commandBufferCount = (uint32_t)frame_resources.size(), + }); + + for (auto && [res, cb]: utils::zip(frame_resources, command_buffers)) + { + res.fence = device.createFence({.flags = vk::FenceCreateFlagBits::eSignaled}); + res.cb = std::move(cb); + } + + renderpass = create_renderpass(); + + // Create the descriptor set layouts + std::array layout_bindings_0{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eUniformBufferDynamic, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}}; + vk::DescriptorSetLayoutCreateInfo dsl0_info{}; + dsl0_info.setBindings(layout_bindings_0); + descriptor_set_frame = vk::raii::DescriptorSetLayout{device, dsl0_info}; + + std::array layout_bindings_1{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 5, + .stageFlags = vk::ShaderStageFlagBits::eFragment}, + vk::DescriptorSetLayoutBinding{ + .binding = 5, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eFragment}}; + vk::DescriptorSetLayoutCreateInfo dsl1_info{}; + dsl1_info.setBindings(layout_bindings_1); + descriptor_set_material = vk::raii::DescriptorSetLayout{device, dsl1_info}; + + std::array layouts{*descriptor_set_frame, *descriptor_set_material}; + pipeline_layout = create_pipeline_layout(layouts); + +} + +scene_renderer::~scene_renderer() +{ + std::vector fences; + for (auto & i: frame_resources) + fences.push_back(*i.fence); + + device.waitForFences(fences, true, 1'000'000'000); // TODO check for timeout +} + +vk::raii::RenderPass scene_renderer::create_renderpass() +{ + vk::RenderPassCreateInfo info; + + std::array attachments = { + vk::AttachmentDescription{ + .format = output_format, + .samples = vk::SampleCountFlagBits::e1, + .loadOp = vk::AttachmentLoadOp::eClear, + .storeOp = vk::AttachmentStoreOp::eStore, + .initialLayout = vk::ImageLayout::eUndefined, + .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, + }, + vk::AttachmentDescription{ + .format = depth_format, + .samples = vk::SampleCountFlagBits::e1, + .loadOp = vk::AttachmentLoadOp::eClear, + .storeOp = vk::AttachmentStoreOp::eDontCare, + .stencilLoadOp = vk::AttachmentLoadOp::eClear, + .stencilStoreOp = vk::AttachmentStoreOp::eDontCare, + .initialLayout = vk::ImageLayout::eUndefined, + .finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal, + + }}; + info.setAttachments(attachments); + + vk::AttachmentReference color_attachment{ + .attachment = 0, + .layout = vk::ImageLayout::eColorAttachmentOptimal, + }; + + vk::AttachmentReference depth_attachment{ + .attachment = 1, + .layout = vk::ImageLayout::eDepthStencilAttachmentOptimal, + }; + + vk::SubpassDescription subpasses{ + .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, + .pDepthStencilAttachment = &depth_attachment, + }; + subpasses.setColorAttachments(color_attachment); + info.setSubpasses(subpasses); + + std::array dependencies{ + vk::SubpassDependency{ + .srcSubpass = vk::SubpassExternal, + .dstSubpass = 0, + .srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput, + .dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput, + .srcAccessMask{}, + .dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite, + }, + vk::SubpassDependency{ + .srcSubpass = vk::SubpassExternal, + .dstSubpass = 0, + .srcStageMask = vk::PipelineStageFlagBits::eEarlyFragmentTests, + .dstStageMask = vk::PipelineStageFlagBits::eEarlyFragmentTests, + .srcAccessMask{}, + .dstAccessMask = vk::AccessFlagBits::eDepthStencilAttachmentWrite, + }}; + info.setDependencies(dependencies); + + return vk::raii::RenderPass(device, info); +} + +scene_renderer::output_image & scene_renderer::get_output_image_data(vk::Image output) +{ + auto it = output_images.find(output); + if (it != output_images.end()) + return it->second; + + return output_images.emplace(output, create_output_image_data(output)).first->second; +} + +scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image output) +{ + output_image out; + + // TODO: use image view from xr::swapchain + out.image_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ + .image = output, + .viewType = vk::ImageViewType::e2D, + .format = output_format, + .components{}, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, + }); + + out.depth_buffer = image_allocation{vk::ImageCreateInfo{ + .imageType = vk::ImageType::e2D, + .format = depth_format, + .extent = { + .width = output_size.width, + .height = output_size.height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .samples = vk::SampleCountFlagBits::e1, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eDepthStencilAttachment + + }, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check + }}; + + out.depth_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ + .image = out.depth_buffer, + .viewType = vk::ImageViewType::e2D, + .format = depth_format, + .components{}, + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eDepth, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, + }); + + vk::FramebufferCreateInfo fb_info{ + .renderPass = *renderpass, + .width = output_size.width, + .height = output_size.height, + .layers = 1, + }; + + std::array attachments{ + vk::ImageView{*out.image_view}, + vk::ImageView{*out.depth_view}}; + fb_info.setAttachments(attachments); + out.framebuffer = vk::raii::Framebuffer(device, fb_info); + + return out; +} + +vk::raii::Pipeline & scene_renderer::get_pipeline(const pipeline_info & info) +{ + auto it = pipelines.find(info); + if (it != pipelines.end()) + return it->second; + + return pipelines.emplace(info, create_pipeline(info)).first->second; +} + +vk::raii::PipelineLayout scene_renderer::create_pipeline_layout(std::span layouts) +{ + vk::PipelineLayoutCreateInfo pipeline_layout_info; + pipeline_layout_info.setSetLayouts(layouts); + + return vk::raii::PipelineLayout{device, pipeline_layout_info}; +} + +vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) +{ + auto vertex_description = scene_data::vertex::describe(); + + spdlog::debug("Creating pipeline"); + + auto vertex_shader = load_shader(device, info.shader_name + ".vert"); + auto fragment_shader = load_shader(device, info.shader_name + ".frag"); + + return vk::raii::Pipeline{device, nullptr, vk::pipeline_builder{ + .Stages{ + vk::PipelineShaderStageCreateInfo{.stage = vk::ShaderStageFlagBits::eVertex, .module = *vertex_shader, .pName = "main"}, + vk::PipelineShaderStageCreateInfo{.stage = vk::ShaderStageFlagBits::eFragment, .module = *fragment_shader, .pName = "main"}, + }, + .VertexBindingDescriptions = {vertex_description.binding}, + .VertexAttributeDescriptions = vertex_description.attributes, + .InputAssemblyState = {{ + .topology = info.topology, + .primitiveRestartEnable = false, + }}, + .Viewports = {vk::Viewport{ + .x = 0, + .y = 0, + .width = (float)output_size.width, + .height = (float)output_size.height, + .minDepth = 0, + .maxDepth = 1, + }}, + .Scissors = {vk::Rect2D{ + .offset = {0, 0}, + .extent = output_size, + }}, + .RasterizationState = {vk::PipelineRasterizationStateCreateInfo{ + .polygonMode = vk::PolygonMode::eFill, + .cullMode = info.cull_mode, + .frontFace = info.front_face, + .lineWidth = 1.0, + }}, + .MultisampleState = {vk::PipelineMultisampleStateCreateInfo{ + .rasterizationSamples = vk::SampleCountFlagBits::e1, + }}, + .DepthStencilState = {vk::PipelineDepthStencilStateCreateInfo{ + .depthTestEnable = true, + .depthWriteEnable = true, + .depthCompareOp = vk::CompareOp::eLess, + .depthBoundsTestEnable = false, + .minDepthBounds = 0.0f, + .maxDepthBounds = 1.0f, + }}, + .ColorBlendState = {vk::PipelineColorBlendStateCreateInfo{}}, + .ColorBlendAttachments = {vk::PipelineColorBlendAttachmentState{ + .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB}}, + .DynamicState = {}, + .layout = *pipeline_layout, + .renderPass = *renderpass, + .subpass = 0, + }}; +} + +vk::Sampler scene_renderer::get_sampler(const sampler_info & info) +{ + auto it = samplers.find(info); + if (it != samplers.end()) + return **it->second; + + auto out = std::make_shared(device, vk::SamplerCreateInfo{ + .magFilter = info.mag_filter, + .minFilter = info.min_filter, + .mipmapMode = info.min_filter_mipmap, + .addressModeU = info.wrapS, + .addressModeV = info.wrapT, + }); + + samplers.emplace(info, out); + return **out; +} + +scene_renderer::per_frame_resources & scene_renderer::start_frame() +{ + current_frame = (current_frame + 1) % frame_resources.size(); + + device.waitForFences(*frame_resources[current_frame].fence, true, 1'000'000'000); + device.resetFences(*frame_resources[current_frame].fence); + + frame_resources[current_frame].resources.clear(); + frame_resources[current_frame].cb.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); + // frame_resources[current_frame]. + + return frame_resources[current_frame]; +} + +void scene_renderer::update_material_descriptor_set(scene_data::material& material) +{ + if (!material.ds || !material.ds.unique()) + material.ds = ds_pool_material.allocate(descriptor_set_material); + + vk::DescriptorSet ds = **material.ds; + + auto f = [&](std::shared_ptr& texture){ + return vk::DescriptorImageInfo{ + .sampler = get_sampler(texture->sampler), + .imageView = *texture->image_->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(scene_data::material::gpu_data) + }; + + std::array write_ds{ + vk::WriteDescriptorSet{ + .dstSet = ds, + .dstBinding = 0, + .descriptorCount = (uint32_t)write_ds_image.size(), + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = write_ds_image.data() + }, + 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, {}); +} + +void scene_renderer::render(scene_data & scene, std::span frames) +{ + size_t ubo_alignment = physical_device_properties.limits.minUniformBufferOffsetAlignment; + + size_t ubo_frame_size = utils::align_up(ubo_alignment, sizeof(frame_gpu_data)); + size_t ubo_instance_size = utils::align_up(ubo_alignment, sizeof(instance_gpu_data)); + + size_t nb_frames = frames.size(); + //size_t nb_objects = scene.scene_objects.size(); + size_t nb_objects = std::count_if(scene.scene_objects.begin(), scene.scene_objects.end(), [](const scene_data::scene_object& object){ + return object.mesh_id; + }); + + // Enough room for one frame_gpu_data per view and one instance_gpu_data per instance and per view + size_t ubo_size = nb_frames * (ubo_frame_size + nb_objects * ubo_instance_size); + + // Compute the position of each ubo, taking in account the minimum alignment + ptrdiff_t offset = 0; + std::vector ubo_frame_offset(nb_frames); + for(size_t i = 0; i < nb_frames; i++) + { + ubo_frame_offset[i] = offset; + offset += ubo_frame_size; + } + + std::vector ubo_object_offset(nb_frames * nb_objects); + for(size_t i = 0; i < nb_frames; i++) + { + for(size_t j = 0; j < nb_objects; j++) + { + ubo_object_offset[i * nb_objects + j] = offset; + offset += ubo_frame_size; + } + } + + auto current_ubo_frame_offset = ubo_frame_offset.begin(); + auto current_ubo_object_offset = ubo_object_offset.begin(); + + per_frame_resources & resources = start_frame(); + vk::raii::CommandBuffer & cb = resources.cb; + + if (!resources.staging_buffer || resources.staging_buffer.info().size < ubo_size) + { + resources.staging_buffer = buffer_allocation{vk::BufferCreateInfo{ + .size = ubo_size, + .usage = vk::BufferUsageFlagBits::eUniformBuffer}, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, + .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}}; + } + + // if (!resources.uniform_buffer || resources.uniform_buffer.info().size < ubo_size) + // { + // resources.staging_buffer = buffer_allocation{vk::BufferCreateInfo{ + // .size = ubo_size, + // .usage = vk::BufferUsageFlagBits::eUniformBuffer}, + // VmaAllocationCreateInfo{ + // .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, + // .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}}; + // } + + uintptr_t ubo = reinterpret_cast(resources.staging_buffer.map()); + + std::array clear_values{ + vk::ClearColorValue(0.0f, 0.0f, 0.0f, 0.0f), + vk::ClearDepthStencilValue{1.0, 0}, + }; + + // cb.copyBuffer(resources.staging_buffer, resources.uniform_buffer, {}); + + auto vertex_layout = scene_data::vertex::describe(); + + std::vector transform_to_root(scene.scene_objects.size()); + std::vector reverse_side(scene.scene_objects.size()); + std::vector visible(scene.scene_objects.size()); + + for(const auto& [index, object]: utils::enumerate(scene.scene_objects)) + { + glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), object.translation) * (glm::mat4)object.rotation * glm::scale(glm::mat4(1), object.scale); + float det = object.scale.x * object.scale.y * object.scale.z; + + if (object.parent_id == scene_data::scene_object::root_id) + { + transform_to_root[index] = transform_to_parent; + reverse_side[index] = det < 0; + visible[index] = object.visible; + } + else + { + size_t parent = object.parent_id; + assert(parent < index); + + transform_to_root[index] = transform_to_root.at(parent) * transform_to_parent; + + reverse_side[index] = reverse_side[parent] ^ (det < 0); + + visible[index] = visible[parent] && object.visible; + } + } + + for (const auto && [frame_index, frame]: utils::enumerate(frames)) + { + scene_renderer::output_image & output = get_output_image_data(frame.destination); + glm::mat4 viewproj = frame.projection * frame.view; + + frame_gpu_data& frame_ubo = *reinterpret_cast(ubo + *current_ubo_frame_offset); + + frame_ubo.ambient_color = glm::vec4(0,0,0,0); // TODO + frame_ubo.light_color = glm::vec4(0,0,0,0); // TODO + frame_ubo.light_position = glm::vec4(0,0,0,0); // TODO + frame_ubo.proj = frame.projection; + frame_ubo.view = frame.view; + + cb.beginRenderPass(vk::RenderPassBeginInfo{ + .renderPass = *renderpass, + .framebuffer = *output.framebuffer, + .renderArea = { + .offset = {0, 0}, + .extent = output_size, + }, + .clearValueCount = clear_values.size(), + .pClearValues = clear_values.data(), + }, + vk::SubpassContents::eInline); + + auto ds = ds_pool_frame.allocate(descriptor_set_frame); + vk::DescriptorBufferInfo buffer_info_1{ + .buffer = resources.staging_buffer, + .offset = (vk::DeviceSize)*current_ubo_frame_offset, + .range = sizeof(frame_gpu_data) + };; + vk::DescriptorBufferInfo buffer_info_2{ + .buffer = resources.staging_buffer, + .offset = 0, + .range = sizeof(instance_gpu_data) + }; + device.updateDescriptorSets(std::array{ + vk::WriteDescriptorSet{ + .dstSet = **ds, + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info_1, + }, + vk::WriteDescriptorSet{ + .dstSet = **ds, + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBufferDynamic, + .pBufferInfo = &buffer_info_2, + }, + }, {}); + resources.resources.push_back(ds); + + for(const auto& [index, object]: utils::enumerate(scene.scene_objects)) + { + if (!object.mesh_id) + continue; + + scene_data::mesh& mesh = scene.meshes.at(*object.mesh_id); + + instance_gpu_data& object_ubo = *reinterpret_cast(ubo + *current_ubo_object_offset); + + glm::mat4& transform = transform_to_root[index]; + object_ubo.model = transform; + object_ubo.modelview = frame.view * transform; + object_ubo.modelviewproj = viewproj * transform; + + for(scene_data::primitive& primitive: mesh.primitives) + { + // Get the material + std::shared_ptr material = primitive.material_ ? primitive.material_ : default_material; + + if (material->ds_dirty || !material->ds) + update_material_descriptor_set(*material); + + // Get the pipeline + pipeline_info info{ + .shader_name = "lit", + .cull_mode = primitive.cull_mode, + .front_face = primitive.front_face, + .topology = primitive.topology + }; + + if (material->double_sided) + info.cull_mode = vk::CullModeFlagBits::eNone; + + if (reverse_side[index]) + info.front_face = reverse(info.front_face); + + cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info)); + + if (primitive.indexed) + cb.bindIndexBuffer(*mesh.buffer, primitive.index_offset, primitive.index_type); + + cb.bindVertexBuffers(0, (vk::Buffer)*mesh.buffer, primitive.vertex_offset); + + std::array descriptor_sets{ + **ds, // Set 0: per view and per object instance UBOs + **material->ds // Set 1: material + }; + + std::array dynamic_offsets{ + (uint32_t)*current_ubo_object_offset // Offset of the object data + }; + + cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptor_sets, dynamic_offsets); + + if (primitive.indexed) + cb.drawIndexed(primitive.index_count, 1, 0, 0, 0); + else + cb.draw(primitive.vertex_count, 1, 0, 0); + + resources.resources.push_back(material->ds); + } + + current_ubo_object_offset++; + } + cb.endRenderPass(); + + current_ubo_frame_offset++; + } + + cb.end(); + + queue.submit(vk::SubmitInfo{ + .commandBufferCount = 1, + .pCommandBuffers = &*cb, + }, *frame_resources[current_frame].fence); + +} diff --git a/client/render/scene_renderer.h b/client/render/scene_renderer.h index d8795bfd..31d5327f 100644 --- a/client/render/scene_renderer.h +++ b/client/render/scene_renderer.h @@ -1,187 +1,184 @@ -// #pragma once -// -// #include -// #include -// #include -// #include -// -// #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 descriptor_set_layouts; -// std::vector descriptor_pools; -// VkShaderModule vertex_shader{}; -// VkShaderModule fragment_shader{}; -// VkPipelineLayout pipeline_layout{}; -// -// struct pipeline_info -// { -// VkPrimitiveTopology topology; -// std::vector vertex_bindings; -// std::vector vertex_attributes; -// }; -// -// std::vector> 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 indices; -// size_t indices_offset; -// size_t indices_count; -// -// std::weak_ptr vertices; -// size_t vertices_offset; -// }; -// -// class model -// { -// friend class scene_renderer; -// -// tinygltf::Model gltf_model; -// std::vector> images; -// std::vector> 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 -// void load_buffer(VkBuffer b, std::span 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> shaders; -// std::vector> images; -// std::vector> buffers; -// std::vector> primitives; -// std::vector> models; -// std::vector instances; -// -// // Destination images -// std::vector output_images; -// std::vector output_image_views; -// std::vector 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 output_images, VkExtent2D output_size, VkFormat output_format); -// -// std::weak_ptr create_shader(std::string name, -// std::vector> uniform_bindings); -// -// VkPipeline get_shader_pipeline(std::weak_ptr shader, VkPrimitiveTopology topology, std::span vertex_bindings, std::span vertex_attributes); -// -// std::weak_ptr create_image(void * data, VkExtent2D size, VkFormat format); -// -// std::weak_ptr create_buffer(const void * data, size_t size, VkBufferUsageFlags usage); -// -// template -// // requires(std::contiguous_iterator) -// std::weak_ptr 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 + * + * 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 . + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 : utils::magic_hash +{}; +} // 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 layouts); + vk::raii::Pipeline create_pipeline(const pipeline_info & info); + + std::shared_ptr create_default_texture(vk::raii::CommandBuffer & cb, std::vector& staging_buffers, std::initializer_list pixel); + std::shared_ptr create_default_material(vk::raii::CommandPool & cb_pool); + + // Caches + std::unordered_map output_images; + std::unordered_map 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> 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 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> 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 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 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 info); + + std::shared_ptr get_default_material() + { + return default_material; + } +}; diff --git a/client/render/text_rasterizer.cpp b/client/render/text_rasterizer.cpp index d87d2b60..23ecf224 100644 --- a/client/render/text_rasterizer.cpp +++ b/client/render/text_rasterizer.cpp @@ -34,7 +34,7 @@ #include #include -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ #include #include #include @@ -74,8 +74,7 @@ std::error_category & freetype_error_category() // static hb_feature_t CligOn = { CligTag, 1, 0, std::numeric_limits::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(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(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; diff --git a/client/render/text_rasterizer.h b/client/render/text_rasterizer.h index 142e2cc0..d52947e1 100644 --- a/client/render/text_rasterizer.h +++ b/client/render/text_rasterizer.h @@ -1,7 +1,6 @@ /* * WiVRn VR streaming * Copyright (C) 2022-2024 Guillaume Meunier - * Copyright (C) 2022-2023 Patrick Nicolas * * 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 +#include "vk/allocation.h" #include #include #include #include #include -#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); diff --git a/client/scenes/input_profile.cpp b/client/scenes/input_profile.cpp new file mode 100644 index 00000000..b6af12ea --- /dev/null +++ b/client/scenes/input_profile.cpp @@ -0,0 +1,407 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 . + */ + +#include "input_profile.h" + +#include "application.h" +#include "asset.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +// clang-format off +const std::unordered_map input_mappings = { + {"xr-standard-squeeze" , "/input/squeeze/value" }, + {"xr-standard-trigger" , "/input/trigger/value" }, + {"xr-standard-touchpad" , "/input/trackpad" }, + {"xr-standard-thumbstick", "/input/thumbstick" }, + {"a-button" , "/input/a/click" }, + {"b-button" , "/input/b/click" }, + {"x-button" , "/input/x/click" }, + {"y-button" , "/input/y/click" }, + {"thumbrest" , "/input/thumbrest/touch" }, +}; +// clang-format on + +enum class component_type +{ + trigger, + squeeze, + button, + thumbstick, + touchpad +}; + +component_type parse_component_type(std::string_view type) +{ + if (type == "trigger") + return component_type::trigger; + + if (type == "squeeze") + return component_type::squeeze; + + if (type == "button") + return component_type::button; + + if (type == "thumbstick") + return component_type::thumbstick; + + if (type == "touchpad") + return component_type::touchpad; + + throw std::runtime_error("Invalid type: " + std::string(type)); +} + +enum class component_property +{ + x_axis, + y_axis, + button, + state, // ??? +}; + +component_property parse_component_property(std::string_view property) +{ + if (property == "xAxis") + return component_property::x_axis; + + if (property == "yAxis") + return component_property::y_axis; + + if (property == "button") + return component_property::button; + + if (property == "state") + return component_property::state; + + throw std::runtime_error("Invalid property: " + std::string(property)); +} + +enum class value_node_property +{ + transform, + visibility +}; + +value_node_property parse_value_node_property(std::string_view property) +{ + if (property == "transform") + return value_node_property::transform; + + if (property == "visibility") + return value_node_property::visibility; + + throw std::runtime_error("Invalid property: " + std::string(property)); +} + +struct json_visual_response +{ + // From the WebXR profile + std::string layout; + std::string component_id; + component_type type; + component_property property; + std::string target_node; + input_profile::node_state state; + + // OpenXR component path + std::string component_subpath; +}; +} // namespace + +input_profile::input_profile(const std::filesystem::path & json_profile, scene_loader & loader, scene_data & scene) +{ + std::string json = asset(json_profile); + + simdjson::dom::parser parser; + simdjson::dom::element root = parser.parse(json); + + id = std::string(root["profileId"]); + + // Don't load them into the scene right now in case there is an exception + std::vector> models; + std::vector json_responses; + + for (simdjson::dom::key_value_pair layout: simdjson::dom::object(root["layouts"])) + { + // TODO handle case where i.key is none and there is no left or right + // std::string user_path = "/user/hand/" + std::string(layout.key); + std::filesystem::path asset_path = json_profile.parent_path() / std::string(layout.value["assetPath"]); + + scene_data & data = models.emplace_back(layout.key, loader(asset_path)).second; + + for (simdjson::dom::key_value_pair component: simdjson::dom::object(layout.value["components"])) + { + auto it = input_mappings.find(std::string(component.key)); + if (it == input_mappings.end()) + { + spdlog::debug("Unknown component: {}", component.key); + continue; + } + + std::string component_subpath = it->second; + component_type type = parse_component_type(component.value["type"]); + + for (simdjson::dom::key_value_pair response: simdjson::dom::object(component.value["visualResponses"])) + { + json_visual_response & vr = json_responses.emplace_back(); + + vr.layout = layout.key; + vr.component_id = component.key; + vr.type = type; + vr.property = parse_component_property(response.value["componentProperty"]); + vr.target_node = std::string(response.value["valueNodeName"]); + vr.component_subpath = component_subpath; + + // Check if the node exists + data.find_node(vr.target_node); + + auto node_property = parse_value_node_property(response.value["valueNodeProperty"]); + switch (node_property) + { + case value_node_property::transform: { + auto min_node = data.find_node(response.value["minNodeName"]); + auto max_node = data.find_node(response.value["maxNodeName"]); + + node_state_transform min{ + min_node->translation, + min_node->rotation}; + + node_state_transform max{ + max_node->translation, + max_node->rotation}; + + vr.state = std::make_pair(min, max); + } + break; + + case value_node_property::visibility: + vr.state = node_state_visibility{}; + break; + } + } + } + } + + for(auto&& [layout, model]: models) + { + scene_object_handle root_node = scene.new_node(); + root_node->name = layout; + + XrSpace space; + if (layout == "left") + space = application::left_grip(); + else if (layout == "right") + space = application::right_grip(); + else + continue; + + model_handles.emplace_back(space, root_node); + + scene.import(std::move(model), root_node); + } + + for(auto& json_response: json_responses) + { + std::string action_path = "/user/hand/" + json_response.layout + json_response.component_subpath; + + if (json_response.type == component_type::thumbstick && json_response.property == component_property::button) + action_path += "/click"; + + auto action = application::get_action(action_path); + if (action.first == XR_NULL_PATH) + { + spdlog::debug("No input for {}/{} ({})", json_response.layout, json_response.component_id, action_path); + continue; + } + + auto& response = responses.emplace_back(); + response.action = action.first; + response.type = action.second; + + switch(json_response.property) + { + case component_property::button: + case component_property::state: + response.axis = -1; + response.bias = 0; + response.scale = 1; + break; + case component_property::x_axis: + response.axis = 0; + response.bias = 0.5; + response.scale = 0.5; + break; + case component_property::y_axis: + // Y axis is reversed in WebXR (min up, max down, https://github.com/immersive-web/webxr-input-profiles/blob/main/packages/assets/tutorial/README.md#buttons) and OpenXR (-1 down, +1 up, ยง6.3.2, Standard components) + response.axis = 1; + response.bias = 0.5; + response.scale = -0.5; + break; + } + + scene_object_handle controller_root_node; + for(auto&& [i, j]: model_handles) + { + if (j->name == json_response.layout) + { + controller_root_node = j; + assert(controller_root_node->name == json_response.layout); + break; + } + } + + response.target.node = scene.find_node(controller_root_node, json_response.target_node); + response.target.state = json_response.state; + } +} + +static std::optional> locate_controller(XrSpace space, XrSpace reference, XrTime time) +{ + XrSpaceLocation location{.type = XR_TYPE_SPACE_LOCATION}; + + assert(space != XR_NULL_HANDLE); + assert(reference != XR_NULL_HANDLE); + + xrLocateSpace(space, reference, time, &location); + + auto req_flags = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT; + if ((location.locationFlags & req_flags) != req_flags) + return {}; + + glm::vec3 position{ + location.pose.position.x, + location.pose.position.y, + location.pose.position.z, + }; + + glm::quat orientation{ + location.pose.orientation.w, + location.pose.orientation.x, + location.pose.orientation.y, + location.pose.orientation.z, + }; + + return std::make_pair(position, orientation); +} + +void apply_visual_response(scene_object_handle node, std::pair transforms, float value) +{ + node->translation = glm::mix(transforms.first.position, transforms.second.position, value); + node->rotation = glm::slerp(transforms.first.orientation, transforms.second.orientation, value); +} + +void apply_visual_response(scene_object_handle node, input_profile::node_state_visibility, float value) +{ + node->visible = value > 0.5; +} + +void input_profile::apply(XrSpace world_space, XrTime predicted_display_time) +{ + for (auto && [space, node]: model_handles) + { + if (auto location = locate_controller(space, world_space, predicted_display_time); location) + { + node->visible = true; + node->translation = location->first; + node->rotation = location->second; + } + else + { + node->visible = false; + } + } + + for (auto & response: responses) + { + assert(response.action); + + std::optional value; + + switch (response.type) + { + case XR_ACTION_TYPE_BOOLEAN_INPUT: { + auto opt_value = application::read_action_bool(response.action); + if (opt_value) + value = opt_value->second; + break; + } + + case XR_ACTION_TYPE_FLOAT_INPUT: { + auto opt_value = application::read_action_float(response.action); + if (opt_value) + value = opt_value->second; + break; + } + + case XR_ACTION_TYPE_VECTOR2F_INPUT: { + auto opt_value = application::read_action_vec2(response.action); + if (opt_value) + { + switch (response.axis) + { + case 0: + value = opt_value->second.x; + break; + case 1: + value = opt_value->second.y; + break; + } + } + break; + } + + case XR_ACTION_TYPE_POSE_INPUT: + case XR_ACTION_TYPE_VIBRATION_OUTPUT: + case XR_ACTION_TYPE_MAX_ENUM: + assert(false); + break; + } + + if (value) + { + float scaled_value = *value * response.scale + response.bias; + + if ((scaled_value < 0) || (scaled_value > 1)) + { + std::string full_name = response.target.node->name; + + for(auto i = response.target.node; i; i = i.parent()) + { + full_name = i->name + "/" + full_name; + } + + spdlog::warn("Out of range value {} (scaled to {}) for node {}", *value, scaled_value, full_name); + } + + + std::visit([&](auto& transform) + { + apply_visual_response(response.target.node, transform, scaled_value); + }, response.target.state); + } + } +} diff --git a/client/scenes/input_profile.h b/client/scenes/input_profile.h new file mode 100644 index 00000000..d44f980d --- /dev/null +++ b/client/scenes/input_profile.h @@ -0,0 +1,66 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 . + */ + +#pragma once + +#include +#include +#include +#include + +struct input_profile +{ + struct node_state_transform + { + glm::vec3 position; + glm::quat orientation; + }; + + struct node_state_visibility + { + }; + + using node_state = std::variant, node_state_visibility>; + + struct node_target + { + scene_object_handle node; + node_state state; + }; + + struct visual_response + { + XrAction action; + XrActionType type; + int axis; // Only if type is XR_ACTION_TYPE_VECTOR2F_INPUT + float bias; + float scale; + + node_target target; + }; + + std::string id; + + std::vector responses; + std::vector> model_handles; + + input_profile(const std::filesystem::path& json_profile, scene_loader& loader, scene_data& scene); + + // application::poll_actions() must have been called before + void apply(XrSpace world_space, XrTime predicted_display_time); +}; diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index 17217cda..ba1f6e6d 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -1,7 +1,7 @@ /* * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 Patrick Nicolas * * 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 @@ -18,19 +18,21 @@ */ #include "lobby.h" -#include "render/text_rasterizer.h" -#include "stream.h" #include "../common/version.h" #include "application.h" - -#include "vk/pipeline_layout.h" -#include "vk/shader.h" -#include "vk/pipeline.h" +#include "input_profile.h" +#include "openxr/openxr.h" +#include "render/scene_data.h" +#include "render/text_rasterizer.h" +#include "stream.h" +#include "hardware.h" #include #include -#include +#include #include +#include +#include #include #include @@ -38,187 +40,55 @@ static const std::string discover_service = "_wivrn._tcp.local."; scenes::lobby::~lobby() {} +static std::string choose_webxr_profile() +{ +#ifndef __ANDROID__ + const char * controller = std::getenv("WIVRN_CONTROLLER"); + if (controller && strcmp(controller, "")) + return controller; +#endif + + switch(guess_model()) + { + case model::oculus_quest: + return "oculus-touch-v2"; + case model::oculus_quest_2: + return "oculus-touch-v3"; + case model::meta_quest_pro: + return "meta-quest-touch-pro"; + case model::meta_quest_3: + return "meta-quest-touch-plus"; + case model::pico_neo_3: + return "pico-neo3"; + case model::pico_4: + return "pico-4"; + case model::unknown: + return "generic-trigger-squeeze"; + } +} + scenes::lobby::lobby() : - status_string_rasterizer(device, physical_device, commandpool, queue)//, renderer(device, physical_device, queue) + status_string_rasterizer(device, physical_device, commandpool, queue) { uint32_t width = swapchains[0].width(); uint32_t height = swapchains[0].height(); + vk::Extent2D output_size{width, height}; - // Create renderpass - vk::RenderPassCreateInfo renderpass_info; - - vk::AttachmentDescription attachment_desc{ - .format = swapchains[0].format(), - .samples = vk::SampleCountFlagBits::e1, - .loadOp = vk::AttachmentLoadOp::eClear, - .storeOp = vk::AttachmentStoreOp::eStore, - .initialLayout = vk::ImageLayout::eUndefined, - .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, - }; - renderpass_info.setAttachments(attachment_desc); - - vk::SubpassDescription subpass_desc{ - .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, - }; - vk::AttachmentReference color_ref{ - .attachment = 0, - .layout = vk::ImageLayout::eColorAttachmentOptimal, - }; - subpass_desc.setColorAttachments(color_ref); - renderpass_info.setSubpasses(subpass_desc); - - renderpass = vk::raii::RenderPass(device, renderpass_info); - - vk::SamplerCreateInfo sampler_info{ - .magFilter = vk::Filter::eLinear, - .minFilter = vk::Filter::eLinear, - .mipmapMode = vk::SamplerMipmapMode::eNearest, - .addressModeU = vk::SamplerAddressMode::eClampToBorder, - .addressModeV = vk::SamplerAddressMode::eClampToBorder, - .addressModeW = vk::SamplerAddressMode::eClampToBorder, - .mipLodBias = 0.0f, - .anisotropyEnable = VK_FALSE, - .maxAnisotropy = 1, - .compareEnable = VK_FALSE, - .compareOp = vk::CompareOp::eNever, - .minLod = 0.0f, - .maxLod = 0.0f, - .borderColor = vk::BorderColor::eFloatOpaqueBlack, - .unnormalizedCoordinates = VK_FALSE, + std::array depth_formats{ + vk::Format::eD16Unorm, + vk::Format::eX8D24UnormPack32, + vk::Format::eD32Sfloat, }; - status_string_sampler = vk::raii::Sampler(device, sampler_info); + renderer.emplace(device, physical_device, queue, commandpool, output_size, swapchains[0].format(), depth_formats); - // Create descriptor set layout - vk::DescriptorSetLayoutBinding layout_binding{ - .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment, - }; + scene_loader loader(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material()); - vk::DescriptorSetLayoutCreateInfo layout_info; - layout_info.setBindings(layout_binding); + teapot.import(loader("lobby.gltf")); - status_string_image_descriptor_set_layout = vk::raii::DescriptorSetLayout(device, layout_info); + input = input_profile("webxr-profiles/" + choose_webxr_profile() + "/profile.json", loader, teapot); - vk::DescriptorPoolSize status_string_image_descriptor_set_pool_size{ - .type = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - }; - - vk::DescriptorPoolCreateInfo pool_info{ - .maxSets = 1, - }; - pool_info.setPoolSizes(status_string_image_descriptor_set_pool_size); - - status_string_descriptor_pool = vk::raii::DescriptorPool(device, pool_info); - - vk::DescriptorSetAllocateInfo ds_info{ - .descriptorPool = *status_string_descriptor_pool, - .descriptorSetCount = 1, - }; - ds_info.setSetLayouts(*status_string_image_descriptor_set_layout); - - status_string_image_descriptor_set = device.allocateDescriptorSets(ds_info)[0].release(); - - vk::PipelineLayoutCreateInfo pipeline_layout_info; - pipeline_layout_info.setSetLayouts(*status_string_image_descriptor_set_layout); - vk::PushConstantRange push_constant_range{ - .stageFlags = vk::ShaderStageFlagBits::eVertex, - .offset = 0, - .size = sizeof(glm::mat4), - }; - pipeline_layout_info.setPushConstantRanges(push_constant_range); - - layout = vk::raii::PipelineLayout(device, pipeline_layout_info); - - // Create graphics pipeline - vk::raii::ShaderModule vertex_shader = load_shader(device, "text.vert"); - vk::raii::ShaderModule fragment_shader = load_shader(device, "text.frag"); - - vk::pipeline_builder pipeline_info - { - .flags = {}, - .Stages = {{ - .stage = vk::ShaderStageFlagBits::eVertex, - .module = *vertex_shader, - .pName = "main", - },{ - .stage = vk::ShaderStageFlagBits::eFragment, - .module = *fragment_shader, - .pName = "main", - }}, - .VertexInputState = {.flags = {}}, - .VertexBindingDescriptions = {}, - .VertexAttributeDescriptions = {}, - .InputAssemblyState = {{ - .topology = vk::PrimitiveTopology::eTriangleList, - }}, - .ViewportState = {.flags = {}}, - .Viewports = {{ - .x = 0, - .y = 0, - .width = (float)width, - .height = (float)height, - .minDepth = 0, - .maxDepth = 1, - }}, - .Scissors = {{ - .offset = { .x = 0, .y = 0 }, - .extent= { .width = width, .height = height }, - }}, - .RasterizationState = {{ - .polygonMode = vk::PolygonMode::eFill, - .lineWidth = 1, - }}, - .MultisampleState = {{ - .rasterizationSamples = vk::SampleCountFlagBits::e1, - }}, - .ColorBlendState = {.flags = {}}, - .ColorBlendAttachments = {{ - .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB - }}, - .layout = *layout, - .renderPass = *renderpass, - .subpass = 0, - }; - - pipeline = vk::raii::Pipeline(device, nullptr, pipeline_info); - - images_data.resize(swapchains.size()); - for (size_t i = 0; i < swapchains.size(); i++) - { - auto & images = swapchains[i].images(); - images_data[i].reserve(images.size()); - - for (size_t j = 0; j < images.size(); j++) - { - vk::FramebufferCreateInfo fb_create_info{ - .renderPass = *renderpass, - .attachmentCount = 1, - .pAttachments = &*images[j].view, - .width = swapchains[i].width(), - .height = swapchains[i].height(), - .layers = 1, - }; - - images_data[i].emplace_back(image_data{ - .framebuffer = vk::raii::Framebuffer(device, fb_create_info), - .render_finished = create_semaphore() - }); - } - } - - vk::CommandBufferAllocateInfo alloc_info; - alloc_info.commandBufferCount = 1; - alloc_info.level = vk::CommandBufferLevel::ePrimary; - alloc_info.commandPool = *commandpool; - - command_buffer = std::move(device.allocateCommandBuffers(alloc_info)[0]); - - application::set_debug_reports_name((VkCommandBuffer)*command_buffer, "lobby command buffer"); - fence = create_fence(false); + spdlog::info("Loaded input profile {}", input->id); } void scenes::lobby::rasterize_status_string() @@ -226,39 +96,39 @@ void scenes::lobby::rasterize_status_string() status_string_rasterized_text = status_string_rasterizer.render(status_string); vk::ImageViewCreateInfo iv_info{ - .image = status_string_rasterized_text.image, - .viewType = vk::ImageViewType::e2D, - .format = status_string_rasterized_text.format, - .components = { - .r = vk::ComponentSwizzle::eIdentity, - .g = vk::ComponentSwizzle::eIdentity, - .b = vk::ComponentSwizzle::eIdentity, - .a = vk::ComponentSwizzle::eIdentity, - }, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, + .image = status_string_rasterized_text.image, + .viewType = vk::ImageViewType::e2D, + .format = status_string_rasterized_text.format, + .components = { + .r = vk::ComponentSwizzle::eIdentity, + .g = vk::ComponentSwizzle::eIdentity, + .b = vk::ComponentSwizzle::eIdentity, + .a = vk::ComponentSwizzle::eIdentity, + }, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, }; status_string_image_view = vk::raii::ImageView(device, iv_info); vk::DescriptorImageInfo image_info{ - .sampler = *status_string_sampler, - .imageView = *status_string_image_view, - .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .sampler = *status_string_sampler, + .imageView = *status_string_image_view, + .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, }; vk::WriteDescriptorSet descriptor_write{ - .dstSet = status_string_image_descriptor_set, - .dstBinding = 0, - .dstArrayElement = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = &image_info, + .dstSet = status_string_image_descriptor_set, + .dstBinding = 0, + .dstArrayElement = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &image_info, }; device.updateDescriptorSets(descriptor_write, {}); @@ -266,12 +136,12 @@ void scenes::lobby::rasterize_status_string() last_status_string = status_string; } -std::unique_ptr connect_to_session(const std::vector& services) +std::unique_ptr connect_to_session(const std::vector & services) { char protocol_string[17]; sprintf(protocol_string, "%016lx", xrt::drivers::wivrn::protocol_version); - for(const wivrn_discover::service& service: services) + for (const wivrn_discover::service & service: services) { auto protocol = service.txt.find("protocol"); if (protocol == service.txt.end()) @@ -281,15 +151,16 @@ std::unique_ptr connect_to_session(const std::vector(address, port); - }, address); + }, + address); } - catch(std::exception& e) + catch (std::exception & e) { spdlog::warn("Cannot connect to {}: {}", service.hostname, e.what()); } @@ -299,6 +170,35 @@ std::unique_ptr connect_to_session(const std::vectoralive()) @@ -339,8 +239,8 @@ void scenes::lobby::render() status_string = "Waiting for connection"; } - if (status_string != last_status_string) - rasterize_status_string(); + // if (status_string != last_status_string) + // rasterize_status_string(); XrFrameState framestate = session.wait_frame(); @@ -353,38 +253,47 @@ void scenes::lobby::render() session.begin_frame(); - command_buffer.reset(); - - command_buffer.begin(vk::CommandBufferBeginInfo{}); - auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space); assert(views.size() == swapchains.size()); - std::vector layer_view(views.size()); - for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++) + + + application::poll_actions(); + input->apply(world_space, framestate.predictedDisplayTime); + + + std::vector layer_view; + std::vector frames; + + layer_view.reserve(views.size()); + frames.reserve(views.size()); + + for (auto && [view, swapchain]: utils::zip(views, swapchains)) { - int image_index = swapchains[swapchain_index].acquire(); - swapchains[swapchain_index].wait(); + int image_index = swapchain.acquire(); + swapchain.wait(); - render_view(flags, framestate.predictedDisplayTime, views[swapchain_index], swapchain_index, image_index); + frames.push_back({.destination = swapchain.images()[image_index].image, + .projection = projection_matrix(view.fov), + .view = view_matrix(view.pose)}); - swapchains[swapchain_index].release(); - - layer_view[swapchain_index].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW; - layer_view[swapchain_index].pose = views[swapchain_index].pose; - layer_view[swapchain_index].fov = views[swapchain_index].fov; - layer_view[swapchain_index].subImage.swapchain = swapchains[swapchain_index]; - layer_view[swapchain_index].subImage.imageRect.offset = {0, 0}; - layer_view[swapchain_index].subImage.imageRect.extent.width = swapchains[swapchain_index].width(); - layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height(); + layer_view.push_back({ + .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, + .pose = view.pose, + .fov = view.fov, + .subImage = { + .swapchain = swapchain, + .imageRect = { + .offset = {0, 0}, + .extent = swapchain.extent()}}, + }); } - command_buffer.end(); + assert(renderer); + renderer->render(teapot, frames); - vk::SubmitInfo submit_info; - submit_info.setCommandBuffers(*command_buffer); - - queue.submit(submit_info, *fence); + for (auto & swapchain: swapchains) + swapchain.release(); XrCompositionLayerProjection layer{ .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION, @@ -398,67 +307,6 @@ void scenes::lobby::render() layers_base.push_back(reinterpret_cast(&layer)); session.end_frame(framestate.predictedDisplayTime, layers_base); - - if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout) - throw std::runtime_error("Vulkan fence timeout"); - device.resetFences(*fence); -} - -void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index) -{ - xr::swapchain & swapchain = swapchains[swapchain_index]; - image_data & data = images_data[swapchain_index][image_index]; - - vk::ClearValue clear_color; - clear_color.color = {0.0f, 0.0f, 0.0f, 1.0f}; - - vk::RenderPassBeginInfo renderpass_info{ - .renderPass = *renderpass, - .framebuffer = *data.framebuffer, - .renderArea = { - .offset = {0, 0}, - .extent = {swapchain.width(), swapchain.height()}, - } - }; - renderpass_info.setClearValues(clear_color); - - command_buffer.beginRenderPass(renderpass_info, vk::SubpassContents::eInline); - command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *pipeline); - command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *layout, 0, status_string_image_descriptor_set, {}); - - float zn = 0.1; - float r = tan(view.fov.angleRight); - float l = tan(view.fov.angleLeft); - float t = tan(view.fov.angleUp); - float b = tan(view.fov.angleDown); - - // clang-format off - glm::mat4 proj{ - { 2/(r-l), 0, 0, 0 }, - { 0, 2/(b-t), 0, 0 }, - { (l+r)/(r-l), (t+b)/(b-t), -1, -1 }, - { 0, 0, -2*zn, 0 } - }; - // clang-format on - - glm::mat4 view_matrix = glm::mat4_cast(glm::quat(view.pose.orientation.w, view.pose.orientation.x, view.pose.orientation.y, view.pose.orientation.z)); - - view_matrix = glm::translate(glm::mat4(1), - glm::vec3(view.pose.position.x, view.pose.position.y, view.pose.position.z)) * - view_matrix; - - float aspect_ratio = (float)status_string_rasterized_text.size.width / (float)status_string_rasterized_text.size.height; - glm::mat4 model_matrix{ - {aspect_ratio, 0, 0, 0}, - {0, 1, 0, 0}, - {0, 0, 1, 0}, - {-0.5 * aspect_ratio, -0.5, -10, 1}}; - - glm::mat4 mvp = proj * glm::inverse(view_matrix) * model_matrix; - - command_buffer.pushConstants(*layout, vk::ShaderStageFlagBits::eVertex, 0, mvp); - command_buffer.draw(6, 1, 0, 0); - command_buffer.endRenderPass(); } void scenes::lobby::on_focused() diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index f47aae1e..f9a1eebc 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -27,6 +27,7 @@ #include "render/scene_renderer.h" #include "render/text_rasterizer.h" +#include "input_profile.h" namespace scenes { @@ -44,32 +45,34 @@ class lobby : public scene vk::DescriptorSet status_string_image_descriptor_set; text_rasterizer status_string_rasterizer; - vk::raii::RenderPass renderpass = nullptr; - vk::raii::PipelineLayout layout = nullptr; - vk::raii::Pipeline pipeline = nullptr; + // vk::raii::RenderPass renderpass = nullptr; + // vk::raii::PipelineLayout layout = nullptr; + // vk::raii::Pipeline pipeline = nullptr; - vk::raii::Fence fence = nullptr; - vk::raii::CommandBuffer command_buffer = nullptr; + // vk::raii::Fence fence = nullptr; + // vk::raii::CommandBuffer command_buffer = nullptr; - struct image_data - { - vk::raii::Framebuffer framebuffer; - vk::raii::Semaphore render_finished; - }; + // struct image_data + // { + // vk::raii::Framebuffer framebuffer; + // vk::raii::Semaphore render_finished; + // }; - std::vector> images_data; + // std::vector> images_data; std::optional discover; - std::vector model_memory; - std::vector model_buffers; - std::vector model_images; + // std::vector model_memory; + // std::vector model_buffers; + // std::vector model_images; - void load_model(const std::string & filename); + // void load_model(const std::string & filename); std::shared_ptr next_scene; - // scene_renderer renderer; + std::optional renderer; + scene_data teapot; + std::optional input; void rasterize_status_string(); diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 3c222117..eb063aaa 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -459,8 +459,9 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript .initialLayout = vk::ImageLayout::eUndefined, }; - VmaAllocationCreateInfo alloc_info{}; - alloc_info.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + VmaAllocationCreateInfo alloc_info{ + .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + }; decoder_output[i].image = image_allocation{image_info, alloc_info}; @@ -506,7 +507,7 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript } spdlog::info("Initializing reprojector"); - vk::Extent2D extent = {swapchains[0].width(), swapchains[0].height()}; + vk::Extent2D extent = {(uint32_t)swapchains[0].width(), (uint32_t)swapchains[0].height()}; std::vector swapchain_images; for (auto & swapchain: swapchains) { @@ -525,7 +526,7 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript void scenes::stream::video() { -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ application::instance().setup_jni(); #endif diff --git a/client/shaders/lit.glsl b/client/shaders/lit.glsl new file mode 100644 index 00000000..6e1ca828 --- /dev/null +++ b/client/shaders/lit.glsl @@ -0,0 +1,132 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * 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 . + */ + +#version 450 + +#define NB_TEXCOORDS 2 + +layout(set = 0, binding = 0) uniform scene_ubo +{ + mat4 view; + mat4 proj; + vec4 light_position; + vec4 ambient_color; + vec4 light_color; +} scene; + +layout(set = 0, binding = 1) uniform mesh_ubo +{ + mat4 model; + mat4 modelview; + mat4 modelviewproj; +} mesh; + +#ifdef FRAG_SHADER +layout(set = 1, binding = 0) uniform sampler2D base_color; +layout(set = 1, binding = 1) uniform sampler2D metallic_roughness; +layout(set = 1, binding = 2) uniform sampler2D occlusion; +layout(set = 1, binding = 3) uniform sampler2D emissive; +layout(set = 1, binding = 4) uniform sampler2D normal_map; +layout(set = 1, binding = 5) uniform material_ubo +{ + vec4 base_color_factor; + vec4 base_emissive_factor; + float metallic_factor; + float roughness_factor; + float occlusion_strength; + float normal_scale; + + int base_color_texcoord; + int metallic_roughness_texcoord; + int occlusion_texcoord; + int emissive_texcoord; + int normal_texcoord; +} material; +#endif + +// Vertex input +#ifdef VERT_SHADER +layout(location = 0) in vec3 in_position; +layout(location = 1) in vec3 in_normal; +layout(location = 2) in vec3 in_tangent; +layout(location = 3) in vec2 in_texcoord[NB_TEXCOORDS]; +layout(location = 3+NB_TEXCOORDS) in vec4 in_color; +layout(location = 4+NB_TEXCOORDS) in vec4 in_joints; +layout(location = 5+NB_TEXCOORDS) in vec4 in_weights; +#endif + +// Vertex-to-fragment +#ifdef VERT_SHADER +#define VERT_TO_FRAG out +#else +#define VERT_TO_FRAG in +#endif + +layout(location = 0) VERT_TO_FRAG vec3 normal; +layout(location = 1) VERT_TO_FRAG vec2 texcoord[NB_TEXCOORDS]; +layout(location = 1+NB_TEXCOORDS) VERT_TO_FRAG vec3 frag_pos; +layout(location = 2+NB_TEXCOORDS) VERT_TO_FRAG vec4 light_pos; + +// Fragment output +#ifdef FRAG_SHADER +layout(location = 0) out vec4 out_color; +#endif + +// Shader code +#ifdef VERT_SHADER +void main() +{ + normal = vec3(mesh.modelview * vec4(in_normal, 0.0)); + + for(int i = 0; i < 2; i++) + texcoord[i] = in_texcoord[i]; + + gl_Position = mesh.modelviewproj * vec4(in_position, 1.0); + frag_pos = vec3(mesh.modelview * vec4(in_position, 1.0)); + light_pos = mesh.modelview * scene.light_position; +} + +#endif + +#ifdef FRAG_SHADER +void main() +{ + vec3 light_dir = normalize(light_pos.xyz - frag_pos * light_pos.w); + vec3 view_dir = normalize(frag_pos); + vec3 normal_unit = normalize(normal); + vec3 reflect_dir = reflect(-light_dir, normal_unit); + + // Ambient lighting + vec3 ambient = vec3(scene.ambient_color); + + // Diffuse lighting + vec3 diffuse = max(dot(normal_unit, light_dir), 0.0) * vec3(scene.light_color); + + // Specular lighting +// vec3 half_dir = normalize(light_dir + view_dir); +// float spec_angle = max(dot(half_dir, normal_unit), 0.0); +// vec3 specular = pow(spec_angle, instance.specular_power) * instance.specular_strength * instance.light_color; + + vec3 light = ambient + diffuse /*+ specular*/; +// out_color = texture(base_color, texcoord[0]) * vec4(light, 1.0); + +// out_color = vec4(1.0, 1.0, 1.0, 1.0); + out_color = texture(base_color, texcoord[0]); +} +#endif diff --git a/client/vk/pipeline.cpp b/client/utils/alignment.h similarity index 80% rename from client/vk/pipeline.cpp rename to client/utils/alignment.h index d02e7105..d2727360 100644 --- a/client/vk/pipeline.cpp +++ b/client/utils/alignment.h @@ -17,4 +17,16 @@ * along with this program. If not, see . */ -#include "pipeline.h" +#pragma once + +#include + +namespace utils +{ + template + requires std::integral + T align_up(T alignment, T value) + { + return ((value + alignment - 1) / alignment) * alignment; + } +} diff --git a/client/utils/fmt_glm.h b/client/utils/fmt_glm.h new file mode 100644 index 00000000..ca4e8374 --- /dev/null +++ b/client/utils/fmt_glm.h @@ -0,0 +1,96 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 . + */ + +#pragma once + +#include +#include + + +// /usr/include/fmt/chrono.h:2017 + +template +struct fmt::formatter, Char> //: fmt::formatter +{ + // auto parse(basic_format_parse_context& ctx) const -> decltype(ctx.begin()) + // { + // auto begin = ctx.begin(), end = ctx.end(); + // // if (begin != end && *begin == 'L') { + // // ++begin; + // // localized = true; + // // } + // return begin; + // } + + auto parse(basic_format_parse_context& ctx) const // -> decltype(ctx.begin()) + { + return ctx.begin(); + } + + + template + auto format(const glm::vec& v, FormatContext& ctx) const -> decltype(ctx.out()) + { + if constexpr (L == 1) + { + return fmt::format_to(ctx.out(), "[ {} ]", v.x); + } + + if constexpr (L == 2) + { + return fmt::format_to(ctx.out(), "[ {}, {} ]", v.x, v.y); + } + + if constexpr (L == 3) + { + return fmt::format_to(ctx.out(), "[ {}, {}, {} ]", v.x, v.y, v.z); + } + + if constexpr (L == 4) + { + return fmt::format_to(ctx.out(), "[ {}, {}, {}, {} ]", v.x, v.y, v.z, v.w); + } + + + + // return formatter( + + + // auto time = std::tm(); + // time.tm_wday = static_cast(wd.c_encoding()); + // detail::get_locale loc(localized, ctx.locale()); + // auto w = detail::tm_writer(loc, ctx.out(), time); + // w.on_abbr_weekday(); + // return w.out(); + } + +}; + + +/* +template +struct fmt::formatter> : fmt::formatter +{ +}; + + + +template +struct fmt::formatter> : fmt::formatter +{ +};*/ diff --git a/client/vk/pipeline_layout.h b/client/utils/magic_hash.h similarity index 53% rename from client/vk/pipeline_layout.h rename to client/utils/magic_hash.h index f3504909..500462cc 100644 --- a/client/vk/pipeline_layout.h +++ b/client/utils/magic_hash.h @@ -19,29 +19,45 @@ #pragma once -#include "utils/handle.h" -#include -#include +#include +#include +#include -namespace vk +namespace utils { -class pipeline_layout : public utils::handle -{ - VkDevice device{}; -public: - struct info +template +struct is_vk_flags : std::false_type {}; + +template +struct is_vk_flags> : std::true_type {}; + + +template +struct magic_hash +{ + std::size_t operator()(const T & info) const noexcept { - std::vector descriptor_set_layouts; - std::vector push_constant_ranges; - }; + size_t h = 0; - ~pipeline_layout(); - pipeline_layout() = default; - pipeline_layout(VkDevice device, const info & create_info); - pipeline_layout(const pipeline_layout &) = delete; - pipeline_layout(pipeline_layout &&) = default; - pipeline_layout & operator=(const pipeline_layout &) = delete; - pipeline_layout & operator=(pipeline_layout &&) = default; + boost::pfr::for_each_field(info, [&](const auto & member) { + + using U = std::remove_cvref_t; + + if constexpr (is_vk_flags::value) + { + using V = U::MaskType; + std::hash hasher; + h = std::rotl(h, 5) ^ hasher(static_cast(member)); + } + else + { + std::hash hasher; + h = std::rotl(h, 5) ^ hasher(member); + } + }); + + return h; + } }; -} // namespace vk +} diff --git a/client/utils/ranges.h b/client/utils/ranges.h index bc94c067..c7e149aa 100644 --- a/client/utils/ranges.h +++ b/client/utils/ranges.h @@ -25,12 +25,34 @@ namespace utils { + + template + concept has_const_iterator = requires { + std::declval(); + }; + + template struct get_const_iterator_aux; + + template struct get_const_iterator_aux + { + using const_iterator = T::const_iterator; + }; + + template struct get_const_iterator_aux + { + using const_iterator = T::iterator; + }; + + template + using get_const_iterator = get_const_iterator_aux>::const_iterator; + + template struct enumerate_range { struct iterator { - using underlying_iterator = std::conditional_t, typename T::const_iterator, typename T::iterator>; + using underlying_iterator = std::conditional_t, get_const_iterator, typename T::iterator>; using underlying_value_type = std::conditional_t, const typename T::value_type, typename T::value_type>; size_t index; @@ -38,7 +60,8 @@ struct enumerate_range std::pair operator*() const { - return {index, *it}; + underlying_value_type & x = *it; + return {index, x}; } iterator & operator++() diff --git a/client/vk/allocation.cpp b/client/vk/allocation.cpp index 817a060c..385b1b07 100644 --- a/client/vk/allocation.cpp +++ b/client/vk/allocation.cpp @@ -55,7 +55,7 @@ void basic_allocation_traits::destroy( vmaDestroyBuffer(allocator, buffer.release(), allocation); } -void * basic_allocation_traits::map(VmaAllocation allocation) +void * basic_allocation_traits_base::map(VmaAllocation allocation) { VmaAllocator allocator = application::get_allocator(); @@ -64,6 +64,13 @@ void * basic_allocation_traits::map(VmaAllocation allocation) return mapped; } +void basic_allocation_traits_base::unmap(VmaAllocation allocation) +{ + VmaAllocator allocator = application::get_allocator(); + + vmaUnmapMemory(allocator, allocation); +} + std::pair basic_allocation_traits::create( const CreateInfo& image_info, const VmaAllocationCreateInfo* alloc_info) @@ -90,12 +97,3 @@ void basic_allocation_traits::destroy( vmaDestroyImage(allocator, image.release(), allocation); } - -void * basic_allocation_traits::map(VmaAllocation allocation) -{ - VmaAllocator allocator = application::get_allocator(); - - void * mapped; - CHECK_VK(vmaMapMemory(allocator, allocation, &mapped)); - return mapped; -} diff --git a/client/vk/allocation.h b/client/vk/allocation.h index 68e9c153..53ca6c66 100644 --- a/client/vk/allocation.h +++ b/client/vk/allocation.h @@ -27,8 +27,14 @@ struct basic_allocation_traits { }; +struct basic_allocation_traits_base +{ + static void * map(VmaAllocation allocation); + static void unmap(VmaAllocation allocation); +}; + template<> -struct basic_allocation_traits +struct basic_allocation_traits : basic_allocation_traits_base { using CreateInfo = vk::BufferCreateInfo; using NativeCreateInfo = CreateInfo::NativeType; @@ -42,12 +48,10 @@ struct basic_allocation_traits RaiiType& buffer, VmaAllocation allocation, void * mapped); - - static void * map(VmaAllocation allocation); }; template<> -struct basic_allocation_traits +struct basic_allocation_traits : basic_allocation_traits_base { using CreateInfo = vk::ImageCreateInfo; using NativeCreateInfo = CreateInfo::NativeType; @@ -61,8 +65,6 @@ struct basic_allocation_traits RaiiType& image, VmaAllocation allocation, void * mapped); - - static void * map(VmaAllocation allocation); }; template @@ -79,6 +81,7 @@ private: VmaAllocation allocation = nullptr; RaiiType resource = nullptr; void * mapped = nullptr; + CreateInfo create_info{}; public: operator T() @@ -91,6 +94,11 @@ public: return *resource; } + operator bool() const + { + return *resource; + } + operator VmaAllocation() const { return allocation; @@ -107,16 +115,18 @@ public: } basic_allocation() = default; - basic_allocation(const CreateInfo& buffer_info, const VmaAllocationCreateInfo& alloc_info) + basic_allocation(const CreateInfo& create_info, const VmaAllocationCreateInfo& alloc_info) : + create_info(create_info) { - std::tie(resource, allocation) = traits::create(buffer_info, &alloc_info); + std::tie(resource, allocation) = traits::create(create_info, &alloc_info); } basic_allocation(const basic_allocation&) = delete; basic_allocation(basic_allocation&& other) : allocation(other.allocation), resource(std::move(other.resource)), - mapped(other.mapped) + mapped(other.mapped), + create_info(other.create_info) { other.allocation = nullptr; other.mapped = nullptr; @@ -128,6 +138,7 @@ public: std::swap(allocation, other.allocation); std::swap(resource, other.resource); std::swap(mapped, other.mapped); + std::swap(create_info, other.create_info); return *this; } @@ -146,11 +157,25 @@ public: return mapped; } + void unmap() + { + if (!mapped) + return; + + traits::unmap(allocation); + mapped = nullptr; + } + template U * data() { return reinterpret_cast(map()); } + + const CreateInfo& info() const + { + return create_info; + } }; diff --git a/client/vk/device_memory.cpp b/client/vk/device_memory.cpp deleted file mode 100644 index a18475e4..00000000 --- a/client/vk/device_memory.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * 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 . - */ - -#include "device_memory.h" -#include "utils/check.h" - -uint32_t vk::device_memory::get_memory_type(VkPhysicalDevice physical_device, VkMemoryRequirements requirements, VkMemoryPropertyFlags property_flags) -{ - uint32_t types = requirements.memoryTypeBits; - - VkPhysicalDeviceMemoryProperties memory_properties{}; - vkGetPhysicalDeviceMemoryProperties(physical_device, &memory_properties); - - for (uint32_t type = 0; type < memory_properties.memoryTypeCount; ++type) - { - if (not((1 << type) & types)) - continue; - - const auto & properties = memory_properties.memoryTypes[type]; - if ((properties.propertyFlags & property_flags) == property_flags) - return type; - } - - throw std::runtime_error{"No Vulkan memory with required flags"}; -} - -vk::device_memory::device_memory(VkDevice device, const VkMemoryAllocateInfo & allocate_info) : - device(device) -{ - CHECK_VK(vkAllocateMemory(device, &allocate_info, nullptr, &id)); -} - -vk::device_memory::device_memory(VkDevice device, VkPhysicalDevice physical_device, VkImage target_image, VkMemoryPropertyFlags properties) : - device(device) -{ - VkMemoryRequirements requirements; - vkGetImageMemoryRequirements(device, target_image, &requirements); - - uint32_t memory_type = get_memory_type(physical_device, requirements, properties); - - VkMemoryDedicatedAllocateInfoKHR dedicated_allocate_info{}; - dedicated_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO; - dedicated_allocate_info.image = target_image; - - VkMemoryAllocateInfo memory_allocate_info{}; - memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - memory_allocate_info.allocationSize = requirements.size; - memory_allocate_info.memoryTypeIndex = memory_type; - memory_allocate_info.pNext = &dedicated_allocate_info; - - CHECK_VK(vkAllocateMemory(device, &memory_allocate_info, nullptr, &id)); - - try - { - CHECK_VK(vkBindImageMemory(device, target_image, id, 0)); - } - catch (...) - { - vkFreeMemory(device, id, nullptr); - throw; - } -} - -vk::device_memory::device_memory(VkDevice device, VkPhysicalDevice physical_device, VkBuffer target_buffer, VkMemoryPropertyFlags properties) : - device(device) -{ - VkMemoryRequirements requirements; - vkGetBufferMemoryRequirements(device, target_buffer, &requirements); - - uint32_t memory_type = get_memory_type(physical_device, requirements, properties); - - VkMemoryDedicatedAllocateInfoKHR dedicated_allocate_info{}; - dedicated_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO; - dedicated_allocate_info.buffer = target_buffer; - - VkMemoryAllocateInfo memory_allocate_info{}; - memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - memory_allocate_info.allocationSize = requirements.size; - memory_allocate_info.memoryTypeIndex = memory_type; - memory_allocate_info.pNext = &dedicated_allocate_info; - - CHECK_VK(vkAllocateMemory(device, &memory_allocate_info, nullptr, &id)); - - try - { - CHECK_VK(vkBindBufferMemory(device, target_buffer, id, 0)); - } - catch (...) - { - vkFreeMemory(device, id, nullptr); - throw; - } -} - -vk::device_memory::~device_memory() -{ - if (device) - { - if (id and map) - { - vkUnmapMemory(device, id); - } - vkFreeMemory(device, id, nullptr); - } -} - -void vk::device_memory::map_memory() -{ - CHECK_VK(vkMapMemory(device, id, 0, VK_WHOLE_SIZE, 0, (void **)&map)); -} diff --git a/client/vk/device_memory.h b/client/vk/device_memory.h deleted file mode 100644 index 923df1cf..00000000 --- a/client/vk/device_memory.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * 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 . - */ - -#pragma once - -#include "utils/handle.h" -#include - -static_assert(not std::is_same_v, "vulkan handles need to be different types"); - -namespace vk -{ -class device_memory : public utils::handle -{ - VkDevice device{}; - void * map = nullptr; - -public: - device_memory() = default; - device_memory(VkDevice device, const VkMemoryAllocateInfo & allocate_info); - device_memory(VkDevice device, VkPhysicalDevice physical_device, VkImage target_image, VkMemoryPropertyFlags properties); - - device_memory(VkDevice device, VkPhysicalDevice physical_device, VkBuffer target_buffer, VkMemoryPropertyFlags properties); - - device_memory(const device_memory &) = delete; - device_memory(device_memory &&) = default; - device_memory & operator=(const device_memory &) = delete; - device_memory & operator=(device_memory &&) = default; - ~device_memory(); - - void * data() - { - return map; - } - - void map_memory(); - - static uint32_t get_memory_type(VkPhysicalDevice physical_device, VkMemoryRequirements requirements, VkMemoryPropertyFlags property_flags); -}; -} // namespace vk diff --git a/client/vk/error_category.cpp b/client/vk/error_category.cpp index d6affbc7..e899a4e3 100644 --- a/client/vk/error_category.cpp +++ b/client/vk/error_category.cpp @@ -18,8 +18,9 @@ */ #include "utils/check.h" -#include "vk.h" #include +#include +#include namespace { @@ -32,7 +33,7 @@ struct : std::error_category std::string message(int condition) const override { - return string_VkResult(static_cast(condition)); + return vk::to_string(static_cast(condition)); } } vulkan_error_category; } // namespace diff --git a/client/vk/pipeline.h b/client/vk/pipeline.h index 3b8dac53..a793db94 100644 --- a/client/vk/pipeline.h +++ b/client/vk/pipeline.h @@ -40,7 +40,7 @@ public: std::optional InputAssemblyState; std::optional TessellationState; - vk::PipelineViewportStateCreateInfo ViewportState; + vk::PipelineViewportStateCreateInfo ViewportState; // Automatically filled std::vector Viewports = {}; std::vector Scissors = {}; diff --git a/client/vk/pipeline_layout.cpp b/client/vk/pipeline_layout.cpp deleted file mode 100644 index 47ca3a0e..00000000 --- a/client/vk/pipeline_layout.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * 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 . - */ - -#include "pipeline_layout.h" -#include "utils/check.h" - -vk::pipeline_layout::pipeline_layout(VkDevice device, const info & create_info) : - device(device) -{ - VkPipelineLayoutCreateInfo plci{ - .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, - .setLayoutCount = (uint32_t)create_info.descriptor_set_layouts.size(), - .pSetLayouts = create_info.descriptor_set_layouts.data(), - .pushConstantRangeCount = (uint32_t)create_info.push_constant_ranges.size(), - .pPushConstantRanges = create_info.push_constant_ranges.data()}; - CHECK_VK(vkCreatePipelineLayout(device, &plci, nullptr, &id)); -} - -vk::pipeline_layout::~pipeline_layout() -{ - if (device) - vkDestroyPipelineLayout(device, id, nullptr); -} diff --git a/client/vk/renderpass.cpp b/client/vk/renderpass.cpp deleted file mode 100644 index fecdcd7b..00000000 --- a/client/vk/renderpass.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * 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 . - */ - -#include "renderpass.h" - -#include "vk/vk.h" - -vk::renderpass::renderpass(VkDevice device, info & create_info) : - device(device) -{ - VkRenderPassCreateInfo renderpass_create_info{}; - renderpass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; - renderpass_create_info.attachmentCount = create_info.attachments.size(); - renderpass_create_info.pAttachments = create_info.attachments.data(); - renderpass_create_info.subpassCount = create_info.subpasses.size(); - renderpass_create_info.pSubpasses = create_info.subpasses.data(); - renderpass_create_info.dependencyCount = create_info.dependencies.size(); - renderpass_create_info.pDependencies = create_info.dependencies.data(); - - CHECK_VK(vkCreateRenderPass(device, &renderpass_create_info, nullptr, &id)); -} - -vk::renderpass::~renderpass() -{ - if (device) - vkDestroyRenderPass(device, id, nullptr); -} diff --git a/client/vk/renderpass.h b/client/vk/renderpass.h deleted file mode 100644 index e28c32ae..00000000 --- a/client/vk/renderpass.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * 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 . - */ - -#pragma once - -#include "utils/handle.h" -#include -#include - -namespace vk -{ -class renderpass : public utils::handle -{ - VkDevice device{}; - -public: - struct info - { - std::vector attachments; - std::vector subpasses; - std::vector dependencies; - }; - - renderpass() = default; - renderpass(VkDevice device, info & create_info); - renderpass(const renderpass &) = delete; - renderpass(renderpass &&) = default; - renderpass & operator=(const renderpass &) = delete; - renderpass & operator=(renderpass &&) = default; - ~renderpass(); -}; -} // namespace vk diff --git a/client/vk/shader.cpp b/client/vk/shader.cpp index 64a595c9..1c5ea73d 100644 --- a/client/vk/shader.cpp +++ b/client/vk/shader.cpp @@ -21,9 +21,10 @@ vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::vector & spirv) { - vk::ShaderModuleCreateInfo create_info{}; - create_info.pCode = data(spirv); - create_info.codeSize = spirv.size() * sizeof(uint32_t); + vk::ShaderModuleCreateInfo create_info{ + .codeSize = spirv.size() * sizeof(uint32_t), + .pCode = data(spirv), + }; return vk::raii::ShaderModule{device, create_info}; } diff --git a/client/vk/vk.h b/client/vk/vk.h deleted file mode 100644 index b5b87dbd..00000000 --- a/client/vk/vk.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * 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 . - */ - -#pragma once - -#include "magic_enum.hpp" -#include "utils/check.h" -#include -#include - -#define string_VkFormat(x) std::string(magic_enum::enum_name((VkFormat)(x))) -#define string_VkResult(x) std::string(magic_enum::enum_name((VkResult)(x))) - -template <> -struct magic_enum::customize::enum_range -{ - static constexpr int min = 0; - static constexpr int max = 200; -}; - -template -struct vk_chain -{ - std::tuple structs; -}; diff --git a/client/xr/details/enumerate.h b/client/xr/details/enumerate.h index 56dc803e..a72f1c60 100644 --- a/client/xr/details/enumerate.h +++ b/client/xr/details/enumerate.h @@ -19,7 +19,7 @@ #pragma once -#ifdef XR_USE_PLATFORM_ANDROID +#ifdef __ANDROID__ #include #endif diff --git a/client/xr/swapchain.cpp b/client/xr/swapchain.cpp index 5bf3173e..47497e97 100644 --- a/client/xr/swapchain.cpp +++ b/client/xr/swapchain.cpp @@ -19,11 +19,9 @@ #include "swapchain.h" #include "details/enumerate.h" -#include "error.h" #include "session.h" -#include "xr.h" -xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format format, uint32_t width, uint32_t height, int sample_count) +xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format format, int32_t width, int32_t height, int sample_count) { assert(sample_count == 1); @@ -54,19 +52,19 @@ xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format f { images_[i].image = array[i].image; - vk::ImageViewCreateInfo iv_create_info; - iv_create_info.image = array[i].image; - iv_create_info.viewType = vk::ImageViewType::e2D; - iv_create_info.format = format; - iv_create_info.components.r = vk::ComponentSwizzle::eIdentity; - iv_create_info.components.g = vk::ComponentSwizzle::eIdentity; - iv_create_info.components.b = vk::ComponentSwizzle::eIdentity; - iv_create_info.components.a = vk::ComponentSwizzle::eIdentity; - iv_create_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor; - iv_create_info.subresourceRange.baseMipLevel = 0; - iv_create_info.subresourceRange.levelCount = 1; - iv_create_info.subresourceRange.baseArrayLayer = 0; - iv_create_info.subresourceRange.layerCount = 1; + vk::ImageViewCreateInfo iv_create_info{ + .image = array[i].image, + .viewType = vk::ImageViewType::e2D, + .format = format, + .components = {}, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + } + }; images_[i].view = vk::raii::ImageView(device, iv_create_info); } diff --git a/client/xr/swapchain.h b/client/xr/swapchain.h index 4b3e586f..c30d2cdc 100644 --- a/client/xr/swapchain.h +++ b/client/xr/swapchain.h @@ -43,8 +43,8 @@ public: }; private: - uint32_t width_; - uint32_t height_; + int32_t width_; + int32_t height_; int sample_count_; vk::Format format_; @@ -52,21 +52,25 @@ private: public: swapchain() = default; - swapchain(session &, vk::raii::Device& device, vk::Format format, uint32_t width, uint32_t height, int sample_count = 1); + swapchain(session &, vk::raii::Device& device, vk::Format format, int32_t width, int32_t height, int sample_count = 1); swapchain(swapchain &&) = default; swapchain(const swapchain &) = delete; swapchain & operator=(swapchain &&) = default; swapchain & operator=(const swapchain &) = delete; ~swapchain(); - uint32_t width() const + int32_t width() const { return width_; } - uint32_t height() const + int32_t height() const { return height_; } + XrExtent2Di extent() const + { + return { width_, height_ }; + } int sample_count() const { return sample_count_; @@ -74,7 +78,7 @@ public: const std::vector & images() const { return images_; - }; + } std::vector & images() { return images_;