diff --git a/client/application.cpp b/client/application.cpp index c62433ab..51437b43 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -899,6 +899,8 @@ void application::initialize_vulkan() optional_device_extensions.emplace(VK_IMG_FILTER_CUBIC_EXTENSION_NAME); optional_device_extensions.emplace(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME); optional_device_extensions.emplace(VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME); + optional_device_extensions.emplace(VK_EXT_FRAGMENT_DENSITY_MAP_2_EXTENSION_NAME); + optional_device_extensions.emplace(VK_QCOM_FRAGMENT_DENSITY_MAP_OFFSET_EXTENSION_NAME); #if WIVRN_USE_V4L2 // V4L2 decoders expose their output through DMA-buf @@ -1054,7 +1056,9 @@ void application::initialize_vulkan() vk::PhysicalDeviceMultiviewFeaturesKHR{ .multiview = true, }, - vk::PhysicalDeviceIndexTypeUint8FeaturesEXT{}}; + vk::PhysicalDeviceIndexTypeUint8FeaturesEXT{}, + vk::PhysicalDeviceFragmentDensityMapFeaturesEXT{}, + vk::PhysicalDeviceFragmentDensityMapOffsetFeaturesQCOM{}}; auto check_feature_flag = [&](auto feature_flag, const char * extension_name) -> bool { using FeatureStruct = class_from_member_t; @@ -1074,6 +1078,14 @@ void application::initialize_vulkan() check_feature_flag(&vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::timelineSemaphore, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME); check_feature_flag(&vk::PhysicalDeviceIndexTypeUint8FeaturesEXT::indexTypeUint8, VK_EXT_INDEX_TYPE_UINT8_EXTENSION_NAME); + const bool fragment_density_map_supported = + check_feature_flag(&vk::PhysicalDeviceFragmentDensityMapFeaturesEXT::fragmentDensityMap, VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME); + const bool fragment_density_map2_supported = + utils::contains(vk_device_extensions, VK_EXT_FRAGMENT_DENSITY_MAP_2_EXTENSION_NAME); + const bool fragment_density_map_offset_supported = + check_feature_flag(&vk::PhysicalDeviceFragmentDensityMapOffsetFeaturesQCOM::fragmentDensityMapOffset, VK_QCOM_FRAGMENT_DENSITY_MAP_OFFSET_EXTENSION_NAME); + foveation_vulkan_supported = fragment_density_map_supported and fragment_density_map2_supported and fragment_density_map_offset_supported; + spdlog::info(" Vulkan eye-tracked foveation support: {}", foveation_vulkan_supported); vk_device = xr_system_id.create_device(vk_physical_device, device_create_info.get()); *vk_queue.lock() = vk_device.getQueue(vk_queue_family_index, 0); @@ -1382,6 +1394,9 @@ void application::initialize() XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME, XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME, XR_FB_FACE_TRACKING2_EXTENSION_NAME, + XR_FB_FOVEATION_EXTENSION_NAME, + XR_FB_FOVEATION_CONFIGURATION_EXTENSION_NAME, + XR_FB_FOVEATION_VULKAN_EXTENSION_NAME, XR_FB_PASSTHROUGH_EXTENSION_NAME, XR_FB_SWAPCHAIN_UPDATE_STATE_EXTENSION_NAME, @@ -1392,8 +1407,10 @@ void application::initialize() XR_META_BODY_TRACKING_FIDELITY_EXTENSION_NAME, XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME, + XR_META_FOVEATION_EYE_TRACKED_EXTENSION_NAME, XR_META_LOCAL_DIMMING_EXTENSION_NAME, XR_META_BOUNDARY_VISIBILITY_EXTENSION_NAME, + XR_META_VULKAN_SWAPCHAIN_CREATE_INFO_EXTENSION_NAME, }; for (const auto & i: interaction_profiles) @@ -1444,6 +1461,13 @@ void application::initialize() eye_gaze_supported = eye_gaze_properties.supportsEyeGazeInteraction; } + if (xr_instance.has_extension(XR_META_FOVEATION_EYE_TRACKED_EXTENSION_NAME)) + { + XrSystemFoveationEyeTrackedPropertiesMETA foveation_properties = xr_system_id.foveation_eye_tracked_properties(); + spdlog::info(" Eye tracked foveation center support: {}", (bool)foveation_properties.supportsFoveationEyeTracked); + foveation_center_supported = foveation_properties.supportsFoveationEyeTracked; + } + if (xr_instance.has_extension(XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME)) { spdlog::info(" OpenXR post-processing extension support: true"); diff --git a/client/application.h b/client/application.h index 739b6710..11305d8a 100644 --- a/client/application.h +++ b/client/application.h @@ -131,6 +131,8 @@ private: std::vector> generic_trackers; bool eye_gaze_supported = false; + bool foveation_center_supported = false; + bool foveation_vulkan_supported = false; bool openxr_post_processing_supported = false; @@ -407,6 +409,16 @@ public: return instance().eye_gaze_supported; } + static bool get_foveation_center_supported() + { + return instance().foveation_center_supported; + } + + static bool get_foveation_vulkan_supported() + { + return instance().foveation_vulkan_supported; + } + static bool get_openxr_post_processing_supported() { return instance().openxr_post_processing_supported; diff --git a/client/foveation.cpp b/client/foveation.cpp new file mode 100644 index 00000000..81a216f7 --- /dev/null +++ b/client/foveation.cpp @@ -0,0 +1,487 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 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 "foveation.h" + +#include "application.h" +#include "xr/instance.h" +#include "xr/session.h" +#include "xr/system.h" + +#include +#include +#include +#include +#include + +namespace +{ +float convergence_angle(float distance, float eye_x, float yaw) +{ + const float target_x = distance * std::sin(yaw); + const float target_z = distance * std::cos(yaw); + + return std::atan2(target_x - eye_x, target_z); +} + +XrVector2f yaw_pitch(const XrQuaternionf & q) +{ + const float sine_theta = std::clamp(-2.0f * (q.y * q.z - q.w * q.x), -1.0f, 1.0f); + const float pitch = std::asin(sine_theta); + + if (std::abs(sine_theta) > 0.99999f) + { + const float scale = std::copysign(2.0f, 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}; +} + +float ndc_to_angle(float center, float a0, float a1) +{ + const float u = std::clamp(center * 0.5f + 0.5f, 0.0f, 1.0f); + const float tangent = std::lerp(std::tan(a0), std::tan(a1), u); + return std::atan(tangent); +} + +client_foveation::angles center_to_angles(const std::array & center, std::span fovs) +{ + assert(fovs.size() == 2); + client_foveation::angles result{}; + + for (size_t i = 0; i < result.size(); ++i) + { + result[i].x = ndc_to_angle(center[i].x, fovs[i].angleLeft, fovs[i].angleRight); + result[i].y = ndc_to_angle(center[i].y, fovs[i].angleUp, fovs[i].angleDown); + } + + return result; +} + +bool fov_equal(const XrFovf & a, const XrFovf & b, const float epsilon) +{ + return std::abs(a.angleLeft - b.angleLeft) <= epsilon and + std::abs(a.angleRight - b.angleRight) <= epsilon and + std::abs(a.angleUp - b.angleUp) <= epsilon and + std::abs(a.angleDown - b.angleDown) <= epsilon; +} + +client_foveation::angles target_angles( + float yaw, + float pitch, + float convergence_distance, + std::span views) +{ + assert(views.size() == 2); + client_foveation::angles result{}; + + for (size_t i = 0; i < result.size(); ++i) + { + result[i].x = convergence_angle(convergence_distance, views[i].pose.position.x, yaw); + result[i].y = pitch; + } + + return result; +} + +std::optional eye_gaze_angles( + XrSpace eye_gaze_space, + XrSpace view_space, + XrTime time, + XrViewStateFlags view_flags, + std::span views) +{ + if (not eye_gaze_space or not view_space or views.size() != 2) + return {}; + + XrSpaceLocation location{ + .type = XR_TYPE_SPACE_LOCATION, + }; + + XrResult res = xrLocateSpace(eye_gaze_space, view_space, time, &location); + if (XR_FAILED(res) or + not(location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) or + not(location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)) + return {}; + + if (not(view_flags & XR_VIEW_STATE_POSITION_VALID_BIT)) + return {}; + + const XrVector2f gaze = yaw_pitch(location.pose.orientation); + return target_angles(-gaze.x, gaze.y, client_foveation::default_convergence_distance, views); +} + +} // namespace + +namespace client_foveation +{ + +center::center(xr::instance & inst, xr::system & sys, xr::session & xr_session, vk::raii::Device & vk_device, vk::raii::CommandPool & vk_commandpool, thread_safe & vk_queue, vk::Format format) : + instance(inst), + session(xr_session), + device(vk_device), + commandpool(vk_commandpool), + queue(vk_queue), + swapchain_format(format) +{ + if (application::get_foveation_center_supported() and + application::get_foveation_vulkan_supported() and + inst.has_extension(XR_META_FOVEATION_EYE_TRACKED_EXTENSION_NAME) and + inst.has_extension(XR_FB_FOVEATION_EXTENSION_NAME) and + inst.has_extension(XR_FB_FOVEATION_CONFIGURATION_EXTENSION_NAME) and + inst.has_extension(XR_FB_FOVEATION_VULKAN_EXTENSION_NAME) and + inst.has_extension(XR_FB_SWAPCHAIN_UPDATE_STATE_EXTENSION_NAME) and + inst.has_extension(XR_META_VULKAN_SWAPCHAIN_CREATE_INFO_EXTENSION_NAME) and + sys.foveation_eye_tracked_properties().supportsFoveationEyeTracked) + { + xrCreateFoveationProfileFB = inst.get_proc("xrCreateFoveationProfileFB"); + xrDestroyFoveationProfileFB = inst.get_proc("xrDestroyFoveationProfileFB"); + xrUpdateSwapchainFB = inst.get_proc("xrUpdateSwapchainFB"); + xrGetFoveationEyeTrackedStateMETA = inst.get_proc("xrGetFoveationEyeTrackedStateMETA"); + + if (xrCreateFoveationProfileFB and xrDestroyFoveationProfileFB and + xrUpdateSwapchainFB and xrGetFoveationEyeTrackedStateMETA) + { + XrFoveationEyeTrackedProfileCreateInfoMETA eye_tracked_info{ + .type = XR_TYPE_FOVEATION_EYE_TRACKED_PROFILE_CREATE_INFO_META, + .flags = 0, + }; + XrFoveationLevelProfileCreateInfoFB level_info{ + .type = XR_TYPE_FOVEATION_LEVEL_PROFILE_CREATE_INFO_FB, + .next = &eye_tracked_info, + .level = XR_FOVEATION_LEVEL_LOW_FB, + .verticalOffset = 0, + .dynamic = XR_FOVEATION_DYNAMIC_DISABLED_FB, + }; + XrFoveationProfileCreateInfoFB profile_info{ + .type = XR_TYPE_FOVEATION_PROFILE_CREATE_INFO_FB, + .next = &level_info, + }; + + XrFoveationProfileFB raw_profile = XR_NULL_HANDLE; + XrResult profile_result = xrCreateFoveationProfileFB(session, &profile_info, &raw_profile); + if (XR_SUCCEEDED(profile_result)) + foveation_profile.emplace(raw_profile, xrDestroyFoveationProfileFB); + } + } + + if (foveation_profile.has_value()) + spdlog::info("XR_META_foveation_eye_tracked will be used for this stream"); + else if (application::get_eye_gaze_supported()) + spdlog::info("Eye gaze tracking will be used for this stream"); + else + spdlog::info("Static foveation will be used for this stream"); + + auto [flags, views] = session.locate_views( + XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, + instance.now(), + application::space(xr::spaces::view)); + (void)flags; + assert(views.size() == headset_fov.size()); + for (size_t i = 0; i < headset_fov.size(); ++i) + headset_fov[i] = views[i].fov; + + const auto & config = application::get_config(); + set_manual_mode({ + .enabled = config.override_foveation_enable, + .pitch = config.override_foveation_pitch, + .distance = config.override_foveation_distance, + }); +} + +// member order ensures swapchain is dropped before foveation profile +center::~center() = default; + +bool center::supports_meta() const +{ + return foveation_profile.has_value(); +} + +manual_override center::get_manual_mode() const +{ + return *manual_mode_.lock(); +} + +void center::set_manual_mode(manual_override mode) +{ + *manual_mode_.lock() = mode; +} + +bool center::is_cropped(std::span submitted_fov, std::span valid) const +{ + assert(submitted_fov.size() == view_count and valid.size() == view_count); + for (size_t i = 0; i < view_count; ++i) + { + // generous epsilon of ~6° per-side to filter out false positives + if (valid[i] and not fov_equal(submitted_fov[i], headset_fov[i], 0.1f)) + return true; + } + return false; +} + +bool center::needs_swapchain_recreation(bool cropped) const +{ + return supports_meta() and (not cropped_mode or *cropped_mode != cropped); +} + +bool center::use_meta_swapchain(bool cropped) const +{ + return supports_meta() and not cropped; +} + +void center::set_cropped(bool cropped) +{ + if (not cropped_mode or *cropped_mode != cropped) + spdlog::info("Stream FOV mode: {}", cropped ? "cropped" : "full"); + cropped_mode = cropped; +} + +void center::on_swapchain_recreated(bool cropped) +{ + dummy_swapchain = {}; + if (supports_meta() and cropped) + create_dummy_swapchain(); + set_cropped(cropped); +} + +bool center::update_meta_swapchain(XrSwapchain swapchain) const +{ + if (not supports_meta() or not swapchain) + return false; + + XrSwapchainStateFoveationFB swapchain_state{ + .type = XR_TYPE_SWAPCHAIN_STATE_FOVEATION_FB, + .flags = 0, + .profile = *foveation_profile, + }; + + XrResult update_result = xrUpdateSwapchainFB( + swapchain, + reinterpret_cast(&swapchain_state)); + return XR_SUCCEEDED(update_result); +} + +std::optional center::meta_angles(XrSwapchain swapchain, std::span fov) const +{ + if (not update_meta_swapchain(swapchain)) + return {}; + + XrFoveationEyeTrackedStateMETA state{ + .type = XR_TYPE_FOVEATION_EYE_TRACKED_STATE_META, + }; + + XrResult result = xrGetFoveationEyeTrackedStateMETA(session, &state); + if (XR_FAILED(result) or not(state.flags & XR_FOVEATION_EYE_TRACKED_STATE_VALID_BIT_META)) + return {}; + + std::array ndc_center{state.foveationCenter[0], state.foveationCenter[1]}; + return center_to_angles(ndc_center, fov); +} + +void center::update(std::span submitted_fov, std::span valid, XrSwapchain stream_swapchain, XrTime display_time) +{ + assert(submitted_fov.size() == view_count and valid.size() == view_count); + layer_.reset(); + packet_.reset(); + + XrSpace view_space = application::space(xr::spaces::view); + auto [view_flags, views] = session.locate_views( + XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO, display_time, view_space); + + constexpr XrViewStateFlags layer_flags = + XR_VIEW_STATE_POSITION_VALID_BIT | XR_VIEW_STATE_ORIENTATION_VALID_BIT; + if (supports_meta() and cropped_mode.value_or(false) and dummy_swapchain and + views.size() == view_count and (view_flags & layer_flags) == layer_flags) + { + projection_layer layer{ + .flags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + .space = view_space, + }; + for (size_t i = 0; i < view_count; ++i) + { + layer.views[i] = { + .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, + .pose = views[i].pose, + .fov = headset_fov[i], + .subImage = { + .swapchain = dummy_swapchain, + .imageRect = { + .offset = {0, 0}, + .extent = {dummy_swapchain_size, dummy_swapchain_size}, + }, + .imageArrayIndex = uint32_t(i), + }, + }; + } + layer_ = layer; + } + + if (views.size() != view_count or not(view_flags & XR_VIEW_STATE_POSITION_VALID_BIT)) + return; + + // dummy layer is always full FOV + std::array effective_fov{}; + for (size_t i = 0; i < view_count; ++i) + effective_fov[i] = valid[i] ? submitted_fov[i] : headset_fov[i]; + const XrSwapchain meta_swapchain = cropped_mode.value_or(false) ? static_cast(dummy_swapchain) : stream_swapchain; + const std::span meta_fov = cropped_mode.value_or(false) ? std::span(headset_fov) : std::span(effective_fov); + + const auto manual = get_manual_mode(); + std::optional angles; + if (manual.enabled) + { + if (supports_meta()) + update_meta_swapchain(meta_swapchain); + angles = target_angles(0, manual.pitch, manual.distance, views); + } + else + { + if (supports_meta()) + { + if (auto a = meta_angles(meta_swapchain, meta_fov)) + angles = *a; + } + if (not angles and application::get_eye_gaze_supported()) + { + if (auto a = eye_gaze_angles(application::space(xr::spaces::eye_gaze), + view_space, + display_time, + view_flags, + views)) + angles = *a; + } + if (not angles) + angles = target_angles(0, default_foveation_pitch, default_convergence_distance, views); + } + // angles guaranteed to have a value at this point + packet_ = wivrn::from_headset::foveation{.angles = *angles}; +} + +std::optional center::get_layer() const +{ + return layer_; +} + +std::optional center::take_packet() +{ + // A skipped render must not resend the previous frame's center. + auto result = packet_; + packet_.reset(); + return result; +} + +void center::create_dummy_swapchain() +{ + device.waitIdle(); + + dummy_swapchain = xr::swapchain( + instance, + session, + device, + swapchain_format, + dummy_swapchain_size, + dummy_swapchain_size, + 1, + view_count, + true, + true); + + if (not update_meta_swapchain(dummy_swapchain)) + throw std::runtime_error("Failed to apply eye-tracked foveation profile to dummy swapchain"); + + const int image_index = dummy_swapchain.acquire(); + dummy_swapchain.wait(); + + auto clear_command_buffer = std::move(device.allocateCommandBuffers({ + .commandPool = *commandpool, + .level = vk::CommandBufferLevel::ePrimary, + .commandBufferCount = 1, + })[0]); + auto clear_fence = device.createFence({}); + + clear_command_buffer.begin(vk::CommandBufferBeginInfo{ + .flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit, + }); + + vk::ImageMemoryBarrier to_transfer{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eTransferWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eTransferDstOptimal, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = dummy_swapchain.image(image_index), + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = view_count, + }, + }; + clear_command_buffer.pipelineBarrier( + vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eTransfer, + {}, + {}, + {}, + to_transfer); + + clear_command_buffer.clearColorImage( + dummy_swapchain.image(image_index), + vk::ImageLayout::eTransferDstOptimal, + vk::ClearColorValue{std::array{0, 0, 0, 0}}, + to_transfer.subresourceRange); + + vk::ImageMemoryBarrier to_runtime{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eMemoryRead, + .oldLayout = vk::ImageLayout::eTransferDstOptimal, + .newLayout = vk::ImageLayout::eColorAttachmentOptimal, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = dummy_swapchain.image(image_index), + .subresourceRange = to_transfer.subresourceRange, + }; + clear_command_buffer.pipelineBarrier( + vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eAllCommands, + {}, + {}, + {}, + to_runtime); + clear_command_buffer.end(); + + vk::SubmitInfo submit_info; + submit_info.setCommandBuffers(*clear_command_buffer); + queue.lock()->submit(submit_info, *clear_fence); + if (device.waitForFences(*clear_fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout) + throw std::runtime_error("Vulkan fence timeout while clearing foveation dummy swapchain"); + + dummy_swapchain.release(); + spdlog::info( + "Created {}x{} eye-tracked foveation dummy swapchain", + dummy_swapchain_size, + dummy_swapchain_size); +} + +} // namespace client_foveation diff --git a/client/foveation.h b/client/foveation.h new file mode 100644 index 00000000..d9e169fd --- /dev/null +++ b/client/foveation.h @@ -0,0 +1,112 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 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 "utils/handle.h" +#include "utils/thread_safe.h" +#include "wivrn_packets.h" +#include "xr/swapchain.h" + +#include +#include +#include +#include + +namespace xr +{ +class instance; +class session; +class system; +} // namespace xr + +namespace client_foveation +{ +using angles = std::array; + +inline constexpr float default_convergence_distance = 1.0f; +// Default foveation target is 1 m forward and 10 degrees below horizontal. +inline constexpr float default_foveation_pitch = -0.17453292519943295f; // -10 degrees + +struct manual_override +{ + bool enabled = false; + float pitch = default_foveation_pitch; + float distance = default_convergence_distance; +}; + +// Unified class for static, meta and eye-gaze based foveation. +class center +{ +public: + static constexpr size_t view_count = 2; + static constexpr int32_t dummy_swapchain_size = 512; + + struct projection_layer + { + XrCompositionLayerFlags flags; + XrSpace space; + std::array views; + }; + + center(xr::instance &, xr::system &, xr::session &, vk::raii::Device &, vk::raii::CommandPool &, thread_safe &, vk::Format swapchain_format); + ~center(); + + bool supports_meta() const; + + manual_override get_manual_mode() const; + void set_manual_mode(manual_override mode); + + bool is_cropped(std::span submitted_fov, std::span valid) const; + bool needs_swapchain_recreation(bool cropped) const; + bool use_meta_swapchain(bool cropped) const; + void on_swapchain_recreated(bool cropped); + void set_cropped(bool cropped); + + void update(std::span submitted_fov, std::span valid, XrSwapchain stream_swapchain, XrTime display_time); + std::optional get_layer() const; + std::optional take_packet(); + +private: + mutable thread_safe manual_mode_{}; + + xr::instance & instance; + xr::session & session; + vk::raii::Device & device; + vk::raii::CommandPool & commandpool; + thread_safe & queue; + vk::Format swapchain_format; + + PFN_xrCreateFoveationProfileFB xrCreateFoveationProfileFB = nullptr; + PFN_xrDestroyFoveationProfileFB xrDestroyFoveationProfileFB = nullptr; + PFN_xrUpdateSwapchainFB xrUpdateSwapchainFB = nullptr; + PFN_xrGetFoveationEyeTrackedStateMETA xrGetFoveationEyeTrackedStateMETA = nullptr; + std::optional> foveation_profile; + + std::array headset_fov{}; + std::optional cropped_mode; + xr::swapchain dummy_swapchain; + std::optional layer_; + std::optional packet_; + + bool update_meta_swapchain(XrSwapchain swapchain) const; + std::optional meta_angles(XrSwapchain swapchain, std::span fov) const; + void create_dummy_swapchain(); +}; + +} // namespace client_foveation diff --git a/client/hmd_traits.cpp b/client/hmd_traits.cpp index 22c56df1..752b7b08 100644 --- a/client/hmd_traits.cpp +++ b/client/hmd_traits.cpp @@ -38,6 +38,7 @@ #include #include +#include #ifdef __ANDROID__ #include "utils/wrap_lambda.h" @@ -229,11 +230,13 @@ void hmd_traits::init() else if (manufacturer == "Play For Dream" and model == "PFDM MR") { + blacklisted_extensions.insert(XR_META_FOVEATION_EYE_TRACKED_EXTENSION_NAME); controller_profile = "yvr-touch-v2"; } else if (manufacturer == "Pico") { + blacklisted_extensions.insert(XR_META_FOVEATION_EYE_TRACKED_EXTENSION_NAME); permissions[feature::eye_gaze] = "com.picovr.permission.EYE_TRACKING"; permissions[feature::face_tracking] = "com.picovr.permission.FACE_TRACKING"; view_locate = false; @@ -315,6 +318,7 @@ void hmd_traits::init() } if (manufacturer == "samsung") { + blacklisted_extensions.insert(XR_META_FOVEATION_EYE_TRACKED_EXTENSION_NAME); if (model == "SM-I610") // Galaxy XR { panel_width_override = 3552; @@ -359,6 +363,8 @@ void hmd_traits::init() break; } + // frame: always returns 0,0 + blacklisted_extensions.insert(XR_META_FOVEATION_EYE_TRACKED_EXTENSION_NAME); #endif spdlog::info("HMD traits initialized"); diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index ffdd8b9c..3a32f508 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -40,6 +40,7 @@ #include "utils/ranges.h" #include "wivrn_packets.h" #include +#include #include #include #include @@ -200,7 +201,8 @@ static const std::array supported_depth_formats{ scenes::stream::stream(std::string server_name, scene & parent_scene) : scene_impl(supported_color_formats, supported_depth_formats, parent_scene), - apps{*this, std::move(server_name)} + apps{*this, std::move(server_name)}, + foveation_center{instance, system, session, device, commandpool, queue, swapchain_format} { auto views = system.view_configuration_views(viewconfig); width = views[0].recommendedImageRectWidth; @@ -387,20 +389,6 @@ std::shared_ptr scenes::stream::create(std::unique_ptroverride_foveation_enable = config.override_foveation_enable; - self->override_foveation_pitch = config.override_foveation_pitch; - self->override_foveation_distance = config.override_foveation_distance; - - if (self->override_foveation_enable) - self->network_session->send_control(from_headset::override_foveation_center{ - .enabled = self->override_foveation_enable, - .pitch = self->override_foveation_pitch, - .distance = self->override_foveation_distance, - }); - } - self->network_thread = utils::named_thread("network_thread", &stream::process_packets, self.get()); self->command_buffer = std::move(self->device.allocateCommandBuffers({ @@ -892,6 +880,33 @@ void scenes::stream::render(const XrFrameState & frame_state) } } + // Search for frame with desired display time on all decoders + // If no such frame exists, use the latest frame for each decoder + current_blit_handles = common_frame(frame_state.predictedDisplayTime); + std::array pose; + std::array fov{}; + std::array valid_fov{}; + std::array foveation; + std::array extents; + int32_t max_width = 0; + int32_t max_height = 0; + for (size_t i = 0; i < view_count; ++i) + { + auto & blit_handle = current_blit_handles[i]; + if (!blit_handle) + continue; + + fov[i] = blit_handle->view_info.fov[i]; + valid_fov[i] = true; + foveation[i] = blit_handle->view_info.foveation[i]; + extents[i] = stream_defoveator::defoveated_size(foveation[i]); + max_width = std::max(max_width, extents[i].width); + max_height = std::max(max_height, extents[i].height); + } + + if (max_width > 0 and max_height > 0) + ensure_foveation_mode(foveation_center.is_cropped(fov, valid_fov), max_width, max_height); + session.begin_frame(); #if WIVRN_FEATURE_RENDERDOC @@ -907,12 +922,6 @@ void scenes::stream::render(const XrFrameState & frame_state) command_buffer.resetQueryPool(*query_pool, 0, size_gpu_timestamps); command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, *query_pool, 0); - // Search for frame with desired display time on all decoders - // If no such frame exists, use the latest frame for each decoder - current_blit_handles = common_frame(frame_state.predictedDisplayTime); - std::array pose; - std::array fov; - std::array foveation; bool use_alpha = false; std::array images; @@ -1025,42 +1034,18 @@ void scenes::stream::render(const XrFrameState & frame_state) std::ranges::any_of(current_blit_handles, [](const auto & h) { return h and h->feedback.times_displayed < 2; }) or is_gui_interactable()) { - XrExtent2Di extents[view_count]; - { - int32_t max_width = 0; - int32_t max_height = 0; - for (size_t i = 0; i < view_count; ++i) - { - extents[i] = stream_defoveator::defoveated_size(foveation[i]); - max_width = std::max(max_width, extents[i].width); - max_height = std::max(max_height, extents[i].height); - } - if (not swapchain) - setup_reprojection_swapchain(max_width, max_height); - else if (swapchain.width() < max_width or swapchain.height() < max_height) - { - // If the defoveated image is larger than the swapchain, try to reallocate one - try - { - spdlog::info("Recreating swapchain, from {}x{} to {}x{}", - swapchain.width(), - swapchain.height(), - max_width, - max_height); - setup_reprojection_swapchain(max_width, max_height); - } - catch (std::exception & e) - { - spdlog::warn("failed to increase swapchain size"); - for (size_t i = 0; i < view_count; ++i) - { - extents[i].width = std::min(extents[i].width, swapchain.width()); - extents[i].height = std::min(extents[i].height, swapchain.height()); - } - } - } - } assert(swapchain); + + // Swapchains only recreated when switching between cropped/full + // Otherwise we clamp and resize the existing one + for (size_t i = 0; i < view_count; ++i) + { + extents[i].width = std::min(extents[i].width, swapchain.width()); + extents[i].height = std::min(extents[i].height, swapchain.height()); + } + + foveation_center.update(fov, valid_fov, swapchain, frame_state.predictedDisplayTime); + // defoveate the image, apply scale/bias int image_index = swapchain.acquire(); swapchain.wait(); @@ -1170,6 +1155,10 @@ void scenes::stream::render(const XrFrameState & frame_state) render_start(use_alpha, frame_state.predictedDisplayTime); + // full-FOV dummy layer for Meta foveation, used when cropping FOV + if (auto layer = foveation_center.get_layer()) + add_projection_layer(layer->flags, layer->space, layer->views); + // Add the layer with the streamed content std::array layer_view; for (uint32_t view = 0; view < view_count; view++) @@ -1220,7 +1209,8 @@ void scenes::stream::render(const XrFrameState & frame_state) { // Keep a copy of the feedback packets as they can be modified if they're encrypted inplace_vector feedbacks; - inplace_vector packets; + // +1 for optional foveation packet + inplace_vector packets; feedbacks.reserve(current_blit_handles.size()); packets.reserve(current_blit_handles.size()); @@ -1233,6 +1223,11 @@ void scenes::stream::render(const XrFrameState & frame_state) wivrn_session::control_socket_t::serialize(packet, feedbacks.emplace_back(handle->feedback)); } } + if (auto foveation_packet = foveation_center.take_packet()) + { + auto & packet = packets.emplace_back(); + wivrn_session::control_socket_t::serialize(packet, *foveation_packet); + } if (not packets.empty()) { try @@ -1304,7 +1299,7 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript defoveator->reset_pipelines(); } -void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint32_t swapchain_height) +void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint32_t swapchain_height, bool foveation) { assert(swapchain_width); assert(swapchain_height); @@ -1314,8 +1309,21 @@ void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint auto views = system.view_configuration_views(viewconfig); - swapchain = xr::swapchain(instance, session, device, swapchain_format, swapchain_width, swapchain_height, 1, views.size()); - spdlog::info("Created stream swapchain: {}x{}", swapchain.width(), swapchain.height()); + swapchain = xr::swapchain( + instance, + session, + device, + swapchain_format, + swapchain_width, + swapchain_height, + 1, + views.size(), + foveation); + spdlog::info( + "Created stream swapchain: {}x{}{}", + swapchain.width(), + swapchain.height(), + foveation ? " with eye-tracked foveation" : ""); for (auto view: views) { if (swapchain.width() > view.maxImageRectWidth or swapchain.height() > view.maxImageRectHeight) @@ -1333,6 +1341,19 @@ void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint swapchain.format()); } +void scenes::stream::ensure_foveation_mode(bool cropped, uint32_t width, uint32_t height) +{ + if (!swapchain or foveation_center.needs_swapchain_recreation(cropped)) + { + setup_reprojection_swapchain(width, height, foveation_center.use_meta_swapchain(cropped)); + foveation_center.on_swapchain_recreated(cropped); + } + else + { + foveation_center.set_cropped(cropped); + } +} + scene::meta & scenes::stream::get_meta_scene() { static meta m{ diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 4fa5d494..0e134124 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -24,6 +24,7 @@ #include "audio/audio.h" #include "configuration.h" #include "decoder/shard_accumulator.h" +#include "foveation.h" #include "render/imgui_impl.h" #include "scene.h" #include "scenes/input_profile.h" @@ -119,6 +120,7 @@ private: state_.compare_exchange_strong(prev, new_state); } + client_foveation::center foveation_center; xr::swapchain swapchain; std::optional