Rewrite foveation to enforce pixel alignment

foveation now uses integer pixel ratios, and tries to follow the
previous tangent function.
This commit is contained in:
Patrick Nicolas
2025-06-06 20:04:40 +02:00
parent aef8efba8a
commit 64b446c0d8
24 changed files with 1291 additions and 700 deletions
+281 -192
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,200 +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 = 2,
}};
static const std::array<vk::DescriptorSetLayoutBinding, 2> layout_bindings{
vk::DescriptorSetLayoutBinding{.binding = 0,
.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
vk::DescriptorImageInfo image_info{
.imageView = vk::ImageView(image_views[eye]),
.imageLayout = vk::ImageLayout::eGeneral,
};
vk.device.updateDescriptorSets(
vk::WriteDescriptorSet{
.dstSet = ds[eye],
.dstBinding = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eStorageImage,
.pImageInfo = &image_info,
},
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);
@@ -240,20 +155,108 @@ xrt_vec2 yaw_pitch(xrt_quat q)
pitch};
}
std::array<xrt_vec2, 2> wivrn_foveation::get_center()
void fill_param_2d(
float angle_min,
float angle_max,
size_t foveated_dim,
size_t source_dim,
std::vector<uint16_t> & out)
{
float scale = float(foveated_dim) / source_dim;
const float l = tan(angle_min);
const float r = tan(angle_max);
// FIXME: use tan_center
float c = (r + l) / (l - r);
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{};
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)
{
(void)e;
// TODO: implement
// 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;
}
}
return uvs;
for (int i = 0; i < 2; ++i)
{
const auto & fov = fovs[i];
if (foveated_width < src[i].extent.w)
fill_param_2d(fov.angle_left, fov.angle_right, 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(fov.angle_up, fov.angle_down, 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)
@@ -290,16 +293,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