Move client/src/* to client/*
This commit is contained in:
@@ -0,0 +1,413 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "lobby.h"
|
||||
#include "glm/glm.hpp"
|
||||
#include "render/text_rasterizer.h"
|
||||
#include "stream.h"
|
||||
#include "utils/ranges.h"
|
||||
#include "utils/strings.h"
|
||||
#include "vk/vk.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <glm/gtc/quaternion.hpp>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <tiny_gltf.h>
|
||||
|
||||
scenes::lobby::~lobby() {}
|
||||
|
||||
scenes::lobby::lobby() :
|
||||
status_string_rasterizer(device, physical_device, commandpool, queue), discover("_wivrn._tcp.local."), renderer(device, physical_device, queue)
|
||||
{
|
||||
// renderer.load_gltf("Lobby.gltf");
|
||||
|
||||
uint32_t width = swapchains[0].width();
|
||||
uint32_t height = swapchains[0].height();
|
||||
|
||||
// Create renderpass
|
||||
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
|
||||
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
|
||||
.format = swapchains[0].format(),
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
|
||||
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.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);
|
||||
|
||||
VkSamplerCreateInfo sampler_info{
|
||||
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
|
||||
.magFilter = VK_FILTER_LINEAR,
|
||||
.minFilter = VK_FILTER_LINEAR,
|
||||
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
|
||||
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.mipLodBias = 0.0f,
|
||||
.anisotropyEnable = VK_FALSE,
|
||||
.maxAnisotropy = 1,
|
||||
.compareEnable = VK_FALSE,
|
||||
.compareOp = VK_COMPARE_OP_NEVER,
|
||||
.minLod = 0.0f,
|
||||
.maxLod = 0.0f,
|
||||
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
|
||||
.unnormalizedCoordinates = VK_FALSE,
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &status_string_sampler));
|
||||
|
||||
// Create VkDescriptorSetLayout
|
||||
VkDescriptorSetLayoutBinding layout_binding{
|
||||
.binding = 0,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
};
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layout_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = 1,
|
||||
.pBindings = &layout_binding,
|
||||
};
|
||||
|
||||
CHECK_VK(
|
||||
vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &status_string_image_descriptor_set_layout));
|
||||
|
||||
VkDescriptorPoolSize status_string_image_descriptor_set_pool_size{
|
||||
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1,
|
||||
};
|
||||
|
||||
VkDescriptorPoolCreateInfo pool_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.flags = 0,
|
||||
.maxSets = 1,
|
||||
.poolSizeCount = 1,
|
||||
.pPoolSizes = &status_string_image_descriptor_set_pool_size,
|
||||
};
|
||||
CHECK_VK(vkCreateDescriptorPool(device, &pool_info, nullptr, &status_string_descriptor_pool));
|
||||
|
||||
VkDescriptorSetAllocateInfo ds_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = status_string_descriptor_pool,
|
||||
.descriptorSetCount = 1,
|
||||
.pSetLayouts = &status_string_image_descriptor_set_layout,
|
||||
};
|
||||
CHECK_VK(vkAllocateDescriptorSets(device, &ds_info, &status_string_image_descriptor_set));
|
||||
|
||||
// Create graphics pipeline
|
||||
vk::shader vertex_shader(device, "text.vert");
|
||||
vk::shader fragment_shader(device, "text.frag");
|
||||
|
||||
vk::pipeline::graphics_info pipeline_info;
|
||||
|
||||
pipeline_info.shader_stages.resize(2);
|
||||
|
||||
pipeline_info.shader_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
|
||||
pipeline_info.shader_stages[0].module = vertex_shader;
|
||||
pipeline_info.shader_stages[0].pName = "main";
|
||||
|
||||
pipeline_info.shader_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
pipeline_info.shader_stages[1].module = fragment_shader;
|
||||
pipeline_info.shader_stages[1].pName = "main";
|
||||
|
||||
pipeline_info.InputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||||
|
||||
pipeline_info.viewports.push_back(VkViewport{0, 0, (float)width, (float)height, 0.0f, 1.0f});
|
||||
|
||||
pipeline_info.scissors.push_back(VkRect2D{{0, 0}, {width, height}});
|
||||
|
||||
pipeline_info.RasterizationState.polygonMode = VK_POLYGON_MODE_FILL;
|
||||
pipeline_info.RasterizationState.lineWidth = 1;
|
||||
|
||||
pipeline_info.MultisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
|
||||
|
||||
VkPipelineColorBlendAttachmentState pcbas{};
|
||||
pcbas.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT;
|
||||
|
||||
pipeline_info.ColorBlendState.attachmentCount = 1;
|
||||
pipeline_info.ColorBlendState.pAttachments = &pcbas;
|
||||
|
||||
pipeline_info.renderPass = renderpass;
|
||||
pipeline_info.subpass = 0;
|
||||
layout = vk::pipeline_layout(
|
||||
device, {.descriptor_set_layouts = {status_string_image_descriptor_set_layout}, .push_constant_ranges = {VkPushConstantRange{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .offset = 0, .size = sizeof(glm::mat4)}}});
|
||||
pipeline = vk::pipeline(device, pipeline_info, layout);
|
||||
|
||||
images_data.resize(swapchains.size());
|
||||
for (size_t i = 0; i < swapchains.size(); i++)
|
||||
{
|
||||
auto & images = swapchains[i].images();
|
||||
images_data[i].resize(images.size());
|
||||
|
||||
for (size_t j = 0; j < images.size(); j++)
|
||||
{
|
||||
VkFramebufferCreateInfo fb_create_info{};
|
||||
fb_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
||||
fb_create_info.renderPass = renderpass;
|
||||
fb_create_info.attachmentCount = 1;
|
||||
fb_create_info.pAttachments = &images[j].view;
|
||||
fb_create_info.width = swapchains[i].width();
|
||||
fb_create_info.height = swapchains[i].height();
|
||||
fb_create_info.layers = 1;
|
||||
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &images_data[i][j].framebuffer));
|
||||
|
||||
images_data[i][j].render_finished = create_semaphore();
|
||||
}
|
||||
}
|
||||
|
||||
command_buffer = commandpool.allocate_command_buffer();
|
||||
fence = create_fence(false);
|
||||
}
|
||||
|
||||
void scenes::lobby::rasterize_status_string()
|
||||
{
|
||||
if (status_string_image_view)
|
||||
vkDestroyImageView(device, status_string_image_view, nullptr);
|
||||
|
||||
status_string_rasterized_text = status_string_rasterizer.render(status_string);
|
||||
|
||||
assert(status_string_rasterized_text.image != VK_NULL_HANDLE);
|
||||
assert(status_string_rasterized_text.memory != VK_NULL_HANDLE);
|
||||
|
||||
VkImageViewCreateInfo iv_info{.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.image = status_string_rasterized_text.image,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = status_string_rasterized_text.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}};
|
||||
|
||||
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &status_string_image_view));
|
||||
|
||||
VkDescriptorImageInfo image_info{
|
||||
.sampler = status_string_sampler,
|
||||
.imageView = status_string_image_view,
|
||||
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
};
|
||||
|
||||
VkWriteDescriptorSet descriptor_write{
|
||||
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
|
||||
.dstSet = status_string_image_descriptor_set,
|
||||
.dstBinding = 0,
|
||||
.dstArrayElement = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.pImageInfo = &image_info,
|
||||
};
|
||||
|
||||
vkUpdateDescriptorSets(device, 1, &descriptor_write, 0, nullptr);
|
||||
|
||||
last_status_string = status_string;
|
||||
}
|
||||
|
||||
std::unique_ptr<wivrn_session> connect_to_session(const std::vector<wivrn_discover::service>& services)
|
||||
{
|
||||
// TODO: make it asynchronous
|
||||
for(const wivrn_discover::service& service: services)
|
||||
{
|
||||
int port = service.port;
|
||||
for(const auto& address: service.addresses)
|
||||
{
|
||||
try
|
||||
{
|
||||
return std::visit([port](auto& address){
|
||||
return std::make_unique<wivrn_session>(address, port);
|
||||
}, address);
|
||||
}
|
||||
catch(std::exception& e)
|
||||
{
|
||||
spdlog::warn("Cannot connect to {}", service.hostname);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void scenes::lobby::render()
|
||||
{
|
||||
if (next_scene && !next_scene->alive())
|
||||
next_scene.reset();
|
||||
|
||||
if (!next_scene)
|
||||
{
|
||||
auto services = discover.get_services();
|
||||
|
||||
if (auto session = connect_to_session(services))
|
||||
{
|
||||
next_scene = stream::create(std::move(session));
|
||||
}
|
||||
}
|
||||
|
||||
if (next_scene)
|
||||
{
|
||||
if (next_scene->ready())
|
||||
{
|
||||
application::push_scene(next_scene);
|
||||
next_scene.reset();
|
||||
}
|
||||
else
|
||||
{
|
||||
status_string = "Waiting for video stream";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
status_string = "Waiting for connection";
|
||||
}
|
||||
|
||||
if (status_string != last_status_string)
|
||||
rasterize_status_string();
|
||||
|
||||
XrFrameState framestate = session.wait_frame();
|
||||
|
||||
if (!framestate.shouldRender)
|
||||
{
|
||||
session.begin_frame();
|
||||
session.end_frame(framestate.predictedDisplayTime, {});
|
||||
return;
|
||||
}
|
||||
|
||||
session.begin_frame();
|
||||
|
||||
CHECK_VK(vkResetCommandBuffer(command_buffer, 0));
|
||||
|
||||
VkCommandBufferBeginInfo beginInfo{};
|
||||
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
|
||||
CHECK_VK(vkBeginCommandBuffer(command_buffer, &beginInfo));
|
||||
|
||||
auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space);
|
||||
assert(views.size() == swapchains.size());
|
||||
std::vector<XrCompositionLayerProjectionView> layer_view(views.size());
|
||||
|
||||
for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++)
|
||||
{
|
||||
int image_index = swapchains[swapchain_index].acquire();
|
||||
swapchains[swapchain_index].wait();
|
||||
|
||||
render_view(flags, framestate.predictedDisplayTime, views[swapchain_index], swapchain_index, image_index);
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
CHECK_VK(vkEndCommandBuffer(command_buffer));
|
||||
|
||||
VkSubmitInfo submitInfo{};
|
||||
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
|
||||
submitInfo.commandBufferCount = 1;
|
||||
submitInfo.pCommandBuffers = &command_buffer;
|
||||
|
||||
CHECK_VK(vkQueueSubmit(queue, 1, &submitInfo, fence));
|
||||
|
||||
XrCompositionLayerProjection layer{
|
||||
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
|
||||
.layerFlags = 0,
|
||||
.space = world_space,
|
||||
.viewCount = (uint32_t)layer_view.size(),
|
||||
.views = layer_view.data(),
|
||||
};
|
||||
|
||||
std::vector<XrCompositionLayerBaseHeader *> layers_base;
|
||||
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
|
||||
|
||||
session.end_frame(framestate.predictedDisplayTime, layers_base);
|
||||
|
||||
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX));
|
||||
CHECK_VK(vkResetFences(device, 1, &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];
|
||||
|
||||
VkClearValue clearColor = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
|
||||
|
||||
VkRenderPassBeginInfo renderPassInfo{};
|
||||
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
|
||||
renderPassInfo.renderPass = renderpass;
|
||||
renderPassInfo.framebuffer = data.framebuffer;
|
||||
renderPassInfo.renderArea.offset = {0, 0};
|
||||
renderPassInfo.renderArea.extent = {swapchain.width(), swapchain.height()};
|
||||
renderPassInfo.clearValueCount = 1;
|
||||
renderPassInfo.pClearValues = &clearColor;
|
||||
|
||||
vkCmdBeginRenderPass(command_buffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
||||
|
||||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
|
||||
|
||||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &status_string_image_descriptor_set, 0, nullptr);
|
||||
|
||||
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;
|
||||
vkCmdPushConstants(command_buffer, layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(glm::mat4), &mvp);
|
||||
|
||||
vkCmdDraw(command_buffer, 6, 1, 0, 0);
|
||||
|
||||
vkCmdEndRenderPass(command_buffer);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "scene.h"
|
||||
#include "vk/buffer.h"
|
||||
#include "vk/image.h"
|
||||
#include "vk/renderpass.h"
|
||||
#include "wivrn_client.h"
|
||||
#include "wivrn_discover.h"
|
||||
#include <tiny_gltf.h>
|
||||
|
||||
#include "render/scene_renderer.h"
|
||||
#include "render/text_rasterizer.h"
|
||||
|
||||
namespace scenes
|
||||
{
|
||||
class stream;
|
||||
|
||||
class lobby : public scene
|
||||
{
|
||||
std::string status_string;
|
||||
std::string last_status_string;
|
||||
VkSampler status_string_sampler{};
|
||||
text status_string_rasterized_text;
|
||||
VkImageView status_string_image_view{};
|
||||
VkDescriptorPool status_string_descriptor_pool{};
|
||||
VkDescriptorSetLayout status_string_image_descriptor_set_layout{};
|
||||
VkDescriptorSet status_string_image_descriptor_set{};
|
||||
text_rasterizer status_string_rasterizer;
|
||||
|
||||
vk::renderpass renderpass;
|
||||
vk::pipeline_layout layout;
|
||||
vk::pipeline pipeline;
|
||||
|
||||
VkFence fence{};
|
||||
VkCommandBuffer command_buffer{};
|
||||
|
||||
struct image_data
|
||||
{
|
||||
VkFramebuffer framebuffer{};
|
||||
VkSemaphore render_finished{};
|
||||
};
|
||||
|
||||
std::vector<std::vector<image_data>> images_data;
|
||||
|
||||
wivrn_discover discover;
|
||||
|
||||
tinygltf::Model model;
|
||||
std::vector<vk::device_memory> model_memory;
|
||||
std::vector<vk::buffer> model_buffers;
|
||||
std::vector<vk::image> model_images;
|
||||
|
||||
void load_model(const std::string & filename);
|
||||
|
||||
std::shared_ptr<stream> next_scene;
|
||||
|
||||
scene_renderer renderer;
|
||||
|
||||
void rasterize_status_string();
|
||||
|
||||
public:
|
||||
virtual ~lobby();
|
||||
lobby();
|
||||
|
||||
virtual void render() override;
|
||||
virtual void render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index) override;
|
||||
};
|
||||
} // namespace scenes
|
||||
@@ -0,0 +1,566 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#define GLM_FORCE_RADIANS
|
||||
|
||||
#include "stream.h"
|
||||
|
||||
#include "application.h"
|
||||
#include "decoder/shard_accumulator.h"
|
||||
#include "external/magic_enum.hpp"
|
||||
#include "glm/fwd.hpp"
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "utils/check.h"
|
||||
#include "utils/ranges.h"
|
||||
#include "utils/sync_queue.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/image.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include "xr/details/enumerate.h"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
using namespace xrt::drivers::wivrn;
|
||||
|
||||
// clang-format off
|
||||
static const std::unordered_map<std::string, device_id> device_ids = {
|
||||
{"/user/hand/left/input/x/click", device_id::X_CLICK},
|
||||
{"/user/hand/left/input/x/touch", device_id::X_TOUCH},
|
||||
{"/user/hand/left/input/y/click", device_id::Y_CLICK},
|
||||
{"/user/hand/left/input/y/touch", device_id::Y_TOUCH},
|
||||
{"/user/hand/left/input/menu/click", device_id::MENU_CLICK},
|
||||
{"/user/hand/left/input/squeeze/value", device_id::LEFT_SQUEEZE_VALUE},
|
||||
{"/user/hand/left/input/trigger/value", device_id::LEFT_TRIGGER_VALUE},
|
||||
{"/user/hand/left/input/trigger/touch", device_id::LEFT_TRIGGER_TOUCH},
|
||||
{"/user/hand/left/input/thumbstick", device_id::LEFT_THUMBSTICK_X},
|
||||
{"/user/hand/left/input/thumbstick/click", device_id::LEFT_THUMBSTICK_CLICK},
|
||||
{"/user/hand/left/input/thumbstick/touch", device_id::LEFT_THUMBSTICK_TOUCH},
|
||||
{"/user/hand/left/input/thumbrest/touch", device_id::LEFT_THUMBREST_TOUCH},
|
||||
{"/user/hand/right/input/a/click", device_id::A_CLICK},
|
||||
{"/user/hand/right/input/a/touch", device_id::A_TOUCH},
|
||||
{"/user/hand/right/input/b/click", device_id::B_CLICK},
|
||||
{"/user/hand/right/input/b/touch", device_id::B_TOUCH},
|
||||
{"/user/hand/right/input/system/click", device_id::SYSTEM_CLICK},
|
||||
{"/user/hand/right/input/squeeze/value", device_id::RIGHT_SQUEEZE_VALUE},
|
||||
{"/user/hand/right/input/trigger/value", device_id::RIGHT_TRIGGER_VALUE},
|
||||
{"/user/hand/right/input/trigger/touch", device_id::RIGHT_TRIGGER_TOUCH},
|
||||
{"/user/hand/right/input/thumbstick", device_id::RIGHT_THUMBSTICK_X},
|
||||
{"/user/hand/right/input/thumbstick/click", device_id::RIGHT_THUMBSTICK_CLICK},
|
||||
{"/user/hand/right/input/thumbstick/touch", device_id::RIGHT_THUMBSTICK_TOUCH},
|
||||
{"/user/hand/right/input/thumbrest/touch", device_id::RIGHT_THUMBREST_TOUCH},
|
||||
};
|
||||
// clang-format on
|
||||
|
||||
std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_session> network_session)
|
||||
{
|
||||
std::shared_ptr<stream> self{new stream};
|
||||
|
||||
self->network_session = std::move(network_session);
|
||||
|
||||
from_headset::headset_info_packet info{};
|
||||
|
||||
info.recommended_eye_width = self->swapchains[0].width();
|
||||
info.recommended_eye_height = self->swapchains[0].height();
|
||||
|
||||
if (self->instance.has_extension(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME))
|
||||
{
|
||||
info.available_refresh_rates = self->session.get_refresh_rates();
|
||||
info.preferred_refresh_rate = self->session.get_current_refresh_rate();
|
||||
}
|
||||
|
||||
if (info.available_refresh_rates.empty())
|
||||
spdlog::warn("Unable to detect refresh rates");
|
||||
|
||||
self->network_session->send_control(info);
|
||||
|
||||
self->network_thread = std::thread(&stream::process_packets, self.get());
|
||||
pthread_setname_np(self->network_thread.native_handle(), "network_thread");
|
||||
|
||||
self->video_thread = std::thread(&stream::video, self.get());
|
||||
pthread_setname_np(self->video_thread.native_handle(), "video_thread");
|
||||
|
||||
self->command_buffer = self->commandpool.allocate_command_buffer();
|
||||
self->fence = self->create_fence(false);
|
||||
|
||||
// Look up the XrActions for haptics
|
||||
self->haptics_actions[0].first = application::get_action("/user/hand/left/output/haptic").first;
|
||||
self->haptics_actions[0].second = application::string_to_path("/user/hand/left");
|
||||
|
||||
self->haptics_actions[1].first = application::get_action("/user/hand/right/output/haptic").first;
|
||||
self->haptics_actions[1].second = application::string_to_path("/user/hand/right");
|
||||
|
||||
// Look up the XrActions for input
|
||||
for (const auto & [action, action_type, name]: application::inputs())
|
||||
{
|
||||
auto it = device_ids.find(name);
|
||||
|
||||
if (it == device_ids.end())
|
||||
continue;
|
||||
|
||||
self->input_actions.emplace_back(it->second, action, action_type);
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
scenes::stream::~stream()
|
||||
{
|
||||
cleanup();
|
||||
exiting = true;
|
||||
shard_queue.close();
|
||||
|
||||
video_thread.join();
|
||||
if (tracking_thread)
|
||||
tracking_thread->join();
|
||||
network_thread.join();
|
||||
}
|
||||
|
||||
void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_ptr<shard_accumulator::blit_handle> handle)
|
||||
{
|
||||
std::lock_guard lock(decoder_mutex);
|
||||
|
||||
if (!application::is_visible())
|
||||
return;
|
||||
|
||||
for (auto & i: decoders)
|
||||
{
|
||||
if (i.decoder.get() == decoder)
|
||||
{
|
||||
static_assert(std::tuple_size_v<decltype(i.latest_frames)> == 2);
|
||||
std::swap(i.latest_frames[0], i.latest_frames[1]);
|
||||
i.latest_frames[1] = handle;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!ready_ && std::all_of(decoders.begin(), decoders.end(), [](accumulator_images & i) {
|
||||
return i.latest_frames.back();
|
||||
}))
|
||||
{
|
||||
ready_ = true;
|
||||
first_frame_time = application::now();
|
||||
spdlog::info("Stream scene ready at t={}", first_frame_time);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<uint64_t> scenes::stream::accumulator_images::frames() const
|
||||
{
|
||||
std::vector<uint64_t> result;
|
||||
for (const auto & frame: latest_frames)
|
||||
{
|
||||
if (frame)
|
||||
result.push_back(frame->feedback.frame_index);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<uint64_t> scenes::stream::accumulator_images::common_frame(const std::vector<accumulator_images> & sets)
|
||||
{
|
||||
if (sets.empty())
|
||||
return {};
|
||||
auto common_frames = sets[0].frames();
|
||||
for (const auto & set: sets)
|
||||
{
|
||||
std::vector<uint64_t> tmp;
|
||||
auto x = set.frames();
|
||||
std::set_intersection(
|
||||
x.begin(), x.end(), common_frames.begin(), common_frames.end(), std::back_inserter(tmp));
|
||||
common_frames = tmp;
|
||||
if (common_frames.empty())
|
||||
return {};
|
||||
}
|
||||
assert(not common_frames.empty());
|
||||
return common_frames.back();
|
||||
}
|
||||
|
||||
std::shared_ptr<shard_accumulator::blit_handle> scenes::stream::accumulator_images::frame(std::optional<uint64_t> id)
|
||||
{
|
||||
for (auto it = latest_frames.rbegin(); it != latest_frames.rend(); ++it)
|
||||
{
|
||||
if (not *it)
|
||||
continue;
|
||||
if (id and (*it)->feedback.frame_index != *id)
|
||||
continue;
|
||||
return *it;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void scenes::stream::render()
|
||||
{
|
||||
if (exiting)
|
||||
application::pop_scene();
|
||||
|
||||
XrFrameState framestate = session.wait_frame();
|
||||
// auto t0 = application::now();
|
||||
|
||||
if (decoders.empty())
|
||||
framestate.shouldRender = false;
|
||||
|
||||
if (!framestate.shouldRender)
|
||||
{
|
||||
// TODO: stop/restart video stream
|
||||
session.begin_frame();
|
||||
session.end_frame(framestate.predictedDisplayTime, {});
|
||||
|
||||
std::unique_lock lock(decoder_mutex);
|
||||
for (auto & i: decoders)
|
||||
{
|
||||
for (auto & frame: i.latest_frames)
|
||||
frame.reset();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
session.begin_frame();
|
||||
// auto dt2 = application::now() - t0;
|
||||
|
||||
auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space);
|
||||
assert(views.size() == swapchains.size());
|
||||
|
||||
std::array<int, view_count> image_indices;
|
||||
assert(views.size() == view_count);
|
||||
for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++)
|
||||
{
|
||||
int image_index = swapchains[swapchain_index].acquire();
|
||||
swapchains[swapchain_index].wait();
|
||||
|
||||
image_indices[swapchain_index] = image_index;
|
||||
}
|
||||
|
||||
CHECK_VK(vkResetCommandBuffer(command_buffer, 0));
|
||||
|
||||
VkCommandBufferBeginInfo begin_info{
|
||||
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
|
||||
};
|
||||
CHECK_VK(vkBeginCommandBuffer(command_buffer, &begin_info));
|
||||
|
||||
// Transition the layout of the decoder framebuffer to the one the decoders expect
|
||||
std::vector<VkImageMemoryBarrier> image_barriers;
|
||||
for (size_t i = 0; i < decoder_output.size(); i++)
|
||||
{
|
||||
image_barriers.push_back(VkImageMemoryBarrier{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.srcAccessMask = 0,
|
||||
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
|
||||
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
.newLayout = shard_accumulator::framebuffer_expected_layout,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = decoder_output[i].image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, image_barriers.size(), image_barriers.data());
|
||||
|
||||
// Keep a reference to the resources needed to blit the images until vkWaitForFences
|
||||
std::vector<std::shared_ptr<shard_accumulator::blit_handle>> current_blit_handles;
|
||||
|
||||
std::array<XrPosef, 2> pose = {views[0].pose, views[1].pose};
|
||||
std::array<XrFovf, 2> fov = {views[0].fov, views[1].fov};
|
||||
{
|
||||
std::lock_guard lock(decoder_mutex);
|
||||
// Search for the most recent frame available on all decoders.
|
||||
// If no such frame exists, use the most latest frame for each decoder
|
||||
auto common_frame = accumulator_images::common_frame(decoders);
|
||||
// Blit images from the decoders
|
||||
// TODO be smarter: group blits per eye, so that the framebuffer can use OP_DONT_CARE instead of OP_LOAD and use the same renderpass if possible
|
||||
for (auto & i: decoders)
|
||||
{
|
||||
auto blit_handle = i.frame(common_frame);
|
||||
if (not blit_handle)
|
||||
continue;
|
||||
|
||||
current_blit_handles.push_back(blit_handle);
|
||||
|
||||
blit_handle->feedback.blitted = application::now();
|
||||
blit_handle->feedback.displayed = framestate.predictedDisplayTime;
|
||||
blit_handle->feedback.real_pose[0] = views[0].pose;
|
||||
blit_handle->feedback.real_pose[1] = views[1].pose;
|
||||
|
||||
pose = blit_handle->view_info.pose;
|
||||
fov = blit_handle->view_info.fov;
|
||||
|
||||
send_feedback(blit_handle->feedback);
|
||||
|
||||
int indices[] = {0, 1};
|
||||
i.decoder->blit(command_buffer, *blit_handle, indices); // TODO blit indices no longer needed here
|
||||
}
|
||||
}
|
||||
|
||||
// Transition the output of the decoder to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
|
||||
image_barriers.clear();
|
||||
for (size_t i = 0; i < decoder_output.size(); i++)
|
||||
{
|
||||
image_barriers.push_back(VkImageMemoryBarrier{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
|
||||
.srcAccessMask = 0,
|
||||
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
|
||||
.oldLayout = shard_accumulator::framebuffer_expected_layout,
|
||||
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = decoder_output[i].image,
|
||||
.subresourceRange = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, image_barriers.size(), image_barriers.data());
|
||||
|
||||
// Reproject the image to the real pose
|
||||
for (size_t view = 0; view < view_count; view++)
|
||||
{
|
||||
size_t destination_index = view * swapchains[0].images().size() + image_indices[view];
|
||||
reprojector.reproject(command_buffer, view, destination_index, pose[view].orientation, fov[view], views[view].pose.orientation, views[view].fov);
|
||||
}
|
||||
|
||||
CHECK_VK(vkEndCommandBuffer(command_buffer));
|
||||
VkSubmitInfo submit_info{
|
||||
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
|
||||
.commandBufferCount = 1,
|
||||
.pCommandBuffers = &command_buffer,
|
||||
};
|
||||
CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, fence));
|
||||
// auto dt4 = application::now() - t0;
|
||||
|
||||
std::vector<XrCompositionLayerBaseHeader *> layers_base;
|
||||
std::vector<XrCompositionLayerProjectionView> layer_view;
|
||||
layer_view.resize(views.size());
|
||||
|
||||
for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++)
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
float brightness = std::clamp<float>(dbrightness * (framestate.predictedDisplayTime - first_frame_time) / 1.e9, 0, 1);
|
||||
|
||||
XrCompositionLayerColorScaleBiasKHR color_scale_bias{
|
||||
.type = XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR,
|
||||
.colorScale = {brightness, brightness, brightness, 1},
|
||||
.colorBias = {}};
|
||||
|
||||
XrCompositionLayerProjection layer{
|
||||
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
|
||||
.layerFlags = 0,
|
||||
.space = world_space,
|
||||
.viewCount = (uint32_t)layer_view.size(),
|
||||
.views = layer_view.data(),
|
||||
};
|
||||
|
||||
if (instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME))
|
||||
layer.next = &color_scale_bias;
|
||||
|
||||
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
|
||||
session.end_frame(/*timestamp*/ framestate.predictedDisplayTime, layers_base);
|
||||
|
||||
// auto dt5 = application::now() - t0;
|
||||
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX));
|
||||
CHECK_VK(vkResetFences(device, 1, &fence));
|
||||
|
||||
// We don't need those after vkWaitForFences
|
||||
current_blit_handles.clear();
|
||||
|
||||
// auto dt6 = application::now() - t0;
|
||||
read_actions();
|
||||
|
||||
// spdlog::info("Render timing: begin frame {:.3f}ms, submit commands {:.3f}ms, end frame {:.3f}ms, wait fence {:.3f}ms, predicted display time {:.3f}ms", dt2/1.e6, dt4/1.e6, dt5/1.e6, dt6/1.e6, (framestate.predictedDisplayTime - t0) / 1.e6);
|
||||
}
|
||||
|
||||
void scenes::stream::cleanup()
|
||||
{
|
||||
// Assumes decoder_mutex is locked
|
||||
ready_ = false;
|
||||
decoders.clear();
|
||||
|
||||
for (auto & output: decoder_output)
|
||||
{
|
||||
if (output.image)
|
||||
vkDestroyImage(device, output.image, nullptr);
|
||||
|
||||
if (output.image_view)
|
||||
vkDestroyImageView(device, output.image_view, nullptr);
|
||||
|
||||
if (output.memory)
|
||||
vkFreeMemory(device, output.memory, nullptr);
|
||||
|
||||
output.image = VK_NULL_HANDLE;
|
||||
output.image_view = VK_NULL_HANDLE;
|
||||
output.memory = VK_NULL_HANDLE;
|
||||
}
|
||||
}
|
||||
|
||||
void scenes::stream::setup(const to_headset::video_stream_description & description)
|
||||
{
|
||||
std::unique_lock lock(decoder_mutex);
|
||||
|
||||
cleanup();
|
||||
|
||||
if (description.items.empty())
|
||||
{
|
||||
spdlog::info("Stopping video stream");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create outputs for the decoders
|
||||
const uint32_t width = description.width / view_count;
|
||||
const uint32_t height = description.height;
|
||||
|
||||
VkExtent3D decoder_out_size{width, height, 1};
|
||||
for (size_t i = 0; i < view_count; i++)
|
||||
{
|
||||
decoder_output[i].format = VK_FORMAT_A8B8G8R8_SRGB_PACK32;
|
||||
decoder_output[i].size = {
|
||||
.width = width,
|
||||
.height = height};
|
||||
|
||||
VkImageCreateInfo image_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
|
||||
.flags = 0,
|
||||
.imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32,
|
||||
.extent = decoder_out_size,
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_SAMPLED_BIT | shard_accumulator::framebuffer_usage,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
};
|
||||
|
||||
decoder_output[i].image = vk::image{device, image_info}.release();
|
||||
|
||||
decoder_output[i].memory = vk::device_memory{device, physical_device, decoder_output[i].image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT}.release();
|
||||
|
||||
VkImageViewCreateInfo image_view_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.image = decoder_output[i].image,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32,
|
||||
.components = {}, // IDENTITY by default
|
||||
.subresourceRange = {
|
||||
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1}};
|
||||
|
||||
CHECK_VK(vkCreateImageView(device, &image_view_info, nullptr, &decoder_output[i].image_view));
|
||||
}
|
||||
|
||||
std::vector<shard_accumulator::blit_target> blit_targets;
|
||||
blit_targets.resize(view_count);
|
||||
|
||||
for (size_t i = 0; i < view_count; i++)
|
||||
{
|
||||
blit_targets[i].image = decoder_output[i].image;
|
||||
blit_targets[i].image_view = decoder_output[i].image_view;
|
||||
blit_targets[i].extent = {width, height};
|
||||
blit_targets[i].offset = {static_cast<int>(width * i), 0};
|
||||
}
|
||||
|
||||
for (const auto & [stream_index, item]: utils::enumerate(description.items))
|
||||
{
|
||||
spdlog::info("Creating decoder size {}x{} offset {},{}", item.width, item.height, item.offset_x, item.offset_y);
|
||||
|
||||
accumulator_images dec;
|
||||
dec.decoder = std::make_unique<shard_accumulator>(device, physical_device, item, description.fps, shared_from_this(), stream_index);
|
||||
dec.decoder->set_blit_targets(blit_targets, VK_FORMAT_A8B8G8R8_SRGB_PACK32);
|
||||
|
||||
decoders.push_back(std::move(dec));
|
||||
}
|
||||
|
||||
spdlog::info("Initializing reprojector");
|
||||
VkExtent2D extent = {swapchains[0].width(), swapchains[0].height()};
|
||||
std::vector<VkImage> swapchain_images;
|
||||
for (auto & swapchain: swapchains)
|
||||
{
|
||||
for (auto & image: swapchain.images())
|
||||
swapchain_images.push_back(image.image);
|
||||
}
|
||||
|
||||
std::vector<VkImage> images;
|
||||
for (renderpass_output & i: decoder_output)
|
||||
{
|
||||
images.push_back(i.image);
|
||||
}
|
||||
|
||||
reprojector.init(device, physical_device, images, swapchain_images, extent, swapchains[0].format());
|
||||
}
|
||||
|
||||
void scenes::stream::video()
|
||||
{
|
||||
jni_thread jni;
|
||||
|
||||
while (not exiting)
|
||||
{
|
||||
try
|
||||
{
|
||||
auto shard = shard_queue.pop();
|
||||
|
||||
std::visit(
|
||||
[this](auto & shard) {
|
||||
if (shard.stream_item_idx >= decoders.size())
|
||||
{
|
||||
// We don't know (yet?) about this stream, ignore packet
|
||||
return;
|
||||
}
|
||||
auto idx = shard.stream_item_idx;
|
||||
decoders[idx].decoder->push_shard(std::move(shard));
|
||||
},
|
||||
shard);
|
||||
}
|
||||
catch (utils::sync_queue_closed &)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::error("Exception in video thread: {}", e.what());
|
||||
exiting = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "decoder/shard_accumulator.h"
|
||||
#include "scene.h"
|
||||
#include "stream_reprojection.h"
|
||||
#include "utils/sync_queue.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/renderpass.h"
|
||||
#include "wivrn_client.h"
|
||||
#include "wivrn_packets.h"
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
namespace scenes
|
||||
{
|
||||
class stream : public scene, public std::enable_shared_from_this<stream>
|
||||
{
|
||||
static const size_t view_count = 2;
|
||||
|
||||
using stream_description = xrt::drivers::wivrn::to_headset::video_stream_description::item;
|
||||
|
||||
struct accumulator_images
|
||||
{
|
||||
std::unique_ptr<shard_accumulator> decoder;
|
||||
// latest frames from oldest to most recent
|
||||
std::array<std::shared_ptr<shard_accumulator::blit_handle>, 2> latest_frames;
|
||||
|
||||
static std::optional<uint64_t> common_frame(const std::vector<accumulator_images> &);
|
||||
std::shared_ptr<shard_accumulator::blit_handle> frame(std::optional<uint64_t> id);
|
||||
std::vector<uint64_t> frames() const;
|
||||
};
|
||||
|
||||
struct renderpass_output
|
||||
{
|
||||
VkExtent2D size;
|
||||
VkFormat format;
|
||||
VkImage image;
|
||||
VkDeviceMemory memory;
|
||||
VkImageView image_view;
|
||||
};
|
||||
|
||||
std::unique_ptr<wivrn_session> network_session;
|
||||
std::atomic<bool> exiting = false;
|
||||
std::thread network_thread;
|
||||
std::optional<std::thread> tracking_thread;
|
||||
std::thread video_thread;
|
||||
|
||||
utils::sync_queue<std::variant<to_headset::video_stream_data_shard, to_headset::video_stream_parity_shard>> shard_queue;
|
||||
|
||||
std::mutex decoder_mutex;
|
||||
std::vector<accumulator_images> decoders; // Locked by decoder_mutex
|
||||
|
||||
std::array<renderpass_output, view_count> decoder_output{};
|
||||
|
||||
stream_reprojection reprojector;
|
||||
|
||||
VkFence fence;
|
||||
VkCommandBuffer command_buffer;
|
||||
|
||||
std::array<std::pair<XrAction, XrPath>, 2> haptics_actions;
|
||||
std::vector<std::tuple<device_id, XrAction, XrActionType>> input_actions;
|
||||
|
||||
bool ready_ = false;
|
||||
bool video_started_ = false;
|
||||
XrTime first_frame_time{};
|
||||
const float dbrightness = 2;
|
||||
|
||||
stream() = default;
|
||||
|
||||
public:
|
||||
~stream();
|
||||
|
||||
static std::shared_ptr<stream> create(std::unique_ptr<wivrn_session> session);
|
||||
|
||||
virtual void render() override;
|
||||
|
||||
void operator()(to_headset::video_stream_data_shard &&);
|
||||
void operator()(to_headset::video_stream_parity_shard &&);
|
||||
void operator()(to_headset::haptics &&);
|
||||
void operator()(to_headset::timesync_query &&);
|
||||
void operator()(to_headset::video_stream_description &&);
|
||||
|
||||
VkFormat swapchain_format()
|
||||
{
|
||||
return swapchains[0].format();
|
||||
}
|
||||
|
||||
void push_blit_handle(shard_accumulator * decoder, std::shared_ptr<shard_accumulator::blit_handle> handle);
|
||||
|
||||
void send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback);
|
||||
|
||||
bool ready() const
|
||||
{
|
||||
return ready_;
|
||||
}
|
||||
|
||||
bool alive() const
|
||||
{
|
||||
return !exiting;
|
||||
}
|
||||
|
||||
private:
|
||||
void process_packets();
|
||||
void tracking();
|
||||
void video();
|
||||
void read_actions();
|
||||
|
||||
void setup(const to_headset::video_stream_description &);
|
||||
void cleanup();
|
||||
};
|
||||
} // namespace scenes
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "stream.h"
|
||||
|
||||
void scenes::stream::read_actions()
|
||||
{
|
||||
from_headset::inputs inputs;
|
||||
application::poll_actions();
|
||||
|
||||
for (const auto & [id, action, action_type]: input_actions)
|
||||
{
|
||||
switch (action_type)
|
||||
{
|
||||
case XR_ACTION_TYPE_BOOLEAN_INPUT: {
|
||||
bool value;
|
||||
if (application::read_action(action, value))
|
||||
inputs.values.push_back({id, (float)value});
|
||||
}
|
||||
break;
|
||||
|
||||
case XR_ACTION_TYPE_FLOAT_INPUT: {
|
||||
float value;
|
||||
if (application::read_action(action, value))
|
||||
inputs.values.push_back({id, value});
|
||||
}
|
||||
break;
|
||||
|
||||
case XR_ACTION_TYPE_VECTOR2F_INPUT: {
|
||||
XrVector2f value;
|
||||
if (application::read_action(action, value))
|
||||
{
|
||||
inputs.values.push_back({id, value.x});
|
||||
inputs.values.push_back({(device_id)((int)id + 1), value.y});
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case XR_ACTION_TYPE_POSE_INPUT:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
network_session->send_stream(inputs);
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::warn("Exception while sending inputs packet: {}", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::haptics && haptics)
|
||||
{
|
||||
XrAction action;
|
||||
XrPath subpath;
|
||||
|
||||
if (haptics.id == device_id::LEFT_CONTROLLER_HAPTIC)
|
||||
{
|
||||
action = haptics_actions[0].first;
|
||||
subpath = haptics_actions[0].second;
|
||||
}
|
||||
else if (haptics.id == device_id::RIGHT_CONTROLLER_HAPTIC)
|
||||
{
|
||||
action = haptics_actions[1].first;
|
||||
subpath = haptics_actions[1].second;
|
||||
}
|
||||
else
|
||||
return;
|
||||
|
||||
if (haptics.amplitude > 0)
|
||||
application::haptic_start(action, subpath, haptics.duration.count(), haptics.frequency, haptics.amplitude);
|
||||
else
|
||||
application::haptic_stop(action, subpath);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "stream.h"
|
||||
|
||||
void scenes::stream::process_packets()
|
||||
{
|
||||
while (not exiting)
|
||||
{
|
||||
try
|
||||
{
|
||||
int n = network_session->poll(*this, std::chrono::milliseconds(5000));
|
||||
if (n == 0 && video_started_)
|
||||
throw std::runtime_error("Timeout waiting for network packets");
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::info("Exception in network thread, exiting: {}", e.what());
|
||||
exiting = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::video_stream_data_shard && shard)
|
||||
{
|
||||
video_started_ = true;
|
||||
shard_queue.push(std::move(shard));
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::video_stream_parity_shard && shard)
|
||||
{
|
||||
video_started_ = true;
|
||||
shard_queue.push(std::move(shard));
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::video_stream_description && desc)
|
||||
{
|
||||
setup(desc);
|
||||
|
||||
if (not tracking_thread)
|
||||
{
|
||||
tracking_thread = std::thread(&stream::tracking, this);
|
||||
pthread_setname_np(tracking_thread->native_handle(), "tracking_thread");
|
||||
}
|
||||
}
|
||||
|
||||
void scenes::stream::operator()(to_headset::timesync_query && query)
|
||||
{
|
||||
from_headset::timesync_response response{};
|
||||
response.query = query.query;
|
||||
response.response = instance.now();
|
||||
network_session->send_stream(response);
|
||||
}
|
||||
|
||||
void scenes::stream::send_feedback(const xrt::drivers::wivrn::from_headset::feedback & feedback)
|
||||
{
|
||||
try
|
||||
{
|
||||
network_session->send_control(feedback);
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::warn("Exception while sending feedback packet: {}", e.what());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "stream_reprojection.h"
|
||||
#include "spdlog/spdlog.h"
|
||||
#include "utils/check.h"
|
||||
#include <array>
|
||||
#include <glm/glm.hpp>
|
||||
#include <glm/gtx/quaternion.hpp>
|
||||
#include <vulkan/vulkan_core.h>
|
||||
|
||||
struct stream_reprojection::uniform
|
||||
{
|
||||
alignas(16) glm::mat4 reprojection;
|
||||
};
|
||||
|
||||
stream_reprojection::~stream_reprojection()
|
||||
{
|
||||
cleanup();
|
||||
}
|
||||
|
||||
void stream_reprojection::cleanup()
|
||||
{
|
||||
if (device)
|
||||
{
|
||||
if (descriptor_pool)
|
||||
vkDestroyDescriptorPool(device, descriptor_pool, nullptr);
|
||||
|
||||
if (descriptor_set_layout)
|
||||
vkDestroyDescriptorSetLayout(device, descriptor_set_layout, nullptr);
|
||||
|
||||
for (VkFramebuffer framebuffer: framebuffers)
|
||||
vkDestroyFramebuffer(device, framebuffer, nullptr);
|
||||
|
||||
for (VkImageView image_view: output_image_views)
|
||||
vkDestroyImageView(device, image_view, nullptr);
|
||||
|
||||
for (VkImageView image_view: input_image_views)
|
||||
vkDestroyImageView(device, image_view, nullptr);
|
||||
|
||||
if (sampler)
|
||||
vkDestroySampler(device, sampler, nullptr);
|
||||
|
||||
descriptor_pool = VK_NULL_HANDLE;
|
||||
descriptor_set_layout = VK_NULL_HANDLE;
|
||||
sampler = VK_NULL_HANDLE;
|
||||
framebuffers.clear();
|
||||
output_image_views.clear();
|
||||
input_image_views.clear();
|
||||
ubo.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void stream_reprojection::init(VkDevice device, VkPhysicalDevice physical_device, std::vector<VkImage> input_images_, std::vector<VkImage> output_images_, VkExtent2D extent, VkFormat format)
|
||||
{
|
||||
cleanup();
|
||||
this->device = device;
|
||||
this->physical_device = physical_device,
|
||||
this->input_images = std::move(input_images_);
|
||||
this->output_images = std::move(output_images_);
|
||||
this->extent = extent;
|
||||
this->format = format;
|
||||
|
||||
VkPhysicalDeviceProperties properties;
|
||||
vkGetPhysicalDeviceProperties(physical_device, &properties);
|
||||
|
||||
VkSamplerCreateInfo sampler_info{
|
||||
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
|
||||
.magFilter = VK_FILTER_LINEAR,
|
||||
.minFilter = VK_FILTER_LINEAR,
|
||||
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
|
||||
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER,
|
||||
.mipLodBias = 0.0f,
|
||||
.anisotropyEnable = VK_FALSE,
|
||||
.maxAnisotropy = 1,
|
||||
.compareEnable = VK_FALSE,
|
||||
.compareOp = VK_COMPARE_OP_NEVER,
|
||||
.minLod = 0.0f,
|
||||
.maxLod = 0.0f,
|
||||
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
|
||||
.unnormalizedCoordinates = VK_FALSE,
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &sampler));
|
||||
|
||||
size_t uniform_size = sizeof(uniform) + properties.limits.minUniformBufferOffsetAlignment - 1;
|
||||
uniform_size = uniform_size - uniform_size % properties.limits.minUniformBufferOffsetAlignment;
|
||||
|
||||
VkBufferCreateInfo create_info{
|
||||
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
|
||||
.size = uniform_size * input_images.size(),
|
||||
.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
};
|
||||
buffer = vk::buffer(device, create_info);
|
||||
memory = vk::device_memory(device, physical_device, buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
memory.map_memory();
|
||||
for (size_t i = 0; i < input_images.size(); i++)
|
||||
ubo.push_back(reinterpret_cast<uniform *>(reinterpret_cast<uintptr_t>(memory.data()) + i * uniform_size));
|
||||
|
||||
// Create VkDescriptorSetLayout
|
||||
std::array<VkDescriptorSetLayoutBinding, 2> layout_binding{
|
||||
VkDescriptorSetLayoutBinding{
|
||||
.binding = 0,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
},
|
||||
{
|
||||
.binding = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
||||
.descriptorCount = 1,
|
||||
.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
}};
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layout_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = layout_binding.size(),
|
||||
.pBindings = layout_binding.data(),
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &descriptor_set_layout));
|
||||
|
||||
std::array<VkDescriptorPoolSize, 2> pool_size{VkDescriptorPoolSize{
|
||||
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = (uint32_t)input_images.size(),
|
||||
},
|
||||
VkDescriptorPoolSize{
|
||||
.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
||||
.descriptorCount = (uint32_t)input_images.size(),
|
||||
}};
|
||||
|
||||
VkDescriptorPoolCreateInfo pool_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.flags = 0,
|
||||
.maxSets = (uint32_t)input_images.size(),
|
||||
.poolSizeCount = pool_size.size(),
|
||||
.pPoolSizes = pool_size.data(),
|
||||
};
|
||||
|
||||
CHECK_VK(vkCreateDescriptorPool(device, &pool_info, nullptr, &descriptor_pool));
|
||||
|
||||
// Create image views and descriptor sets
|
||||
input_image_views.reserve(input_images.size());
|
||||
descriptor_sets.reserve(input_images.size());
|
||||
VkDeviceSize offset = 0;
|
||||
for (VkImage image: input_images)
|
||||
{
|
||||
VkImageViewCreateInfo iv_info{
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
|
||||
.image = image,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D,
|
||||
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32,
|
||||
.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));
|
||||
input_image_views.push_back(image_view);
|
||||
|
||||
VkDescriptorSetAllocateInfo ds_info{
|
||||
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = descriptor_pool,
|
||||
.descriptorSetCount = 1,
|
||||
.pSetLayouts = &descriptor_set_layout,
|
||||
};
|
||||
VkDescriptorSet ds;
|
||||
CHECK_VK(vkAllocateDescriptorSets(device, &ds_info, &ds));
|
||||
descriptor_sets.push_back(ds);
|
||||
|
||||
VkDescriptorImageInfo image_info{
|
||||
.sampler = sampler,
|
||||
.imageView = image_view,
|
||||
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
};
|
||||
|
||||
VkDescriptorBufferInfo buffer_info{
|
||||
.buffer = buffer, .offset = offset, .range = sizeof(uniform)};
|
||||
offset += uniform_size;
|
||||
|
||||
std::array<VkWriteDescriptorSet, 2> write{
|
||||
VkWriteDescriptorSet{
|
||||
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
|
||||
.dstSet = ds,
|
||||
.dstBinding = 0,
|
||||
.dstArrayElement = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.pImageInfo = &image_info,
|
||||
},
|
||||
VkWriteDescriptorSet{
|
||||
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
|
||||
.dstSet = ds,
|
||||
.dstBinding = 1,
|
||||
.dstArrayElement = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
|
||||
.pBufferInfo = &buffer_info},
|
||||
};
|
||||
|
||||
vkUpdateDescriptorSets(device, write.size(), write.data(), 0, nullptr);
|
||||
}
|
||||
|
||||
// Create renderpass
|
||||
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
|
||||
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
|
||||
.format = 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 graphics pipeline
|
||||
vk::shader vertex_shader(device, "reprojection.vert");
|
||||
vk::shader fragment_shader(device, "reprojection.frag");
|
||||
|
||||
VkPipelineColorBlendAttachmentState pcbas{.colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
|
||||
VK_COLOR_COMPONENT_G_BIT |
|
||||
VK_COLOR_COMPONENT_B_BIT};
|
||||
|
||||
layout = vk::pipeline_layout(device, {.descriptor_set_layouts = {descriptor_set_layout}});
|
||||
|
||||
vk::pipeline::graphics_info pipeline_info{
|
||||
.shader_stages =
|
||||
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vertex_shader, .pName = "main"},
|
||||
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fragment_shader, .pName = "main"}},
|
||||
.vertex_input_bindings = {},
|
||||
.vertex_input_attributes = {},
|
||||
.InputAssemblyState = {.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP},
|
||||
.viewports = {VkViewport{.x = 0,
|
||||
.y = 0,
|
||||
.width = (float)extent.width,
|
||||
.height = (float)extent.height,
|
||||
.minDepth = 0,
|
||||
.maxDepth = 1}},
|
||||
.scissors = {VkRect2D{
|
||||
.offset = {0, 0},
|
||||
.extent = extent,
|
||||
}},
|
||||
.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,
|
||||
};
|
||||
|
||||
pipeline = vk::pipeline(device, pipeline_info, layout);
|
||||
|
||||
// Create image views and framebuffers
|
||||
output_image_views.reserve(output_images.size());
|
||||
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 = 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 = extent.width,
|
||||
.height = extent.height,
|
||||
.layers = 1,
|
||||
};
|
||||
|
||||
VkFramebuffer framebuffer;
|
||||
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &framebuffer));
|
||||
framebuffers.push_back(framebuffer);
|
||||
}
|
||||
}
|
||||
|
||||
void stream_reprojection::reproject(VkCommandBuffer command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf dest_pose, XrFovf dest_fov)
|
||||
{
|
||||
if (source < 0 || source >= (int)input_images.size())
|
||||
throw std::runtime_error("Invalid source image index");
|
||||
if (destination < 0 || destination >= (int)output_images.size())
|
||||
throw std::runtime_error("Invalid destination image index");
|
||||
|
||||
// Compute the reprojection matrix
|
||||
float zn = 1;
|
||||
float r = tan(dest_fov.angleRight);
|
||||
float l = tan(dest_fov.angleLeft);
|
||||
float t = tan(dest_fov.angleUp);
|
||||
float b = tan(dest_fov.angleDown);
|
||||
|
||||
// clang-format off
|
||||
glm::mat4 hmd_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 }
|
||||
};
|
||||
|
||||
glm::mat4 hmd_unview = glm::mat4_cast(glm::quat(
|
||||
dest_pose.w,
|
||||
dest_pose.x,
|
||||
dest_pose.y,
|
||||
dest_pose.z));
|
||||
|
||||
r = tan(source_fov.angleRight);
|
||||
l = tan(source_fov.angleLeft);
|
||||
t = tan(source_fov.angleUp);
|
||||
b = tan(source_fov.angleDown);
|
||||
|
||||
glm::mat4 video_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 }
|
||||
};
|
||||
|
||||
glm::mat4 video_view = glm::mat4_cast(glm::quat(
|
||||
-source_pose.w,
|
||||
source_pose.x,
|
||||
source_pose.y,
|
||||
source_pose.z));
|
||||
// clang-format on
|
||||
|
||||
ubo[source]->reprojection = video_proj * video_view * hmd_unview * glm::inverse(hmd_proj);
|
||||
|
||||
VkClearValue clear_color{};
|
||||
|
||||
VkRenderPassBeginInfo begin_info{
|
||||
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
|
||||
.renderPass = renderpass,
|
||||
.framebuffer = framebuffers[destination],
|
||||
.renderArea =
|
||||
{
|
||||
.offset = {0, 0},
|
||||
.extent = extent,
|
||||
},
|
||||
.clearValueCount = 1,
|
||||
.pClearValues = &clear_color,
|
||||
};
|
||||
|
||||
vkCmdBeginRenderPass(command_buffer, &begin_info, VK_SUBPASS_CONTENTS_INLINE);
|
||||
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
|
||||
|
||||
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &descriptor_sets[source], 0, nullptr);
|
||||
vkCmdDraw(command_buffer, 3, 1, 0, 0);
|
||||
|
||||
vkCmdEndRenderPass(command_buffer);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "vk/buffer.h"
|
||||
#include "vk/device_memory.h"
|
||||
#include "vk/pipeline.h"
|
||||
#include "vk/pipeline_layout.h"
|
||||
#include "vk/renderpass.h"
|
||||
#include "vk/shader.h"
|
||||
#include <vulkan/vulkan_core.h>
|
||||
#include <openxr/openxr.h>
|
||||
|
||||
class stream_reprojection
|
||||
{
|
||||
struct uniform;
|
||||
|
||||
VkDevice device;
|
||||
VkPhysicalDevice physical_device;
|
||||
|
||||
// Uniform buffer
|
||||
vk::buffer buffer;
|
||||
vk::device_memory memory;
|
||||
std::vector<uniform *> ubo{};
|
||||
|
||||
// Source images
|
||||
VkSampler sampler{};
|
||||
std::vector<VkImage> input_images;
|
||||
std::vector<VkImageView> input_image_views;
|
||||
std::vector<VkDescriptorSet> descriptor_sets;
|
||||
|
||||
// Destination images
|
||||
std::vector<VkImage> output_images;
|
||||
std::vector<VkImageView> output_image_views;
|
||||
std::vector<VkFramebuffer> framebuffers;
|
||||
VkExtent2D extent{};
|
||||
VkFormat format{};
|
||||
|
||||
// Graphic pipeline
|
||||
VkDescriptorSetLayout descriptor_set_layout{};
|
||||
VkDescriptorPool descriptor_pool{};
|
||||
vk::pipeline_layout layout;
|
||||
vk::pipeline pipeline;
|
||||
vk::renderpass renderpass;
|
||||
|
||||
void cleanup();
|
||||
|
||||
public:
|
||||
stream_reprojection() = default;
|
||||
stream_reprojection(const stream_reprojection &) = delete;
|
||||
void init(VkDevice device, VkPhysicalDevice physical_device, std::vector<VkImage> input_images, std::vector<VkImage> output_images, VkExtent2D extent, VkFormat format);
|
||||
|
||||
~stream_reprojection();
|
||||
|
||||
void reproject(VkCommandBuffer command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf destination_pose, XrFovf destination_fov);
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "stream.h"
|
||||
#include "utils/ranges.h"
|
||||
#include <thread>
|
||||
|
||||
static from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpace reference, XrTime time)
|
||||
{
|
||||
XrSpaceVelocity velocity{
|
||||
.type = XR_TYPE_SPACE_VELOCITY};
|
||||
|
||||
XrSpaceLocation location{
|
||||
.type = XR_TYPE_SPACE_LOCATION,
|
||||
.next = &velocity};
|
||||
|
||||
xrLocateSpace(space, reference, time, &location);
|
||||
|
||||
from_headset::tracking::pose res{
|
||||
.device = device,
|
||||
.pose = location.pose,
|
||||
.linear_velocity = velocity.linearVelocity,
|
||||
.angular_velocity = velocity.angularVelocity,
|
||||
.flags = 0,
|
||||
};
|
||||
|
||||
if (location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
|
||||
res.flags |= from_headset::tracking::orientation_valid;
|
||||
|
||||
if (location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT)
|
||||
res.flags |= from_headset::tracking::position_valid;
|
||||
|
||||
if (velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT)
|
||||
res.flags |= from_headset::tracking::linear_velocity_valid;
|
||||
|
||||
if (velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT)
|
||||
res.flags |= from_headset::tracking::angular_velocity_valid;
|
||||
|
||||
if (location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)
|
||||
res.flags |= from_headset::tracking::orientation_tracked;
|
||||
|
||||
if (location.locationFlags & XR_SPACE_LOCATION_POSITION_TRACKED_BIT)
|
||||
res.flags |= from_headset::tracking::position_tracked;
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
void scenes::stream::tracking()
|
||||
{
|
||||
std::vector<std::pair<device_id, XrSpace>> spaces = {
|
||||
{device_id::HEAD, application::view()},
|
||||
{device_id::LEFT_AIM, application::left_aim()},
|
||||
{device_id::LEFT_GRIP, application::left_grip()},
|
||||
{device_id::RIGHT_AIM, application::right_aim()},
|
||||
{device_id::RIGHT_GRIP, application::right_grip()}};
|
||||
|
||||
XrSpace view_space = application::view();
|
||||
const XrDuration tracking_period = 10'000'000; // Send tracking data every 10ms
|
||||
const XrDuration dt = 1'000'000; // Wake up 1ms before measuring the position
|
||||
const XrDuration extrapolation_horizon = 1; // 50'000'000;
|
||||
|
||||
XrTime t0 = instance.now();
|
||||
t0 = t0 - t0 % tracking_period;
|
||||
|
||||
while (not exiting)
|
||||
{
|
||||
try
|
||||
{
|
||||
XrTime now = instance.now();
|
||||
if (now < t0)
|
||||
std::this_thread::sleep_for(std::chrono::nanoseconds(t0 - now - dt));
|
||||
|
||||
for (XrTime Δt = 0; Δt < extrapolation_horizon; Δt += tracking_period)
|
||||
{
|
||||
from_headset::tracking packet{};
|
||||
packet.timestamp = t0 + Δt;
|
||||
|
||||
try
|
||||
{
|
||||
auto [flags, views] = session.locate_views(XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, t0 + Δt, view_space);
|
||||
assert(views.size() == packet.views.size());
|
||||
|
||||
for (auto [i, j]: utils::zip(views, packet.views))
|
||||
{
|
||||
j.pose = i.pose;
|
||||
j.fov = i.fov;
|
||||
}
|
||||
|
||||
packet.flags = flags;
|
||||
|
||||
for (auto [device, space]: spaces)
|
||||
{
|
||||
packet.device_poses.push_back(locate_space(device, space, world_space, t0 + Δt));
|
||||
}
|
||||
|
||||
network_session->send_stream(packet);
|
||||
}
|
||||
catch (const std::system_error & e)
|
||||
{
|
||||
if (e.code().category() != xr::error_category() or
|
||||
e.code().value() != XR_ERROR_TIME_INVALID)
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
t0 += tracking_period;
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::info("Exception in tracking thread, exiting: {}", e.what());
|
||||
exiting = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user