Add rendering engine

This commit is contained in:
Guillaume Meunier
2024-01-28 11:33:32 +01:00
parent 814663beae
commit 95d1020559
45 changed files with 4170 additions and 1863 deletions
+407
View File
@@ -0,0 +1,407 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "input_profile.h"
#include "application.h"
#include "asset.h"
#include <cstddef>
#include <magic_enum.hpp>
#include <simdjson.h>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <map>
#include <glm/gtc/quaternion.hpp>
namespace
{
// clang-format off
const std::unordered_map<std::string, std::string> 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<std::pair<std::string, scene_data>> models;
std::vector<json_visual_response> 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<std::pair<glm::vec3, glm::quat>> 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<input_profile::node_state_transform, input_profile::node_state_transform> 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<float> 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);
}
}
}
+66
View File
@@ -0,0 +1,66 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <filesystem>
#include <render/scene_data.h>
#include <openxr/openxr.h>
#include <glm/glm.hpp>
struct input_profile
{
struct node_state_transform
{
glm::vec3 position;
glm::quat orientation;
};
struct node_state_visibility
{
};
using node_state = std::variant<std::pair<node_state_transform, node_state_transform>, 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<visual_response> responses;
std::vector<std::pair<XrSpace, scene_object_handle>> 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);
};
+144 -296
View File
@@ -1,7 +1,7 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
* Copyright (C) 2022-2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022-2024 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
@@ -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 <cstdint>
#include <glm/gtc/quaternion.hpp>
#include <string>
#include <magic_enum.hpp>
#include <spdlog/spdlog.h>
#include <string>
#include <utils/ranges.h>
#include <vulkan/vulkan_enums.hpp>
#include <vulkan/vulkan_raii.hpp>
@@ -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<wivrn_session> connect_to_session(const std::vector<wivrn_discover::service>& services)
std::unique_ptr<wivrn_session> connect_to_session(const std::vector<wivrn_discover::service> & 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<wivrn_session> connect_to_session(const std::vector<wivrn_discov
continue;
int port = service.port;
for(const auto& address: service.addresses)
for (const auto & address: service.addresses)
{
try
{
return std::visit([port](auto& address){
return std::visit([port](auto & address) {
return std::make_unique<wivrn_session>(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<wivrn_session> connect_to_session(const std::vector<wivrn_discov
return {};
}
static glm::mat4 projection_matrix(XrFovf fov, float zn = 0.1)
{
float r = tan(fov.angleRight);
float l = tan(fov.angleLeft);
float t = tan(fov.angleUp);
float b = tan(fov.angleDown);
// clang-format off
return glm::mat4{
{ 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
}
static glm::mat4 view_matrix(XrPosef pose)
{
XrQuaternionf q = pose.orientation;
XrVector3f pos = pose.position;
glm::mat4 inv_view_matrix = glm::mat4_cast(glm::quat(q.w, q.x, q.y, q.z));
inv_view_matrix = glm::translate(glm::mat4(1), glm::vec3(pos.x, pos.y, pos.z)) * inv_view_matrix;
return glm::inverse(inv_view_matrix);
}
void scenes::lobby::render()
{
if (next_scene && !next_scene->alive())
@@ -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<XrCompositionLayerProjectionView> 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<XrCompositionLayerProjectionView> layer_view;
std::vector<scene_renderer::frame_info> 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<XrCompositionLayerBaseHeader *>(&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<glm::mat4>(*layout, vk::ShaderStageFlagBits::eVertex, 0, mvp);
command_buffer.draw(6, 1, 0, 0);
command_buffer.endRenderPass();
}
void scenes::lobby::on_focused()
+19 -16
View File
@@ -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<std::vector<image_data>> images_data;
// std::vector<std::vector<image_data>> images_data;
std::optional<wivrn_discover> discover;
std::vector<vk::DeviceMemory> model_memory;
std::vector<vk::Buffer> model_buffers;
std::vector<vk::Image> model_images;
// std::vector<vk::DeviceMemory> model_memory;
// std::vector<vk::Buffer> model_buffers;
// std::vector<vk::Image> model_images;
void load_model(const std::string & filename);
// void load_model(const std::string & filename);
std::shared_ptr<stream> next_scene;
// scene_renderer renderer;
std::optional<scene_renderer> renderer;
scene_data teapot;
std::optional<input_profile> input;
void rasterize_status_string();
+5 -4
View File
@@ -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<vk::Image> 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