Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Vindicus999
2025-06-07 11:25:22 +00:00
30 changed files with 1354 additions and 3626 deletions
+46 -34
View File
@@ -109,6 +109,9 @@ static void destroy_images(struct wivrn_comp_target * cn)
if (cn->images == nullptr)
return;
if (cn->wivrn_bundle)
cn->wivrn_bundle->device.waitIdle();
cn->psc.status = 1;
cn->psc.status.notify_all();
cn->encoder_threads.clear();
@@ -135,7 +138,9 @@ static void create_encoders(wivrn_comp_target * cn)
to_headset::video_stream_description & desc = cn->desc;
desc.width = cn->width;
desc.height = cn->height;
desc.foveation = cn->cnx.set_foveated_size(desc.width, desc.height);
const auto & hmd = cn->cnx.get_hmd().hmd;
desc.defoveated_width = hmd->views[0].display.w_pixels * 2;
desc.defoveated_height = hmd->views[0].display.h_pixels;
std::map<int, std::vector<std::shared_ptr<video_encoder>>> thread_params;
@@ -316,11 +321,8 @@ static bool comp_wivrn_init_post_vulkan(struct comp_target * ct, uint32_t prefer
U_LOG_E("Failed to create video encoder: %s", e.what());
return false;
}
if (cn->cnx.has_dynamic_foveation())
{
cn->foveation_renderer = std::make_unique<wivrn_foveation_renderer>(*cn->wivrn_bundle, cn->command_pool);
}
cn->cnx.set_foveated_size(cn->c->settings.preferred.width, cn->c->settings.preferred.height);
cn->foveation.emplace(*cn->wivrn_bundle, *cn->cnx.get_hmd().hmd);
return true;
}
@@ -609,7 +611,7 @@ static VkResult comp_wivrn_present(struct comp_target * ct,
#endif
auto & view_info = cn->psc.view_info;
view_info.foveation = cn->cnx.get_foveation_parameters();
view_info.foveation = cn->foveation->get_parameters();
view_info.display_time = cn->cnx.get_offset().to_headset(info.predicted_display_time);
if (view_info.alpha != do_alpha)
cn->pacer.reset();
@@ -651,16 +653,47 @@ static void comp_wivrn_flush(struct comp_target * ct)
r->StartFrameCapture(NULL, NULL);
#endif
vk::CommandBuffer cmd;
// apply foveation for current frame
if (cn->cnx.apply_dynamic_foveation())
// foveation renderer already signaled the semaphore; nothing to do
return;
if (cn->c->base.frame_params.one_projection_layer_fast_path)
{
const auto & data = cn->c->base.layer_accum.layers[0].data;
const auto & hmd = cn->cnx.get_hmd().hmd;
xrt_rect rect[] = {data.proj.v[0].sub.rect, data.proj.v[1].sub.rect};
xrt_fov fov[] = {data.proj.v[0].fov, data.proj.v[1].fov};
cmd = cn->foveation->update_foveation_buffer(
ct->c->nr.distortion.buffer,
data.flip_y,
rect,
fov);
}
else
{
const auto & hmd = cn->cnx.get_hmd().hmd;
xrt_rect rect[] = {
{.extent = {
.w = int(hmd->views[0].display.w_pixels),
.h = int(hmd->views[0].display.h_pixels),
}},
{.extent = {
.w = int(hmd->views[1].display.w_pixels),
.h = int(hmd->views[1].display.h_pixels),
}},
};
cmd = cn->foveation->update_foveation_buffer(
ct->c->nr.distortion.buffer,
false,
rect,
hmd->distortion.fov);
}
struct vk_bundle * vk = get_vk(cn);
vk::Semaphore sem(cn->semaphores.present_complete);
vk::SubmitInfo submit_info{
.commandBufferCount = cmd ? 1u : 0,
.pCommandBuffers = &cmd,
.signalSemaphoreCount = 1,
.pSignalSemaphores = &sem,
};
@@ -753,14 +786,14 @@ static xrt_result_t comp_wivrn_request_refresh_rate(struct comp_target * ct, flo
wivrn_comp_target::~wivrn_comp_target()
{
if (wivrn_bundle)
wivrn_bundle->device.waitIdle();
destroy_images(this);
}
static void comp_wivrn_destroy(struct comp_target * ct)
{
delete (struct wivrn_comp_target *)ct;
auto cn = (struct wivrn_comp_target *)ct;
destroy_images(cn);
cn->self = nullptr;
}
static void comp_wivrn_info_gpu(struct comp_target * ct, int64_t frame_id, int64_t gpu_start_ns, int64_t gpu_end_ns, int64_t when_ns)
@@ -800,27 +833,6 @@ void wivrn_comp_target::set_bitrate(int bitrate_bps)
}
}
void wivrn_comp_target::render_dynamic_foveation(std::array<to_headset::foveation_parameter, 2> foveation)
{
assert(foveation_renderer);
vk::Semaphore sem(semaphores.present_complete);
vk::SubmitInfo submit_info{
.commandBufferCount = 1,
.pCommandBuffers = &*foveation_renderer->cmd_buf,
.signalSemaphoreCount = 1,
.pSignalSemaphores = &sem,
};
foveation_renderer->render_distortion_images(foveation, c->nr.distortion.images, c->nr.distortion.image_views);
{
scoped_lock lock(c->base.vk.queue_mutex);
wivrn_bundle->queue.submit(submit_info);
}
}
void wivrn_comp_target::set_refresh_rate(float refresh_rate_hz)
{
U_LOG_I("Refresh rate change from %.0f to %.0f", desc.fps, refresh_rate_hz);
+2 -3
View File
@@ -78,6 +78,7 @@ struct pseudo_swapchain
struct wivrn_comp_target : public comp_target
{
std::shared_ptr<wivrn_comp_target> self;
to_headset::video_stream_description desc{};
wivrn_pacer pacer;
@@ -98,7 +99,7 @@ struct wivrn_comp_target : public comp_target
std::vector<std::shared_ptr<video_encoder>> encoders;
wivrn::wivrn_session & cnx;
std::unique_ptr<wivrn_foveation_renderer> foveation_renderer = nullptr;
std::optional<wivrn_foveation> foveation;
std::atomic<float> requested_refresh_rate;
@@ -109,8 +110,6 @@ struct wivrn_comp_target : public comp_target
void reset_encoders();
void set_bitrate(int bitrate_bps);
void render_dynamic_foveation(std::array<to_headset::foveation_parameter, 2> foveation);
void set_refresh_rate(float);
};
+287 -210
View File
@@ -1,6 +1,7 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 galister <galister@librevr.org>
* Copyright (C) 2025 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
@@ -17,6 +18,7 @@
*/
#include "render/render_interface.h"
#include "vk/vk_mini_helpers.h"
#include "wivrn_foveation.h"
@@ -29,218 +31,113 @@
#include <array>
#include <cmath>
#include <map>
#include <ranges>
#include <vulkan/vulkan_raii.hpp>
#include <vulkan/vulkan_structs.hpp>
#include <openxr/openxr.h>
extern const std::map<std::string, std::vector<uint32_t>> shaders;
namespace wivrn
bool render_distortion_images_ensure(struct render_resources * r,
struct vk_bundle * vk,
struct xrt_device * xdev,
bool pre_rotate)
{
const uint32_t dispatch_group_count = RENDER_DISTORTION_IMAGE_DIMENSIONS / 8;
struct FoveationParamsPcs
{
float a[2];
float b[2];
float scale[2];
float center[2];
};
static const std::array pool_sizes =
{
vk::DescriptorPoolSize{
.type = vk::DescriptorType::eStorageImage,
.descriptorCount = 4,
}};
static const std::array<vk::DescriptorSetLayoutBinding, 2> layout_bindings{
vk::DescriptorSetLayoutBinding{.binding = 0,
.descriptorType = vk::DescriptorType::eStorageImage,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eCompute},
vk::DescriptorSetLayoutBinding{.binding = 1,
.descriptorType = vk::DescriptorType::eStorageImage,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eCompute},
};
wivrn_foveation_renderer::wivrn_foveation_renderer(wivrn_vk_bundle & vk, vk::raii::CommandPool & cmd_pool) :
vk(vk),
dp(vk.device,
vk::DescriptorPoolCreateInfo{
.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet,
.maxSets = pool_sizes[0].descriptorCount,
.poolSizeCount = pool_sizes.size(),
.pPoolSizes = pool_sizes.data(),
}),
ds_layout(vk.device, vk::DescriptorSetLayoutCreateInfo{.bindingCount = layout_bindings.size(), .pBindings = layout_bindings.data()})
{
cmd_buf = std::move(vk.device.allocateCommandBuffers(
{.commandPool = *cmd_pool,
.commandBufferCount = 1})[0]);
// Pipeline layout
if (r->distortion.buffer == VK_NULL_HANDLE)
{
vk::PushConstantRange push_constant_range{
.stageFlags = vk::ShaderStageFlagBits::eCompute,
.offset = 0,
.size = sizeof(FoveationParamsPcs),
};
layout = vk.device.createPipelineLayout({
.setLayoutCount = 1,
.pSetLayouts = &*ds_layout,
.pushConstantRangeCount = 1,
.pPushConstantRanges = &push_constant_range,
});
return vk_buffer_init(vk,
sizeof(render_compute_distortion_foveation_data),
VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&r->distortion.buffer,
&r->distortion.device_memory);
}
// Pipeline
{
auto & spirv = shaders.at("foveate.comp");
vk::raii::ShaderModule shader(vk.device, {
.codeSize = spirv.size() * sizeof(uint32_t),
.pCode = spirv.data(),
});
float one_over_dim = 1.0 / (RENDER_DISTORTION_IMAGE_DIMENSIONS - 1);
vk::SpecializationMapEntry specMapEntry{
.constantID = 0,
.offset = 0,
.size = sizeof(float),
};
vk::SpecializationInfo specInfo{
.mapEntryCount = 1,
.pMapEntries = &specMapEntry,
.dataSize = sizeof(float),
.pData = &one_over_dim,
};
pipeline = vk::raii::Pipeline(vk.device, nullptr, vk::ComputePipelineCreateInfo{
.stage = {
.stage = vk::ShaderStageFlagBits::eCompute,
.module = *shader,
.pName = "main",
.pSpecializationInfo = &specInfo,
},
.layout = *layout,
});
}
std::array<vk::DescriptorSetLayout, 2> layouts = {*ds_layout, *ds_layout};
auto my_ds = vk.device.allocateDescriptorSets({
.descriptorPool = *dp,
.descriptorSetCount = 2,
.pSetLayouts = layouts.data(),
});
ds = {
my_ds[0].release(),
my_ds[1].release(),
};
return true;
}
void wivrn_foveation_renderer::render_distortion_images(std::array<to_headset::foveation_parameter, 2> foveations, const VkImage * images, const VkImageView * image_views)
void render_distortion_images_fini(struct render_resources * r)
{
cmd_buf.reset();
cmd_buf.begin(vk::CommandBufferBeginInfo{});
// images: left position, right position, left derivate, right derivate
std::array<vk::ImageMemoryBarrier, 4> im_barriers;
im_barriers.fill({
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eMemoryWrite,
.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.newLayout = vk::ImageLayout::eGeneral,
.subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1},
});
for (size_t i = 0; i < im_barriers.size(); ++i)
im_barriers[i].image = vk::Image(images[i]);
cmd_buf.pipelineBarrier(
vk::PipelineStageFlagBits::eTopOfPipe,
vk::PipelineStageFlagBits::eComputeShader,
{},
nullptr,
nullptr,
im_barriers);
// Monado's distortion shader is patched to read red as position and green as derivate
for (int eye = 0; eye < 2; ++eye)
{
// Descriptor set
std::array image_info{
vk::DescriptorImageInfo{
.imageView = vk::ImageView(image_views[eye]),
.imageLayout = vk::ImageLayout::eGeneral,
},
vk::DescriptorImageInfo{
.imageView = vk::ImageView(image_views[eye + 2]),
.imageLayout = vk::ImageLayout::eGeneral,
},
};
vk.device.updateDescriptorSets({
vk::WriteDescriptorSet{
.dstSet = ds[eye],
.dstBinding = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eStorageImage,
.pImageInfo = &image_info[0],
},
vk::WriteDescriptorSet{
.dstSet = ds[eye],
.dstBinding = 1,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eStorageImage,
.pImageInfo = &image_info[1],
},
},
nullptr);
auto foveation = foveations[eye];
FoveationParamsPcs f_params{
.a = {foveation.x.a, foveation.y.a},
.b = {foveation.x.b, foveation.y.b},
.scale = {foveation.x.scale, foveation.y.scale},
.center = {foveation.x.center, foveation.y.center},
};
cmd_buf.bindPipeline(vk::PipelineBindPoint::eCompute, *pipeline);
cmd_buf.bindDescriptorSets(vk::PipelineBindPoint::eCompute, *layout, 0, ds[eye], {});
cmd_buf.pushConstants<FoveationParamsPcs>(*layout, vk::ShaderStageFlagBits::eCompute, 0, f_params);
cmd_buf.dispatch(dispatch_group_count, dispatch_group_count, 1);
}
for (auto & barrier: im_barriers)
{
barrier.srcAccessMask = vk::AccessFlagBits::eMemoryWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eNone;
barrier.oldLayout = vk::ImageLayout::eGeneral;
barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
}
cmd_buf.pipelineBarrier(
vk::PipelineStageFlagBits::eComputeShader,
vk::PipelineStageFlagBits::eBottomOfPipe,
{},
nullptr,
nullptr,
im_barriers);
cmd_buf.end();
auto * vk = r->vk;
D(Buffer, r->distortion.buffer);
DF(Memory, r->distortion.device_memory);
}
xrt_vec2 yaw_pitch(xrt_quat q)
static double foveate(double a, double b, double λ, double c, double x)
{
// In order to save encoding, transmit and decoding time, only a portion of the image is encoded in full resolution.
// on each axis, foveated coordinates are defined by the following formula.
return λ / a * tan(a * x + b) + c;
// a and b are defined such as:
// edges of the image are not moved
// f(-1) = -1
// f( 1) = 1
// the function also enforces pixel ratio 1:1 at fovea
// df⁻¹(x)/dx = 1/scale for x = c
// We then ensure that source and destination pixel grids match by
// rounding to integer pixel ratios: 1:1, 1:2 etc.
// Finally, pixel spans are sorted so that we only have increasing
// ratios going out from the center.
}
static std::tuple<float, float> solve_foveation(float λ, float c)
{
// Compute a and b for the foveation function such that:
// foveate(a, b, scale, c, -1) = -1 (eq. 1)
// foveate(a, b, scale, c, 1) = 1 (eq. 2)
//
// Use eq. 2 to express a as function of b, then replace in eq. 1
// equation that needs to be null is:
auto b = [λ, c](double a) { return atan(a * (1 - c) / λ) - a; };
auto eq = [λ, c](double a) { return atan(a * (1 - c) / λ) + atan(a * (1 + c) / λ) - 2 * a; }; // (eq. 3)
// function starts positive, reaches a maximum then decreases to -∞
double a0 = 0;
// Find a negative value by computing eq(2^n)
double a1 = 1;
while (eq(a1) > 0)
a1 *= 2;
// last computed values for f(a0) and f(a1)
std::optional<double> f_a0;
double f_a1 = eq(a1);
int n = 0;
double a = 0;
while (std::abs(a1 - a0) > 0.0000001 && n++ < 100)
{
if (not f_a0)
{
// use binary search
a = 0.5 * (a0 + a1);
double val = eq(a);
if (val > 0)
{
a0 = a;
f_a0 = val;
}
else
{
a1 = a;
f_a1 = val;
}
}
else
{
// f(a1) is always defined
// when f(a0) is defined, use secant method
a = a1 - f_a1 * (a1 - a0) / (f_a1 - *f_a0);
a0 = a1;
a1 = a;
f_a0 = f_a1;
f_a1 = eq(a);
}
}
return {a, b(a)};
}
static xrt_vec2 yaw_pitch(xrt_quat q)
{
float sine_theta = std::clamp(-2.0f * (q.y * q.z - q.w * q.x), -1.0f, 1.0f);
@@ -258,20 +155,114 @@ xrt_vec2 yaw_pitch(xrt_quat q)
pitch};
}
std::array<xrt_vec2, 2> wivrn_foveation::get_center()
static float angles_to_center(float e, float l, float r)
{
return (e - l) / (r - l) * 2 - 1;
}
void fill_param_2d(
float c,
size_t foveated_dim,
size_t source_dim,
std::vector<uint16_t> & out)
{
float scale = float(foveated_dim) / source_dim;
auto [a, b] = solve_foveation(scale, c);
uint16_t last = 0;
std::vector<uint16_t> left; // index 0: 1:1 ratio, then 2:1 etc.
std::vector<uint16_t> right;
for (size_t i = 1; i < foveated_dim; ++i)
{
double u = (i * 2.) / foveated_dim - 1;
auto f = foveate(a, b, scale, c, u);
uint16_t n = std::clamp<uint16_t>((f * 0.5 + 0.5) * source_dim + 0.5, 0, source_dim);
assert(n > last);
size_t count = n - last;
auto & vec = u < c ? left : right;
if (count > vec.size())
vec.resize(count);
vec[count - 1]++;
last = n;
}
assert(last < source_dim);
size_t count = source_dim - last;
if (count > right.size())
right.resize(count);
right[count - 1]++;
count = std::max(left.size(), right.size());
out.clear();
out.resize(count - left.size());
out.insert(out.end(), left.rbegin(), left.rend());
if (not right.empty())
out.back() += right.front();
if (right.size() > 1)
out.insert(out.end(), right.begin() + 1, right.end());
out.resize(count * 2 - 1);
}
namespace wivrn
{
void wivrn_foveation::compute_params(
xrt_rect src[2],
const xrt_fov fovs[2])
{
std::lock_guard lock(mutex);
std::array<xrt_vec2, 2> uvs;
auto e = yaw_pitch(last_gaze);
for (int i = 0; i < 2; i++)
xrt_vec2 tan_center[2]{};
if (gaze.x != 0 or gaze.y != 0 or gaze.z != 0 or gaze.w != 0)
{
uvs[i].x = (e.x - views[i].fov.angleLeft) / (views[i].fov.angleRight - views[i].fov.angleLeft) * 2 - 1 + center_offset[i].x;
uvs[i].y = (e.y - views[i].fov.angleDown) / (views[i].fov.angleUp - views[i].fov.angleDown) * 2 - 1 + center_offset[i].y;
auto e = yaw_pitch(gaze);
for (size_t i = 0; i < 2; ++i)
{
xrt_quat view_quat{
.x = views[i].pose.orientation.x,
.y = views[i].pose.orientation.y,
.z = views[i].pose.orientation.z,
.w = views[i].pose.orientation.w};
auto view = yaw_pitch(view_quat);
auto converge_angle = std::copysign(std::atan(std::abs(views[i].pose.position.x) / CONVERGENCE_DIST_M), views[i].pose.position.x);
tan_center[i].x = angles_to_center(e.x - view.x - converge_angle, views[i].fov.angleLeft, views[i].fov.angleRight);
tan_center[i].y = angles_to_center(-view.y - e.y, views[i].fov.angleUp, views[i].fov.angleDown);
}
}
return uvs;
for (int i = 0; i < 2; ++i)
{
const auto & fov = fovs[i];
if (foveated_width < src[i].extent.w)
fill_param_2d(tan_center[i].x, foveated_width, src[i].extent.w, params[i].x);
else
params[i].x = {uint16_t(src[i].extent.w)};
if (foveated_height < src[i].extent.h)
fill_param_2d(tan_center[i].y, foveated_height, src[i].extent.h, params[i].y);
else
params[i].y = {uint16_t(src[i].extent.h)};
}
}
wivrn_foveation::wivrn_foveation(wivrn_vk_bundle & bundle, const xrt_hmd_parts & hmd) :
foveated_width(hmd.screens[0].w_pixels / 2),
foveated_height(hmd.screens[0].h_pixels),
command_pool(bundle.device, vk::CommandPoolCreateInfo{.queueFamilyIndex = bundle.queue_family_index}),
cmd(std::move(bundle.device.allocateCommandBuffers({
.commandPool = command_pool,
.commandBufferCount = 1,
})[0])),
host_buffer(
bundle.device,
{
.size = sizeof(render_compute_distortion_foveation_data),
.usage = vk::BufferUsageFlagBits::eTransferSrc,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
})
{
}
void wivrn_foveation::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset)
@@ -308,16 +299,102 @@ void wivrn_foveation::update_tracking(const from_headset::tracking & tracking, c
return;
xrt_quat qgaze = xrt_cast(pose.pose.orientation);
math_quat_unrotate(&qgaze, &head.value(), &last_gaze);
math_quat_unrotate(&qgaze, &head.value(), &gaze);
break;
}
}
void wivrn_foveation::set_initial_parameters(std::array<to_headset::foveation_parameter, 2> p)
std::array<to_headset::foveation_parameter, 2> wivrn_foveation::get_parameters()
{
std::lock_guard lock(mutex);
return params;
}
center_offset[0] = {p[0].x.center, p[0].y.center};
center_offset[1] = {p[1].x.center, p[1].y.center};
static void fill_ubo(
uint32_t * ubo,
const std::vector<uint16_t> & params,
bool flip,
size_t offset,
size_t size,
int count)
{
assert(params.size() % 2 == 1);
const int n_ratio = (params.size() - 1) / 2;
*ubo = offset;
if (flip)
*ubo += size;
for (auto [i, n]: std::ranges::enumerate_view(params))
{
const int n_source = std::abs(n_ratio - int(i)) + 1;
for (size_t j = 0; j < n; ++j)
{
if (flip)
ubo[1] = ubo[0] - n_source;
else
ubo[1] = ubo[0] + n_source;
++ubo;
--count;
}
}
if (count > 0)
std::fill(ubo + 1, ubo + count + 1, *ubo);
}
template <typename T>
static bool operator==(const T & a, const T & b)
{
static_assert(std::has_unique_object_representations_v<T>);
return std::memcmp(&a, &b, sizeof(T)) == 0;
}
bool operator==(const xrt_quat & a, const xrt_quat & b)
{
return a.x == b.x and a.y == b.y and a.z == b.z and a.w == b.w;
}
bool operator==(const xrt_fov & a, const xrt_fov & b)
{
return a.angle_left == b.angle_left and a.angle_right == b.angle_right and a.angle_up == b.angle_up and a.angle_down == b.angle_down;
}
vk::CommandBuffer wivrn_foveation::update_foveation_buffer(
vk::Buffer target,
bool flip_y,
xrt_rect source[2],
xrt_fov fovs[2])
{
if (not target)
return nullptr;
if (target != gpu_buffer)
{
command_pool.reset();
cmd.begin({});
cmd.copyBuffer(host_buffer, target, vk::BufferCopy{.size = sizeof(render_compute_distortion_foveation_data)});
cmd.end();
}
// Check if the last value is still valid
if (last.flip_y == flip_y and last.src[0] == source[0] and last.src[1] == source[1] and last.fovs[0] == fovs[0])
{
std::lock_guard lock(mutex);
if (last.gaze == gaze)
return nullptr;
}
last = {
.gaze = gaze,
.flip_y = flip_y,
.src = {source[0], source[1]},
.fovs = {fovs[0], fovs[1]},
};
compute_params(source, fovs);
auto ubo = (render_compute_distortion_foveation_data *)host_buffer.map();
for (size_t view = 0; view < 2; ++view)
{
fill_ubo(ubo->x + view * RENDER_FOVEATION_BUFFER_DIMENSIONS, params[view].x, false, source[view].offset.w, source[view].extent.w, foveated_width);
fill_ubo(ubo->y + view * RENDER_FOVEATION_BUFFER_DIMENSIONS, params[view].y, flip_y, source[view].offset.h, source[view].extent.h, foveated_height);
}
return cmd;
}
} // namespace wivrn
+38 -24
View File
@@ -1,6 +1,7 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 galister <galister@librevr.org>
* Copyright (C) 2025 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,50 +19,63 @@
#pragma once
#include "vk/allocation.h"
#include "wivrn_packets.h"
#include "xrt/xrt_defines.h"
#include "xrt/xrt_device.h"
#include <vulkan/vulkan_raii.hpp>
struct render_resources;
#define CONVERGENCE_DIST_M 1.5
namespace wivrn
{
struct clock_offset;
struct wivrn_vk_bundle;
// Calculates the center parameter from the received eye tracking data.
class wivrn_foveation
{
std::mutex mutex;
std::array<xrt_vec2, 2> center_offset = {};
const size_t foveated_width; // per eye
const size_t foveated_height;
std::array<from_headset::tracking::view, 2> views = {};
xrt_quat last_gaze = {};
xrt_quat gaze = {};
std::array<to_headset::foveation_parameter, 2> params;
vk::raii::CommandPool command_pool;
vk::raii::CommandBuffer cmd;
buffer_allocation host_buffer;
vk::Buffer gpu_buffer = nullptr;
// parameters used for last computation
struct P
{
xrt_quat gaze = {};
bool flip_y = false;
xrt_rect src[2] = {};
xrt_fov fovs[2] = {};
};
P last;
void compute_params(
xrt_rect src[2],
const xrt_fov fovs[2]);
public:
wivrn_foveation() {}
wivrn_foveation(wivrn_vk_bundle &, const xrt_hmd_parts &);
void set_initial_parameters(std::array<to_headset::foveation_parameter, 2> p);
void update_tracking(const from_headset::tracking &, const clock_offset &);
std::array<xrt_vec2, 2> get_center();
};
std::array<to_headset::foveation_parameter, 2> get_parameters();
// Renders foveation parameters to Monado's distortion images using a compute shader
class wivrn_foveation_renderer
{
wivrn_vk_bundle & vk;
vk::raii::DescriptorPool dp = nullptr;
vk::raii::DescriptorSetLayout ds_layout = nullptr;
vk::raii::PipelineLayout layout = nullptr;
vk::raii::Pipeline pipeline = nullptr;
std::array<vk::DescriptorSet, 2> ds;
public:
wivrn_foveation_renderer(wivrn_vk_bundle & vk, vk::raii::CommandPool & cmd_pool);
vk::raii::CommandBuffer cmd_buf = nullptr;
void render_distortion_images(std::array<to_headset::foveation_parameter, 2> foveation_arr, const VkImage * images, const VkImageView * image_views);
vk::CommandBuffer update_foveation_buffer(
vk::Buffer target,
bool flip_y,
xrt_rect src[2],
xrt_fov fovs[2]);
};
} // namespace wivrn
+1 -179
View File
@@ -28,8 +28,6 @@
#include "utils/method.h"
#include "xrt_cast.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <stdio.h>
#include <openxr/openxr.h>
@@ -39,128 +37,6 @@
namespace wivrn
{
static double foveate(double a, double b, double λ, double c, double x)
{
// In order to save encoding, transmit and decoding time, only a portion of the image is encoded in full resolution.
// on each axis, foveated coordinates are defined by the following formula.
return λ / a * tan(a * x + b) + c;
// a and b are defined such as:
// edges of the image are not moved
// f(-1) = -1
// f( 1) = 1
// the function also enforces pixel ratio 1:1 at fovea
// df⁻¹(x)/dx = 1/scale for x = c
}
static double foveate_lod(double a, double b, double /*λ*/, double /*c*/, double x)
{
// derivate of foveate * scale
// bias it to favor sharper image
return std::max(0., log2(1 / (cos(a * x + b) * cos(a * x + b)) - 0.5));
}
static std::tuple<float, float> solve_foveation(float λ, float c)
{
// Compute a and b for the foveation function such that:
// foveate(a, b, scale, c, -1) = -1 (eq. 1)
// foveate(a, b, scale, c, 1) = 1 (eq. 2)
//
// Use eq. 2 to express a as function of b, then replace in eq. 1
// equation that needs to be null is:
auto b = [λ, c](double a) { return atan(a * (1 - c) / λ) - a; };
auto eq = [λ, c](double a) { return atan(a * (1 - c) / λ) + atan(a * (1 + c) / λ) - 2 * a; }; // (eq. 3)
// function starts positive, reaches a maximum then decreases to -∞
double a0 = 0;
// Find a negative value by computing eq(2^n)
double a1 = 1;
while (eq(a1) > 0)
a1 *= 2;
// last computed values for f(a0) and f(a1)
std::optional<double> f_a0;
double f_a1 = eq(a1);
int n = 0;
double a = 0;
while (std::abs(a1 - a0) > 0.0000001 && n++ < 100)
{
if (not f_a0)
{
// use binary search
a = 0.5 * (a0 + a1);
double val = eq(a);
if (val > 0)
{
a0 = a;
f_a0 = val;
}
else
{
a1 = a;
f_a1 = val;
}
}
else
{
// f(a1) is always defined
// when f(a0) is defined, use secant method
a = a1 - f_a1 * (a1 - a0) / (f_a1 - *f_a0);
a0 = a1;
a1 = a;
f_a0 = f_a1;
f_a1 = eq(a);
}
}
return {a, b(a)};
}
bool wivrn_hmd::wivrn_hmd_compute_distortion(xrt_device * xdev, uint32_t view_index, float u, float v, xrt_uv_triplet * result)
{
// u,v are in the output coordinates (sent to the encoder)
// result is in the input coordinates (from the application)
const auto & param = ((wivrn_hmd *)xdev)->foveation_parameters[view_index];
xrt_vec2 out;
xrt_vec2 lod;
if (param.x.scale < 1)
{
u = 2 * u - 1;
out.x = foveate(param.x.a, param.x.b, param.x.scale, param.x.center, u);
lod.x = foveate_lod(param.x.a, param.x.b, param.x.scale, param.x.center, u);
out.x = std::clamp<float>((1 + out.x) / 2, 0, 1);
}
else
{
out.x = u;
lod.x = 0;
}
if (param.y.scale < 1)
{
v = 2 * v - 1;
out.y = foveate(param.y.a, param.y.b, param.y.scale, param.y.center, v);
lod.y = foveate_lod(param.y.a, param.y.b, param.y.scale, param.y.center, v);
out.y = std::clamp<float>((1 + out.y) / 2, 0, 1);
}
else
{
out.y = v;
lod.y = 0;
}
U_LOG_D("distortion parameters: %f %f (%f %f)", lod.x, lod.y, u, v);
result->r = out;
result->g = lod;
result->b = out;
return true;
}
xrt_result_t wivrn_hmd::get_visibility_mask(xrt_visibility_mask_type type, uint32_t view_index, xrt_visibility_mask ** mask)
{
static_assert(sizeof(uint32_t) == sizeof(decltype(from_headset::visibility_mask_changed::mask::indices)::value_type));
@@ -318,14 +194,10 @@ xrt_result_t wivrn_hmd::get_battery_status(bool * out_present,
return XRT_SUCCESS;
}
decltype(wivrn_hmd::foveation_parameters) wivrn_hmd::set_foveated_size(uint32_t width, uint32_t height)
void wivrn_hmd::set_foveated_size(uint32_t width, uint32_t height)
{
assert(width % 2 == 0);
uint32_t eye_width = width / 2;
std::array<double, 2> scale{
double(eye_width) / hmd->views[0].display.w_pixels,
double(height) / hmd->views[0].display.h_pixels,
};
hmd->screens[0].w_pixels = width;
hmd->screens[0].h_pixels = height;
@@ -338,56 +210,6 @@ decltype(wivrn_hmd::foveation_parameters) wivrn_hmd::set_foveated_size(uint32_t
view.viewport.w_pixels = eye_width;
view.viewport.h_pixels = height;
foveation_parameters[i].x.scale = scale[0];
foveation_parameters[i].y.scale = scale[1];
const auto & fov = hmd->distortion.fov[i];
float l = tan(fov.angle_left);
float r = tan(fov.angle_right);
float t = tan(fov.angle_up);
float b = tan(fov.angle_down);
if (scale[0] < 1)
{
float cu = (r + l) / (l - r);
foveation_parameters[i].x.center = cu;
std::tie(foveation_parameters[i].x.a, foveation_parameters[i].x.b) = solve_foveation(scale[0], cu);
}
if (scale[1] < 1)
{
float cv = (t + b) / (t - b);
foveation_parameters[i].y.center = cv;
std::tie(foveation_parameters[i].y.a, foveation_parameters[i].y.b) = solve_foveation(scale[1], cv);
}
}
// Distortion information
compute_distortion = wivrn_hmd_compute_distortion;
hmd->distortion.models = XRT_DISTORTION_MODEL_COMPUTE;
hmd->distortion.preferred = XRT_DISTORTION_MODEL_COMPUTE;
return foveation_parameters;
}
void wivrn_hmd::set_foveation_center(std::array<xrt_vec2, 2> center)
{
for (int i = 0; i < 2; ++i)
{
foveation_parameters[i].x.center = center[i].x;
foveation_parameters[i].y.center = center[i].y;
if (foveation_parameters[i].x.scale < 1)
{
std::tie(foveation_parameters[i].x.a, foveation_parameters[i].x.b) =
solve_foveation(foveation_parameters[i].x.scale, foveation_parameters[i].x.center);
}
if (foveation_parameters[i].y.scale < 1)
{
std::tie(foveation_parameters[i].y.a, foveation_parameters[i].y.b) =
solve_foveation(foveation_parameters[i].y.scale, foveation_parameters[i].y.center);
}
}
}
+2 -12
View File
@@ -44,15 +44,12 @@ class wivrn_hmd : public xrt_device
xrt_hmd_parts hmd_parts{};
view_list views;
std::array<to_headset::foveation_parameter, 2> foveation_parameters{};
from_headset::battery battery{};
thread_safe<std::array<std::optional<from_headset::visibility_mask_changed::masks>, 2>> visibility_mask;
wivrn::wivrn_session * cnx;
static bool wivrn_hmd_compute_distortion(xrt_device * xdev, uint32_t view_index, float u, float v, xrt_uv_triplet * result);
xrt_result_t get_visibility_mask(xrt_visibility_mask_type, uint32_t view_index, xrt_visibility_mask **);
public:
@@ -69,6 +66,8 @@ public:
wivrn_hmd(wivrn::wivrn_session * cnx,
const from_headset::headset_info_packet & info);
void set_foveated_size(uint32_t width, uint32_t height);
xrt_result_t get_tracked_pose(xrt_input_name name, int64_t at_timestamp_ns, xrt_space_relation *);
void get_view_poses(const xrt_vec3 * default_eye_relation,
int64_t at_timestamp_ns,
@@ -82,15 +81,6 @@ public:
void update_battery(const from_headset::battery &);
void update_tracking(const from_headset::tracking &, const clock_offset &);
decltype(foveation_parameters) set_foveated_size(uint32_t width, uint32_t height);
void set_foveation_center(std::array<xrt_vec2, 2> center);
std::array<to_headset::foveation_parameter, 2> get_foveation_parameters()
{
return foveation_parameters;
}
void update_visibility_mask(const from_headset::visibility_mask_changed &);
};
} // namespace wivrn
+9 -30
View File
@@ -20,7 +20,6 @@
#include "wivrn_session.h"
#include "accept_connection.h"
#include "configuration.h"
#include "driver/app_pacer.h"
#include "main/comp_compositor.h"
#include "main/comp_main_interface.h"
@@ -35,20 +34,19 @@
#include "wivrn_config.h"
#include "wivrn_eye_tracker.h"
#include "wivrn_fb_face2_tracker.h"
#include "wivrn_foveation.h"
#include "wivrn_htc_face_tracker.h"
#include "wivrn_ipc.h"
#include "wivrn_packets.h"
#include "xrt/xrt_device.h"
#include "xrt/xrt_session.h"
#include <cmath>
#include <magic_enum.hpp>
#include <stdexcept>
#include <string.h>
#include <vulkan/vulkan.h>
#if WIVRN_FEATURE_STEAMVR_LIGHTHOUSE
#include "configuration.h"
#include "steamvr_lh_interface.h"
#endif
@@ -88,8 +86,9 @@ struct wivrn_comp_target_factory : public comp_target_factory
static bool create_target(const struct comp_target_factory * ctf, struct comp_compositor * c, struct comp_target ** out_ct)
{
auto self = (wivrn_comp_target_factory *)ctf;
self->session.comp_target = new wivrn_comp_target(self->session, c);
*out_ct = self->session.comp_target;
self->session.comp_target = std::make_shared<wivrn_comp_target>(self->session, c);
self->session.comp_target->self = self->session.comp_target;
*out_ct = self->session.comp_target.get();
return true;
}
};
@@ -198,7 +197,6 @@ wivrn::wivrn_session::wivrn_session(std::unique_ptr<wivrn_connection> connection
if (get_info().eye_gaze || is_forced_extension("EXT_eye_gaze_interaction"))
{
eye_tracker = std::make_unique<wivrn_eye_tracker>(&hmd);
foveation = std::make_unique<wivrn_foveation>();
static_roles.eyes = eye_tracker.get();
xdevs[xdev_count++] = eye_tracker.get();
}
@@ -408,8 +406,9 @@ void wivrn_session::operator()(const from_headset::tracking & tracking)
right_hand.update_tracking(tracking, offset);
if (eye_tracker)
eye_tracker->update_tracking(tracking, offset);
if (foveation)
foveation->update_tracking(tracking, offset);
assert(comp_target);
assert(comp_target->foveation);
comp_target->foveation->update_tracking(tracking, offset);
if (fb_face2_tracker)
fb_face2_tracker->update_tracking(tracking, offset);
@@ -620,29 +619,9 @@ xrt_result_t wivrn_session::push_event(const xrt_session_event & event)
return xrt_session_event_sink_push(&xrt_system.broadcast, &event);
}
std::array<to_headset::foveation_parameter, 2> wivrn_session::set_foveated_size(uint32_t width, uint32_t height)
void wivrn_session::set_foveated_size(uint32_t width, uint32_t height)
{
auto p = hmd.set_foveated_size(width, height);
if (foveation)
foveation->set_initial_parameters(p);
return p;
}
bool wivrn_session::apply_dynamic_foveation()
{
if (!foveation)
return false;
hmd.set_foveation_center(foveation->get_center());
comp_target->render_dynamic_foveation(hmd.get_foveation_parameters());
return true;
}
std::array<to_headset::foveation_parameter, 2> wivrn_session::get_foveation_parameters()
{
return hmd.get_foveation_parameters();
hmd.set_foveated_size(width, height);
}
void wivrn_session::dump_time(const std::string & event, uint64_t frame, int64_t time, uint8_t stream, const char * extra)
+7 -11
View File
@@ -44,8 +44,6 @@ namespace wivrn
class wivrn_eye_tracker;
class wivrn_fb_face2_tracker;
class wivrn_htc_face_tracker;
class wivrn_foveation;
class wivrn_foveation_renderer;
struct audio_device;
struct wivrn_comp_target;
struct wivrn_comp_target_factory;
@@ -109,8 +107,7 @@ class wivrn_session : public xrt_system_devices
std::unique_ptr<wivrn_eye_tracker> eye_tracker;
std::unique_ptr<wivrn_fb_face2_tracker> fb_face2_tracker;
std::unique_ptr<wivrn_htc_face_tracker> htc_face_tracker;
std::unique_ptr<wivrn_foveation> foveation;
wivrn_comp_target * comp_target;
std::shared_ptr<wivrn_comp_target> comp_target;
clock_offset_estimator offset_est;
@@ -143,6 +140,11 @@ public:
return connection->info();
};
wivrn_hmd & get_hmd()
{
return hmd;
}
void add_predict_offset(std::chrono::nanoseconds off)
{
tracking_control.add(off);
@@ -185,13 +187,7 @@ public:
xrt_result_t push_event(const xrt_session_event &);
std::array<to_headset::foveation_parameter, 2> set_foveated_size(uint32_t width, uint32_t height);
std::array<to_headset::foveation_parameter, 2> get_foveation_parameters();
bool apply_dynamic_foveation();
bool has_dynamic_foveation()
{
return (bool)foveation;
}
void set_foveated_size(uint32_t width, uint32_t height);
void dump_time(const std::string & event, uint64_t frame, int64_t time, uint8_t stream = -1, const char * extra = "");