From 8503e3480bab9d8c16712719741e410f635a822d Mon Sep 17 00:00:00 2001 From: galister <22305755+galister@users.noreply.github.com> Date: Sat, 3 Aug 2024 10:27:55 +0900 Subject: [PATCH] eye-tracked foveation --- client/scenes/stream.cpp | 3 + client/scenes/stream_reprojection.cpp | 5 + client/scenes/stream_reprojection.h | 4 +- common/wivrn_packets.h | 26 +- patches/monado/0006-distortion-images.patch | 13 + .../monado/2305-prevent-moire-artefacts.patch | 279 +++++++++++++++ server/CMakeLists.txt | 3 +- server/driver/wivrn_comp_target.cpp | 64 +++- server/driver/wivrn_comp_target.h | 3 + server/driver/wivrn_foveation.cpp | 330 ++++++++++++++++++ server/driver/wivrn_foveation.h | 61 ++++ server/driver/wivrn_hmd.cpp | 21 +- server/driver/wivrn_hmd.h | 8 +- server/driver/wivrn_session.cpp | 29 +- server/driver/wivrn_session.h | 11 +- server/shaders/foveate.comp.glsl | 61 ++++ server/{encoder => }/shaders/yuv.comp.glsl | 0 17 files changed, 888 insertions(+), 33 deletions(-) create mode 100644 patches/monado/0006-distortion-images.patch create mode 100644 patches/monado/2305-prevent-moire-artefacts.patch create mode 100644 server/driver/wivrn_foveation.cpp create mode 100644 server/driver/wivrn_foveation.h create mode 100644 server/shaders/foveate.comp.glsl rename server/{encoder => }/shaders/yuv.comp.glsl (100%) diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 5647d718..a761a3ce 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -543,6 +543,7 @@ void scenes::stream::render(const XrFrameState & frame_state) std::array pose{}; std::array fov{}; + std::array foveation{}; { // Search for frame with desired display time on all decoders // If no such frame exists, use the latest frame for each decoder @@ -562,6 +563,7 @@ void scenes::stream::render(const XrFrameState & frame_state) pose = blit_handle->view_info.pose; fov = blit_handle->view_info.fov; + foveation = blit_handle->view_info.foveation; vk::DescriptorImageInfo image_info{ .imageView = *blit_handle->image_view, @@ -662,6 +664,7 @@ void scenes::stream::render(const XrFrameState & frame_state) } command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1); + reprojector->set_foveation(foveation); // Unfoveate the image to the real pose for (size_t view = 0; view < view_count; view++) diff --git a/client/scenes/stream_reprojection.cpp b/client/scenes/stream_reprojection.cpp index 2a075c1b..16710423 100644 --- a/client/scenes/stream_reprojection.cpp +++ b/client/scenes/stream_reprojection.cpp @@ -433,3 +433,8 @@ void stream_reprojection::reproject(vk::raii::CommandBuffer & command_buffer, in command_buffer.draw(6 * nb_reprojection_vertices * nb_reprojection_vertices, 1, 0, 0); command_buffer.endRenderPass(); } + +void stream_reprojection::set_foveation(std::array foveation) +{ + foveation_parameters = foveation; +} diff --git a/client/scenes/stream_reprojection.h b/client/scenes/stream_reprojection.h index 19b832a7..8204bf5b 100644 --- a/client/scenes/stream_reprojection.h +++ b/client/scenes/stream_reprojection.h @@ -52,7 +52,7 @@ class stream_reprojection vk::Extent2D extent; // Foveation - std::array foveation_parameters; + std::array foveation_parameters; public: stream_reprojection( @@ -70,4 +70,6 @@ public: vk::raii::CommandBuffer & command_buffer, int source, int destination); + + void set_foveation(std::array foveation); }; diff --git a/common/wivrn_packets.h b/common/wivrn_packets.h index 54e5b718..fab3f373 100644 --- a/common/wivrn_packets.h +++ b/common/wivrn_packets.h @@ -248,6 +248,19 @@ struct handshake int stream_port; }; +struct foveation_parameter_item +{ + float center; + float scale; + float a; + float b; +}; +struct foveation_parameter +{ + foveation_parameter_item x; + foveation_parameter_item y; +}; + struct audio_stream_description { struct device @@ -275,18 +288,6 @@ struct video_stream_description std::optional range; std::optional color_model; }; - struct foveation_parameter_item - { - double center; - double scale; - double a; - double b; - }; - struct foveation_parameter - { - foveation_parameter_item x; - foveation_parameter_item y; - }; uint16_t width; uint16_t height; float fps; @@ -320,6 +321,7 @@ public: std::array pose; std::array fov; + std::array foveation; }; std::optional view_info; diff --git a/patches/monado/0006-distortion-images.patch b/patches/monado/0006-distortion-images.patch new file mode 100644 index 00000000..c6702d9c --- /dev/null +++ b/patches/monado/0006-distortion-images.patch @@ -0,0 +1,13 @@ +diff --git a/src/xrt/compositor/render/render_distortion.c b/src/xrt/compositor/render/render_distortion.c +index 031f74ad5..1255f2616 100644 +--- a/src/xrt/compositor/render/render_distortion.c ++++ b/src/xrt/compositor/render/render_distortion.c +@@ -42,7 +42,7 @@ create_distortion_image_and_view(struct vk_bundle *vk, + vk, // vk_bundle + extent, // extent + format, // format +- VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, // usage ++ VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, // usage + &device_memory, // out_device_memory + &image); // out_image + VK_CHK_AND_RET(ret, "vk_create_image_simple"); diff --git a/patches/monado/2305-prevent-moire-artefacts.patch b/patches/monado/2305-prevent-moire-artefacts.patch new file mode 100644 index 00000000..2df0dfb0 --- /dev/null +++ b/patches/monado/2305-prevent-moire-artefacts.patch @@ -0,0 +1,279 @@ +diff --git a/src/xrt/compositor/main/comp_renderer.c b/src/xrt/compositor/main/comp_renderer.c +index 1b295a324..baabd2a0c 100644 +--- a/src/xrt/compositor/main/comp_renderer.c ++++ b/src/xrt/compositor/main/comp_renderer.c +@@ -1037,6 +1037,9 @@ dispatch_compute(struct comp_renderer *r, + // Scratch image covers the whole image. + struct xrt_normalized_rect layer_norm_rect = {.x = 0.0f, .y = 0.0f, .w = 1.0f, .h = 1.0f}; + ++ data.cs.scratch_size[i].x = c->scratch.views[i].info.width; ++ data.cs.scratch_size[i].y = c->scratch.views[i].info.height; ++ + comp_render_cs_add_view( // + &data, // data + &world_poses[i], // world_pose +diff --git a/src/xrt/compositor/render/render_compute.c b/src/xrt/compositor/render/render_compute.c +index dadb35ddc..3c3effd7d 100644 +--- a/src/xrt/compositor/render/render_compute.c ++++ b/src/xrt/compositor/render/render_compute.c +@@ -455,6 +455,7 @@ render_compute_projection_timewarp(struct render_compute *crc, + VkSampler src_samplers[XRT_MAX_VIEWS], + VkImageView src_image_views[XRT_MAX_VIEWS], + const struct xrt_normalized_rect src_norm_rects[XRT_MAX_VIEWS], ++ const struct xrt_vec2 src_sizes[XRT_MAX_VIEWS], + const struct xrt_pose src_poses[XRT_MAX_VIEWS], + const struct xrt_fov src_fovs[XRT_MAX_VIEWS], + const struct xrt_pose new_poses[XRT_MAX_VIEWS], +@@ -488,6 +489,8 @@ render_compute_projection_timewarp(struct render_compute *crc, + data->pre_transforms[i] = r->distortion.uv_to_tanangle[i]; + data->transforms[i] = time_warp_matrix[i]; + data->post_transforms[i] = src_norm_rects[i]; ++ data->source_sizes[i].x = src_sizes[i].x; ++ data->source_sizes[i].y = src_sizes[i].y; + } + + /* +@@ -592,6 +595,7 @@ render_compute_projection(struct render_compute *crc, + VkSampler src_samplers[XRT_MAX_VIEWS], + VkImageView src_image_views[XRT_MAX_VIEWS], + const struct xrt_normalized_rect src_norm_rects[XRT_MAX_VIEWS], ++ const struct xrt_vec2 src_sizes[XRT_MAX_VIEWS], + VkImage target_image, + VkImageView target_image_view, + const struct render_viewport_data views[XRT_MAX_VIEWS]) +@@ -611,6 +615,8 @@ render_compute_projection(struct render_compute *crc, + for (uint32_t i = 0; i < crc->r->view_count; ++i) { + data->views[i] = views[i]; + data->post_transforms[i] = src_norm_rects[i]; ++ data->source_sizes[i].x = src_sizes[i].x; ++ data->source_sizes[i].y = src_sizes[i].y; + } + + +diff --git a/src/xrt/compositor/render/render_interface.h b/src/xrt/compositor/render/render_interface.h +index f1a7a941a..fcb6dcc44 100644 +--- a/src/xrt/compositor/render/render_interface.h ++++ b/src/xrt/compositor/render/render_interface.h +@@ -1227,6 +1227,7 @@ struct render_compute_distortion_ubo_data + struct xrt_normalized_rect pre_transforms[XRT_MAX_VIEWS]; + struct xrt_normalized_rect post_transforms[XRT_MAX_VIEWS]; + struct xrt_matrix_4x4 transforms[XRT_MAX_VIEWS]; ++ struct xrt_rect_f32 source_sizes[XRT_MAX_VIEWS]; + }; + + /*! +@@ -1294,6 +1295,7 @@ render_compute_projection_timewarp(struct render_compute *crc, + VkSampler src_samplers[XRT_MAX_VIEWS], + VkImageView src_image_views[XRT_MAX_VIEWS], + const struct xrt_normalized_rect src_rects[XRT_MAX_VIEWS], ++ const struct xrt_vec2 src_sizes[XRT_MAX_VIEWS], + const struct xrt_pose src_poses[XRT_MAX_VIEWS], + const struct xrt_fov src_fovs[XRT_MAX_VIEWS], + const struct xrt_pose new_poses[XRT_MAX_VIEWS], +@@ -1309,6 +1311,7 @@ render_compute_projection(struct render_compute *crc, + VkSampler src_samplers[XRT_MAX_VIEWS], // + VkImageView src_image_views[XRT_MAX_VIEWS], // + const struct xrt_normalized_rect src_rects[XRT_MAX_VIEWS], // ++ const struct xrt_vec2 src_sizes[XRT_MAX_VIEWS], // + VkImage target_image, // + VkImageView target_image_view, // + const struct render_viewport_data views[XRT_MAX_VIEWS]); // +diff --git a/src/xrt/compositor/shaders/distortion.comp b/src/xrt/compositor/shaders/distortion.comp +index 08b44d4cf..69d0a41b0 100644 +--- a/src/xrt/compositor/shaders/distortion.comp ++++ b/src/xrt/compositor/shaders/distortion.comp +@@ -25,14 +25,12 @@ layout(set = 0, binding = 3, std140) uniform restrict Config + vec4 pre_transform[2]; + vec4 post_transform[2]; + mat4 transform[2]; ++ vec2 src_sizes[2]; + } ubo; + + +-vec2 position_to_uv(ivec2 extent, uint ix, uint iy) ++vec2 position_to_uv(ivec2 extent, vec2 xy) + { +- // Turn the index into floating point. +- vec2 xy = vec2(float(ix), float(iy)); +- + // The inverse of the extent of the target image is the pixel size in [0 .. 1] space. + vec2 extent_pixel_size = vec2(1.0 / float(extent.x), 1.0 / float(extent.y)); + +@@ -102,6 +100,17 @@ vec2 transform_uv(vec2 uv, uint iz) + } + } + ++vec2 distorted_uv(ivec2 extent, vec2 xy, uint iz) ++{ ++ vec2 dist_uv = position_to_uv(extent, xy); ++ ++ // Only read red channel, we don't do color aberration ++ vec2 r_uv = texture(distortion[iz + 0], dist_uv).xy; ++ ++ // Do any transformation needed. ++ return transform_uv(r_uv, iz); ++} ++ + void main() + { + uint ix = gl_GlobalInvocationID.x; +@@ -110,29 +119,71 @@ void main() + + ivec2 offset = ivec2(ubo.views[iz].xy); + ivec2 extent = ivec2(ubo.views[iz].zw); ++ ivec2 src_extent = ivec2(ubo.src_sizes[iz]); + + if (ix >= extent.x || iy >= extent.y) { + return; + } + +- vec2 dist_uv = position_to_uv(extent, ix, iy); ++ // extent of the area to sample in normalized coordinates ++ vec2 u0 = distorted_uv(extent, max(vec2(0, 0), vec2(ix - 0.5, iy - 0.5)), iz); ++ vec2 u1 = distorted_uv(extent, min(extent, vec2(ix + 0.5, iy + 0.5)), iz); + +- vec2 r_uv = texture(distortion[iz + 0], dist_uv).xy; +- vec2 g_uv = texture(distortion[iz + 2], dist_uv).xy; +- vec2 b_uv = texture(distortion[iz + 4], dist_uv).xy; ++ if (u0.y > u1.y) ++ { ++ float tmp = u0.y; ++ u0.y = u1.y; ++ u1.y = tmp; ++ } + +- // Do any transformation needed. +- r_uv = transform_uv(r_uv, iz); +- g_uv = transform_uv(g_uv, iz); +- b_uv = transform_uv(b_uv, iz); ++ // extent in pixel coordinates ++ vec2 p0 = u0 * (src_extent - 1); ++ vec2 p1 = u1 * (src_extent - 1); ++ ++ // shrink by 1/2 pixel to prevent overlap ++ p0 += vec2(0.5); ++ p1 -= vec2(0.5); ++ ++ // iteration area ++ vec2 i0, i1; ++ // If there is less than one pixel, just sample it ++ if (p1.x - p0.x <= 1) ++ i0.x = i1.x = distorted_uv(extent, vec2(ix, iy), iz).x * src_extent.x; ++ else ++ { ++ i0.x = floor(p0.x); ++ i1.x = ceil(p1.x); ++ } ++ if (p1.y - p0.y <= 1) ++ i0.y = i1.y = distorted_uv(extent, vec2(ix, iy), iz).y * src_extent.y; ++ else ++ { ++ i0.y = floor(p0.y); ++ i1.y = ceil(p1.y); ++ } + +- // Sample the source with distorted and chromatic-aberration corrected samples. +- vec4 colour = vec4( +- texture(source[iz], r_uv).r, +- texture(source[iz], g_uv).g, +- texture(source[iz], b_uv).b, +- 1); ++ vec4 colour = vec4(0, 0, 0, 1); ++ ++ float count = 0; ++ for (float y = i0.y ; y <= i1.y ; y++) { ++ float wy = 1; ++ if (y < p0.y) ++ wy *= 1 - (p0.y - y); ++ if (y > p1.y) ++ wy *= 1 - (y - p1.y); ++ for (float x = i0.x; x <= i1.x; x++) { ++ float w = wy; ++ if (x < p0.x) ++ w *= 1 - (p0.x - x); ++ if (x > p1.x) ++ w *= 1 - (x - p1.x); ++ vec2 uv = (vec2(x, y) + 0.5) / src_extent; ++ colour.rgb += w * texture(source[iz], uv).rgb; ++ count += w; ++ } ++ } + ++ colour /= count; + // Do colour correction here since there are no automatic conversion in hardware available. + colour = vec4(from_linear_to_srgb(colour.rgb), 1); + +diff --git a/src/xrt/compositor/util/comp_render.h b/src/xrt/compositor/util/comp_render.h +index 653cc0e3d..384b304d7 100644 +--- a/src/xrt/compositor/util/comp_render.h ++++ b/src/xrt/compositor/util/comp_render.h +@@ -126,6 +126,8 @@ struct comp_render_dispatch_data + + // Target image view for distortion. + VkImageView target_unorm_view; ++ ++ struct xrt_vec2 scratch_size[XRT_MAX_VIEWS]; + } cs; + }; + +diff --git a/src/xrt/compositor/util/comp_render_cs.c b/src/xrt/compositor/util/comp_render_cs.c +index 8201407ae..ea9d1f258 100644 +--- a/src/xrt/compositor/util/comp_render_cs.c ++++ b/src/xrt/compositor/util/comp_render_cs.c +@@ -350,6 +350,7 @@ do_cs_distortion_from_scratch(struct render_compute *crc, const struct comp_rend + VkImageView src_image_views[XRT_MAX_VIEWS]; + VkSampler src_samplers[XRT_MAX_VIEWS]; + struct xrt_normalized_rect src_norm_rects[XRT_MAX_VIEWS]; ++ struct xrt_vec2 src_sizes[XRT_MAX_VIEWS]; + + for (uint32_t i = 0; i < d->view_count; i++) { + // Data to be filled in. +@@ -367,6 +368,7 @@ do_cs_distortion_from_scratch(struct render_compute *crc, const struct comp_rend + src_image_views[i] = src_image_view; + src_samplers[i] = clamp_to_border_black; + src_norm_rects[i] = src_norm_rect; ++ src_sizes[i] = d->cs.scratch_size[i]; + } + + render_compute_projection( // +@@ -374,6 +376,7 @@ do_cs_distortion_from_scratch(struct render_compute *crc, const struct comp_rend + src_samplers, // src_samplers + src_image_views, // src_image_views + src_norm_rects, // src_rects ++ src_sizes, // src_sizes + d->cs.target_image, // target_image + d->cs.target_unorm_view, // target_image_view + target_viewport_datas); // views +@@ -402,6 +405,7 @@ do_cs_distortion_for_layer(struct render_compute *crc, + struct xrt_normalized_rect src_norm_rects[XRT_MAX_VIEWS]; + struct xrt_pose src_poses[XRT_MAX_VIEWS]; + struct xrt_fov src_fovs[XRT_MAX_VIEWS]; ++ struct xrt_vec2 src_sizes[XRT_MAX_VIEWS]; + VkSampler src_samplers[XRT_MAX_VIEWS]; + VkImageView src_image_views[XRT_MAX_VIEWS]; + +@@ -435,6 +439,8 @@ do_cs_distortion_for_layer(struct render_compute *crc, + src_norm_rects[i] = src_norm_rect; + src_poses[i] = src_pose; + src_fovs[i] = src_fov; ++ src_sizes[i].x = layer->sc_array[i]->vkic.info.width; ++ src_sizes[i].y = layer->sc_array[i]->vkic.info.height; + src_samplers[i] = clamp_to_border_black; + src_image_views[i] = src_image_view; + } +@@ -445,6 +451,7 @@ do_cs_distortion_for_layer(struct render_compute *crc, + src_samplers, // + src_image_views, // + src_norm_rects, // ++ src_sizes, // + d->cs.target_image, // + d->cs.target_unorm_view, // + target_viewport_datas); // +@@ -454,6 +461,7 @@ do_cs_distortion_for_layer(struct render_compute *crc, + src_samplers, // + src_image_views, // + src_norm_rects, // ++ src_sizes, // + src_poses, // + src_fovs, // + world_poses, // diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index a86571a3..29865a1e 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -81,6 +81,7 @@ add_executable(wivrn-server driver/wivrn_controller.cpp driver/wivrn_eye_tracker.cpp driver/wivrn_fb_face2_tracker.cpp + driver/wivrn_foveation.cpp driver/pose_list.cpp driver/view_list.cpp driver/hand_joints_list.cpp @@ -141,7 +142,7 @@ endif() include(CompileGLSL) -file(GLOB VULKAN_SHADERS CONFIGURE_DEPENDS "encoder/shaders/*.glsl") +file(GLOB VULKAN_SHADERS CONFIGURE_DEPENDS "shaders/*.glsl") target_sources(wivrn-server PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS}) wivrn_compile_glsl(wivrn-server ${VULKAN_SHADERS}) diff --git a/server/driver/wivrn_comp_target.cpp b/server/driver/wivrn_comp_target.cpp index 283b4527..ceeb06fd 100644 --- a/server/driver/wivrn_comp_target.cpp +++ b/server/driver/wivrn_comp_target.cpp @@ -22,10 +22,12 @@ #include "main/comp_compositor.h" #include "math/m_space.h" #include "utils/scoped_lock.h" +#include "wivrn_foveation.h" #include "xrt_cast.h" #include #include #include +#include using namespace xrt::drivers::wivrn; @@ -216,6 +218,12 @@ 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(*cn->wivrn_bundle, cn->command_pool); + } + return true; } @@ -323,19 +331,6 @@ static bool comp_wivrn_has_images(struct comp_target * ct) static VkResult comp_wivrn_acquire(struct comp_target * ct, uint32_t * out_index) { struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; - struct vk_bundle * vk = get_vk(cn); - - vk::Semaphore sem(cn->semaphores.present_complete); - - vk::SubmitInfo submit_info{ - .signalSemaphoreCount = 1, - .pSignalSemaphores = &sem, - }; - - { - scoped_lock lock(vk->queue_mutex); - cn->wivrn_bundle->queue.submit(submit_info); - } while (true) { @@ -470,6 +465,7 @@ static VkResult comp_wivrn_present(struct comp_target * ct, auto & view_info = cn->psc.view_info; view_info.display_time = cn->cnx->get_offset().to_headset(desired_present_time_ns); + view_info.foveation = cn->cnx->get_foveation_parameters(); for (int eye = 0; eye < 2; ++eye) { const auto & slot = cn->c->base.slot; @@ -499,7 +495,26 @@ static VkResult comp_wivrn_present(struct comp_target * ct, static void comp_wivrn_flush(struct comp_target * ct) { - (void)ct; + struct wivrn_comp_target * cn = (struct wivrn_comp_target *)ct; + + // apply foveation for current frame + if (cn->cnx->apply_dynamic_foveation()) + // foveation renderer already signaled the semaphore; nothing to do + return; + + struct vk_bundle * vk = get_vk(cn); + + vk::Semaphore sem(cn->semaphores.present_complete); + + vk::SubmitInfo submit_info{ + .signalSemaphoreCount = 1, + .pSignalSemaphores = &sem, + }; + + { + scoped_lock lock(vk->queue_mutex); + cn->wivrn_bundle->queue.submit(submit_info); + } } static void comp_wivrn_calc_frame_pacing(struct comp_target * ct, @@ -596,6 +611,27 @@ void wivrn_comp_target::reset_encoders() cnx->send_control(desc); } +void wivrn_comp_target::render_dynamic_foveation(std::array 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); + } +} + wivrn_comp_target::wivrn_comp_target(std::shared_ptr cnx, struct comp_compositor * c, float fps) : comp_target{}, pacer(U_TIME_1S_IN_NS / fps), diff --git a/server/driver/wivrn_comp_target.h b/server/driver/wivrn_comp_target.h index 308b91a3..1c4571d5 100644 --- a/server/driver/wivrn_comp_target.h +++ b/server/driver/wivrn_comp_target.h @@ -99,12 +99,15 @@ struct wivrn_comp_target : public comp_target std::vector> encoders; std::shared_ptr cnx; + std::unique_ptr foveation_renderer = nullptr; wivrn_comp_target(std::shared_ptr cnx, struct comp_compositor * c, float fps); ~wivrn_comp_target(); void on_feedback(const from_headset::feedback &, const clock_offset &); void reset_encoders(); + + void render_dynamic_foveation(std::array foveation); }; } // namespace xrt::drivers::wivrn diff --git a/server/driver/wivrn_foveation.cpp b/server/driver/wivrn_foveation.cpp new file mode 100644 index 00000000..8c93d0eb --- /dev/null +++ b/server/driver/wivrn_foveation.cpp @@ -0,0 +1,330 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 galister + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "render/render_interface.h" + +#include "wivrn_foveation.h" + +#include "driver/xrt_cast.h" +#include "math/m_api.h" +#include "utils/wivrn_vk_bundle.h" +#include "wivrn_packets.h" +#include "xrt/xrt_defines.h" + +#include +#include +#include +#include +#include +#include + +extern const std::map> shaders; + +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 vk::DescriptorSetLayoutBinding layout_bindings{ + .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 = 1, .pBindings = &layout_bindings}) +{ + cmd_buf = std::move(vk.device.allocateCommandBuffers( + {.commandPool = *cmd_pool, + .commandBufferCount = 1})[0]); + + // Pipeline layout + { + 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, + }); + } + + // 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 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(), + }; +} + +void wivrn_foveation_renderer::render_distortion_images(std::array foveations, const VkImage * images, const VkImageView * image_views) +{ + cmd_buf.reset(); + cmd_buf.begin(vk::CommandBufferBeginInfo{}); + + std::array im_barriers0 = { + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eMemoryWrite, + .oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .newLayout = vk::ImageLayout::eGeneral, + .image = images[0], + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eMemoryWrite, + .oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .newLayout = vk::ImageLayout::eGeneral, + .image = images[1], + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + }; + + cmd_buf.pipelineBarrier( + vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eComputeShader, + {}, + nullptr, + nullptr, + im_barriers0); + + // Monado's distortion shader is patched to only consider the red channel's image + for (int eye = 0; eye < 2; ++eye) + { + // Descriptor set + + vk::DescriptorImageInfo image_info{ + .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(*layout, vk::ShaderStageFlagBits::eCompute, 0, f_params); + cmd_buf.dispatch(dispatch_group_count, dispatch_group_count, 1); + } + + std::array im_barriers1 = { + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eMemoryWrite, + .dstAccessMask = vk::AccessFlagBits::eNone, + .oldLayout = vk::ImageLayout::eGeneral, + .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .image = images[0], + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eMemoryWrite, + .dstAccessMask = vk::AccessFlagBits::eNone, + .oldLayout = vk::ImageLayout::eGeneral, + .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .image = images[1], + .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1}, + }, + }; + + cmd_buf.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader, + vk::PipelineStageFlagBits::eBottomOfPipe, + {}, + nullptr, + nullptr, + im_barriers1); + + cmd_buf.end(); +} + +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); + + float pitch = std::asin(sine_theta); + + if (std::abs(sine_theta) > 0.99999f) + { + float scale = std::copysign(2.0, sine_theta); + return {scale * std::atan2(-q.z, q.w), pitch}; + } + + return { + std::atan2(2.0f * (q.x * q.z + q.w * q.y), + q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z), + pitch}; +} + +std::array wivrn_foveation::get_center() +{ + std::lock_guard lock(mutex); + + std::array uvs; + auto e = yaw_pitch(last_gaze); + + for (int i = 0; i < 2; i++) + { + 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; +} + +void wivrn_foveation::update_tracking(const from_headset::tracking & tracking, const clock_offset & offset) +{ + std::lock_guard lock(mutex); + + const uint8_t orientation_ok = from_headset::tracking::orientation_valid | from_headset::tracking::orientation_tracked; + + views = tracking.views; + + std::optional head; + + for (const auto & pose: tracking.device_poses) + { + if (pose.device != device_id::HEAD) + continue; + + if ((pose.flags & orientation_ok) != orientation_ok) + return; + + head = xrt_cast(pose.pose.orientation); + break; + } + + if (!head.has_value()) + return; + + for (const auto & pose: tracking.device_poses) + { + if (pose.device != device_id::EYE_GAZE) + continue; + + if ((pose.flags & orientation_ok) != orientation_ok) + return; + + xrt_quat qgaze = xrt_cast(pose.pose.orientation); + math_quat_unrotate(&qgaze, &head.value(), &last_gaze); + break; + } +} + +void wivrn_foveation::set_initial_parameters(std::array p) +{ + std::lock_guard lock(mutex); + + center_offset[0] = {p[0].x.center, p[0].y.center}; + center_offset[1] = {p[1].x.center, p[1].y.center}; +} diff --git a/server/driver/wivrn_foveation.h b/server/driver/wivrn_foveation.h new file mode 100644 index 00000000..6c35fce6 --- /dev/null +++ b/server/driver/wivrn_foveation.h @@ -0,0 +1,61 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 galister + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include + +#include "wivrn_session.h" + +struct wivrn_vk_bundle; + +// Calculates the center parameter from the received eye tracking data. +class wivrn_foveation +{ + std::mutex mutex; + + std::array center_offset = {}; + std::array views = {}; + xrt_quat last_gaze = {}; + +public: + wivrn_foveation() {} + + void set_initial_parameters(std::array p); + void update_tracking(const from_headset::tracking &, const clock_offset &); + std::array get_center(); +}; + +// 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 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 foveation_arr, const VkImage * images, const VkImageView * image_views); +}; diff --git a/server/driver/wivrn_hmd.cpp b/server/driver/wivrn_hmd.cpp index 87a0ff39..d225c321 100644 --- a/server/driver/wivrn_hmd.cpp +++ b/server/driver/wivrn_hmd.cpp @@ -23,7 +23,6 @@ #include "xrt/xrt_device.h" #include "util/u_device.h" -#include "util/u_distortion_mesh.h" #include "util/u_logging.h" #include "xrt_cast.h" @@ -374,6 +373,26 @@ decltype(wivrn_hmd::foveation_parameters) wivrn_hmd::set_foveated_size(uint32_t return foveation_parameters; } +void wivrn_hmd::set_foveation_center(std::array 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); + } + } +} + /* * * Functions diff --git a/server/driver/wivrn_hmd.h b/server/driver/wivrn_hmd.h index c6812c71..b617e6bd 100644 --- a/server/driver/wivrn_hmd.h +++ b/server/driver/wivrn_hmd.h @@ -47,7 +47,7 @@ class wivrn_hmd : public xrt_device }; view_list views; - std::array foveation_parameters{}; + std::array foveation_parameters{}; from_headset::battery battery{}; std::shared_ptr cnx; @@ -80,4 +80,10 @@ public: 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 center); + + std::array get_foveation_parameters() + { + return foveation_parameters; + } }; diff --git a/server/driver/wivrn_session.cpp b/server/driver/wivrn_session.cpp index f40b1ddc..7d6e41bc 100644 --- a/server/driver/wivrn_session.cpp +++ b/server/driver/wivrn_session.cpp @@ -20,6 +20,7 @@ #include "wivrn_session.h" #include "accept_connection.h" +#include "main/comp_compositor.h" #include "main/comp_main_interface.h" #include "main/comp_target.h" #include "util/u_builders.h" @@ -33,6 +34,7 @@ #include "wivrn_controller.h" #include "wivrn_eye_tracker.h" #include "wivrn_fb_face2_tracker.h" +#include "wivrn_foveation.h" #include "wivrn_hmd.h" #include "xrt/xrt_session.h" @@ -161,6 +163,7 @@ xrt_result_t xrt::drivers::wivrn::wivrn_session::create_session(xrt::drivers::wi if (info.eye_gaze) { self->eye_tracker = std::make_unique(self->hmd.get(), self); + self->foveation = std::make_unique(); usysds->base.base.static_roles.eyes = self->eye_tracker.get(); devices->xdevs[n++] = self->eye_tracker.get(); } @@ -266,6 +269,8 @@ void wivrn_session::operator()(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); } void wivrn_session::operator()(from_headset::hand_tracking && hand_tracking) @@ -361,9 +366,29 @@ void wivrn_session::run(std::weak_ptr weak_self) } } -std::array wivrn_session::set_foveated_size(uint32_t width, uint32_t height) +std::array wivrn_session::set_foveated_size(uint32_t width, uint32_t height) { - return hmd->set_foveated_size(width, 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 wivrn_session::get_foveation_parameters() +{ + return hmd->get_foveation_parameters(); } void wivrn_session::dump_time(const std::string & event, uint64_t frame, uint64_t time, uint8_t stream, const char * extra) diff --git a/server/driver/wivrn_session.h b/server/driver/wivrn_session.h index 184d43c2..c059a584 100644 --- a/server/driver/wivrn_session.h +++ b/server/driver/wivrn_session.h @@ -34,6 +34,8 @@ class wivrn_hmd; class wivrn_controller; class wivrn_eye_tracker; class wivrn_fb_face2_tracker; +class wivrn_foveation; +class wivrn_foveation_renderer; struct audio_device; struct u_system; @@ -83,6 +85,7 @@ class wivrn_session : public std::enable_shared_from_this std::unique_ptr right_hand; std::unique_ptr eye_tracker; std::unique_ptr fb_face2_tracker; + std::unique_ptr foveation; wivrn_comp_target * comp_target; clock_offset_estimator offset_est; @@ -135,7 +138,13 @@ public: connection.send_control(std::forward(packet)); } - std::array set_foveated_size(uint32_t width, uint32_t height); + std::array set_foveated_size(uint32_t width, uint32_t height); + std::array get_foveation_parameters(); + bool apply_dynamic_foveation(); + bool has_dynamic_foveation() + { + return (bool)foveation; + } void dump_time(const std::string & event, uint64_t frame, uint64_t time, uint8_t stream = -1, const char * extra = ""); diff --git a/server/shaders/foveate.comp.glsl b/server/shaders/foveate.comp.glsl new file mode 100644 index 00000000..c5aad403 --- /dev/null +++ b/server/shaders/foveate.comp.glsl @@ -0,0 +1,61 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 galister + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#version 450 + +layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; + +layout(set = 0, binding = 0, rgba8) uniform writeonly restrict image2D target; + +layout(push_constant) uniform PushConstants +{ + vec2 a; + vec2 b; + vec2 scale; + vec2 center; +} pcs; + +layout(constant_id = 0) const float one_over_dim = 0.0; + +float foveate(float a, float b, float scale, float c, float x) { + return scale / a * tan(a * x + b) + c; +} + +void main() +{ + ivec2 coords = ivec2(gl_GlobalInvocationID.x, gl_GlobalInvocationID.y); + + vec2 uv = vec2( + float(coords.x), + float(coords.y) + ) * one_over_dim; + + if (pcs.scale.x < 1.0) { + float u = uv.x * 2.0 - 1.0; + float val = foveate(pcs.a.x, pcs.b.x, pcs.scale.x, pcs.center.x, u); + uv.x = clamp((1.0 + val) / 2.0, 0.0, 1.0); + } + + if (pcs.scale.y < 1.0) { + float v = uv.y * 2.0 - 1.0; + float val = foveate(pcs.a.y, pcs.b.y, pcs.scale.y, pcs.center.y, v); + uv.y = clamp((1.0 + val) / 2.0, 0.0, 1.0); + } + + imageStore(target, coords, vec4(uv.x, uv.y, 0.0, 0.0)); +} diff --git a/server/encoder/shaders/yuv.comp.glsl b/server/shaders/yuv.comp.glsl similarity index 100% rename from server/encoder/shaders/yuv.comp.glsl rename to server/shaders/yuv.comp.glsl