diff --git a/.github/pull.yml b/.github/pull.yml new file mode 100644 index 00000000..397643b9 --- /dev/null +++ b/.github/pull.yml @@ -0,0 +1,6 @@ +version: "1" +rules: + - base: master + upstream: WiVRn:master + mergeMethod: hardreset + \ No newline at end of file diff --git a/.github/workflows/APK-Release.yml b/.github/workflows/APK-Release.yml index 545d9330..4eec207d 100644 --- a/.github/workflows/APK-Release.yml +++ b/.github/workflows/APK-Release.yml @@ -22,9 +22,14 @@ jobs: - uses: actions/checkout@v4 with: # Checkout from upstream instead of WiVRn-APK to ensure the GIT_DESC variable is set correctly - repository: 'WiVRn/WiVRn' + repository: 'Vindicus999/WiVRn' ref: ${{ github.sha }} fetch-depth: 0 + # + # - uses: actions/checkout@v4 + # with: + # repository: 'Vindicus999/WiVRn' + # ref: sneed - name: set up JDK uses: actions/setup-java@v4 @@ -68,7 +73,9 @@ jobs: - name: Prepare before archiving artifacts run: | mkdir apk + ls build/outputs/apk/ mv $(find build/outputs/apk/ -name "*.apk") apk/ + ls apk/ mkdir debug mv build/intermediates/merged_native_libs/*/*/out/lib/* debug/ find debug -name libopenxr_loader.so -delete @@ -102,13 +109,15 @@ jobs: pattern: 'apk-*' merge-multiple: true - - name: Rename APK artifacts - run: | - cd apk - for f in *.apk; do - BASENAME=`echo ${f}|awk -F '-APK-' '{print $2}'` - mv "${f}" "org.meumeu.wivrn-${BASENAME}" - done + # - name: Rename APK artifacts + # run: | + # cd apk + # ls + # for f in *.apk; do + # BASENAME=`echo ${f}|awk -F '-APK-' '{print $2}'` + # mv "${f}" "org.meumeu.wivrn-${BASENAME}" + # done + # ls - name: Download APK debug artifacts uses: actions/download-artifact@v4 @@ -122,6 +131,11 @@ jobs: cd symbols zip -r ../debug-symbols.zip . + - name: How the hell doesnt it work + run: | + ls apk + ls + - name: APK Release uses: softprops/action-gh-release@v2 with: diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index e61a4874..d2fb4b61 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -124,7 +124,7 @@ jobs: run: | git config --global --add safe.directory $(pwd) pip install toml aiohttp - tools/gen_flatpak_manifest.py --git https://github.com/${{github.repository}}.git --out flatpak + tools/gen_flatpak_manifest.py --gitlocal --out flatpak cat flatpak/io.github.wivrn.wivrn.yml - uses: flatpak/flatpak-github-actions/flatpak-builder@v6.4 @@ -153,11 +153,13 @@ jobs: nix-test: name: Test Nix package and devshell runs-on: ubuntu-24.04 + if: ${{ vars.APK_ONLY == '' }} + steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - + - uses: cachix/install-nix-action@v31 - run: nix flake check - run: nix build @@ -242,7 +244,7 @@ jobs: WIVRN_SERVER_PID=$! mkdir -p ~/.config/wivrn - echo '{"servers": [{"autoconnect": false, "manual": true, "pretty_name": "Deep Thought", "hostname": "localhost", "port": 9757, "tcp_only": false, "cookie": ""}]}' > ~/.config/wivrn/client.json.in + echo '{"servers": [{"autoconnect": false, "manual": true, "pretty_name": "Deep Thought", "hostname": "localhost", "port": 9757, "tcp_only": false, "cookie": ""}], "first_run": false}' > ~/.config/wivrn/client.json.in for LANG in en $(basename -a ${{github.workspace}}/locale/*) do @@ -574,7 +576,7 @@ jobs: git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" git config --global user.name "github-actions[bot]" - sudo apt-get install python-toml python-aiohttp + sudo apt-get install python3-toml python3-aiohttp cd flathub git remote add upstream https://github.com/flathub/io.github.wivrn.wivrn.git diff --git a/.github/workflows/Sync.yml b/.github/workflows/Sync.yml new file mode 100644 index 00000000..240c2d11 --- /dev/null +++ b/.github/workflows/Sync.yml @@ -0,0 +1,34 @@ +name: Sync Upstream + +env: + UPSTREAM_URL: "https://github.com/wivrn/wivrn.git" + WORKFLOW_TOKEN: ${{ secrets.DOWNSTREAM_GITHUB_TOKEN }} + UPSTREAM_BRANCH: "master" + +on: + schedule: + - cron: '0 5/6 * * *' + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: GitHub Sync to Upstream Repository + uses: dabreadman/sync-upstream-repo@v1.3.0 + with: + upstream_repo: ${{ env.UPSTREAM_URL }} + upstream_branch: ${{ env.UPSTREAM_BRANCH }} + token: ${{ env.WORKFLOW_TOKEN }} + + - name: Checkout stuff + uses: actions/checkout@master + + - name: Merge sneed -> master + uses: devmasx/merge-branch@master + with: + type: now + from_branch: sneed + target_branch: master + github_token: ${{ env.WORKFLOW_TOKEN }} + diff --git a/AndroidManifest.xml b/AndroidManifest.xml index dddc5896..7f9b6505 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -88,6 +88,8 @@ + + diff --git a/CMakeLists.txt b/CMakeLists.txt index 97e4d1fd..cad020f5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.25) +cmake_minimum_required(VERSION 3.28) project(WiVRn VERSION 0.0.0 LANGUAGES C CXX) # Set default for FetchContent projects @@ -31,6 +31,7 @@ option(WIVRN_BUILD_SERVER_LIBRARY "Build OpenXR library for WiVRn server" ${WIVR option(WIVRN_BUILD_DASHBOARD "Build WiVRn dashboard" OFF) option(WIVRN_BUILD_WIVRNCTL "Build wivrnctl" ON) option(WIVRN_BUILD_DISSECTOR "Build Wireshark dissector" OFF) +option(WIVRN_BUILD_TEST "Build test binaries" OFF) option(WIVRN_WERROR "Treat warnings as errors" OFF) option(WIVRN_USE_NVENC "Enable nvenc (Nvidia) hardware encoder" ON) @@ -239,9 +240,9 @@ endif() if (WIVRN_BUILD_DISSECTOR) if (WIVRN_USE_SYSTEM_OPENXR STREQUAL "AUTO") - find_package(OpenXR 1.0.34) + find_package(OpenXR 1.1.48) elseif(WIVRN_USE_SYSTEM_OPENXR STREQUAL "ON") - find_package(OpenXR 1.0.34 REQUIRED) + find_package(OpenXR 1.1.48 REQUIRED) endif() find_package(Wireshark REQUIRED) endif() @@ -273,15 +274,17 @@ FetchContent_Declare(stb EXCLUDE_FROM_ALL SYSTEM URL https://github.co FetchContent_Declare(libktx EXCLUDE_FROM_ALL SYSTEM GIT_REPOSITORY https://github.com/KhronosGroup/KTX-Software GIT_TAG 91ace88675ac59a97e55d0378a6602a9ae6b98bd) -FetchContent_Declare(implot EXCLUDE_FROM_ALL SYSTEM URL https://github.com/epezent/implot/archive/refs/tags/v0.16.tar.gz - URL_HASH SHA256=961df327d8a756304d1b0a67316eebdb1111d13d559f0d3415114ec0eb30abd1) +FetchContent_Declare(implot EXCLUDE_FROM_ALL SYSTEM URL https://github.com/epezent/implot/archive/3da8bd34299965d3b0ab124df743fe3e076fa222.zip + URL_HASH SHA256=e9b439a94aa6f09fcf12ed9c2cd784efe5e99e96242122aa683e690b29f7a59f) file(GLOB IMGUI_PATCHES CONFIGURE_DEPENDS patches/imgui/*) -FetchContent_Declare(imgui EXCLUDE_FROM_ALL SYSTEM URL https://github.com/ocornut/imgui/archive/refs/tags/v1.91.3.tar.gz - URL_HASH SHA256=29949d7b300c30565fbcd66398100235b63aa373acfee0b76853a7aeacd1be28 +FetchContent_Declare(imgui EXCLUDE_FROM_ALL SYSTEM URL https://github.com/ocornut/imgui/archive/refs/tags/v1.92.1.tar.gz + URL_HASH SHA256=32c237c2abf67a2ffccaac17192f711d4a787554b4133187a153d49057d6109c PATCH_COMMAND ${CMAKE_CURRENT_LIST_DIR}/patches/apply.sh ${IMGUI_PATCHES} ) FetchContent_Declare(uni-algo EXCLUDE_FROM_ALL SYSTEM URL https://github.com/uni-algo/uni-algo/archive/v1.2.0.tar.gz URL_HASH SHA256=f2a1539cd8635bc6088d05144a73ecfe7b4d74ee0361fabed6f87f9f19e74ca9) +FetchContent_Declare(entt EXCLUDE_FROM_ALL SYSTEM URL https://github.com/skypjack/entt/archive/refs/tags/v3.15.0.tar.gz + URL_HASH SHA256=01466fcbf77618a79b62891510c0bbf25ac2804af5751c84982b413852234d66) file(GLOB MONADO_PATCHES CONFIGURE_DEPENDS patches/monado/*) set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS monado-rev) @@ -296,7 +299,9 @@ FetchContent_Declare(monado ) add_subdirectory(external) -add_subdirectory(common) +if (WIVRN_BUILD_CLIENT OR WIVRN_BUILD_SERVER OR WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_DISSECTOR) + add_subdirectory(common) +endif() if (WIVRN_BUILD_CLIENT) add_subdirectory(client) diff --git a/build.gradle b/build.gradle index cfdb5663..16d5e697 100644 --- a/build.gradle +++ b/build.gradle @@ -55,7 +55,7 @@ task "generatePngs"() { android { namespace "org.meumeu.wivrn" - ndkVersion "27.1.12297006" + ndkVersion "28.1.13356709" lint { disable += "ExpiredTargetSdkVersion" @@ -72,6 +72,7 @@ android { versionName = project.hasProperty('wivrn_version') ? wivrn_version : "1.0" versionCode = project.hasProperty('wivrn_versionCode') ? wivrn_versionCode.toInteger() : 1 def showImguiDemo = project.hasProperty('wivrn_show_imgui_demo') ? wivrn_show_imgui_demo : 'OFF' + def showDebugMenu = project.hasProperty('wivrn_show_debug_menu') ? wivrn_show_debug_menu : 'OFF' externalNativeBuild { def css = project.hasProperty('wivrn_css') ? project.wivrn_css: "images/wivrn-local.css" @@ -90,6 +91,7 @@ android { '-DWIVRN_BUILD_DASHBOARD=OFF', '-DWIVRN_WERROR=ON', '-DWIVRN_SHOW_IMGUI_DEMO_WINDOW=' + showImguiDemo, + '-DWIVRN_CLIENT_DEBUG_MENU=' + showDebugMenu, '-DWIVRN_CSS=' + css resValue "string", "app_name", project.hasProperty('wivrn_app_name') ? project.wivrn_app_name : "WiVRn Local" } diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 736dd541..01059ded 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -7,7 +7,7 @@ set(KTX_FEATURE_LOADTEST_APPS OFF) set(FASTGLTF_COMPILE_AS_CPP20 ON) -FetchContent_MakeAvailable(simdjson spdlog glm fastgltf imgui stb implot uni-algo) +FetchContent_MakeAvailable(simdjson spdlog glm fastgltf imgui stb implot uni-algo entt) if (WIVRN_USE_LIBKTX) FetchContent_MakeAvailable(libktx) @@ -140,6 +140,10 @@ target_link_libraries(wivrn-imgui FreetypeHarfbuzz) target_link_libraries(wivrn wivrn-imgui) +############################################################################## +# EnTT +# +target_link_libraries(wivrn EnTT::EnTT) ############################################################################## # Vulkan Validation Layer diff --git a/client/application.cpp b/client/application.cpp index 026aa151..798010ac 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -26,7 +26,6 @@ #include "spdlog/spdlog.h" #include "utils/contains.h" #include "utils/files.h" -#include "utils/named_thread.h" #include "vk/check.h" #include "wifi_lock.h" #include "xr/actionset.h" @@ -51,6 +50,7 @@ #endif #ifdef __ANDROID__ +#include "utils/named_thread.h" #include #include @@ -66,15 +66,16 @@ struct interaction_profile { std::string profile_name; std::vector required_extensions; + XrVersion min_version = XR_MAKE_VERSION(1, 0, 0); + XrVersion max_version = XR_MAKE_VERSION(2, 0, 0); // exclusive std::vector input_sources; bool available; }; static std::vector interaction_profiles{ interaction_profile{ - "/interaction_profiles/khr/simple_controller", - {}, - { + .profile_name = "/interaction_profiles/khr/simple_controller", + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -90,11 +91,11 @@ static std::vector interaction_profiles{ "/user/hand/right/input/menu/click", "/user/hand/right/input/select/click", - }}, + }, + }, interaction_profile{ - "/interaction_profiles/oculus/touch_controller", - {}, - { + .profile_name = "/interaction_profiles/oculus/touch_controller", + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -129,11 +130,13 @@ static std::vector interaction_profiles{ "/user/hand/right/input/thumbstick/click", "/user/hand/right/input/thumbstick/touch", "/user/hand/right/input/thumbrest/touch", - }}, + }, + }, interaction_profile{ - " /interaction_profiles/facebook/touch_controller_pro", - {"XR_FB_touch_controller_pro"}, - { + .profile_name = "/interaction_profiles/facebook/touch_controller_pro", + .required_extensions = {"XR_FB_touch_controller_pro"}, + .max_version = XR_MAKE_VERSION(1, 1, 0), + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/left/output/haptic_trigger_fb", "/user/hand/left/output/haptic_thumb_fb", @@ -171,6 +174,7 @@ static std::vector interaction_profiles{ "/user/hand/right/input/b/click", "/user/hand/right/input/b/touch", "/user/hand/right/input/system/click", + "/user/hand/right/input/squeeze/value", "/user/hand/right/input/trigger/value", "/user/hand/right/input/trigger/touch", "/user/hand/right/input/thumbstick", @@ -183,11 +187,12 @@ static std::vector interaction_profiles{ "/user/hand/right/input/trigger/slide_fb", "/user/hand/right/input/trigger/proximity_fb", "/user/hand/right/input/thumb_fb/proximity_fb", - }}, + }, + }, interaction_profile{ - " /interaction_profiles/meta/touch_pro_controller", - {"XR_VERSION_1_1"}, - { + .profile_name = "/interaction_profiles/meta/touch_pro_controller", + .min_version = XR_MAKE_VERSION(1, 1, 0), + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/left/output/haptic_trigger", "/user/hand/left/output/haptic_thumb", @@ -238,12 +243,13 @@ static std::vector interaction_profiles{ "/user/hand/right/input/thumbrest/touch", "/user/hand/right/input/thumbrest/force", "/user/hand/right/input/stylus/force", - - }}, + }, + }, interaction_profile{ - " /interaction_profiles/meta/touch_controller_plus", - {"XR_META_touch_controller_plus"}, - { + .profile_name = "/interaction_profiles/meta/touch_controller_plus", + .required_extensions = {"XR_META_touch_controller_plus"}, + .max_version = XR_MAKE_VERSION(1, 1, 0), + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -287,11 +293,12 @@ static std::vector interaction_profiles{ "/user/hand/right/input/trigger/slide_meta", "/user/hand/right/input/trigger/force", - }}, + }, + }, interaction_profile{ - " /interaction_profiles/meta/touch_plus_controller", - {"XR_VERSION_1_1"}, - { + .profile_name = "/interaction_profiles/meta/touch_plus_controller", + .min_version = XR_MAKE_VERSION(1, 1, 0), + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -337,11 +344,12 @@ static std::vector interaction_profiles{ "/user/hand/right/input/thumbstick/touch", "/user/hand/right/input/thumbrest/touch", - }}, + }, + }, interaction_profile{ - "/interaction_profiles/bytedance/pico_neo3_controller", - {"XR_BD_controller_interaction"}, - { + .profile_name = "/interaction_profiles/bytedance/pico_neo3_controller", + .required_extensions = {"XR_BD_controller_interaction"}, + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -379,11 +387,12 @@ static std::vector interaction_profiles{ "/user/hand/right/input/thumbstick/click", "/user/hand/right/input/thumbstick/touch", - }}, + }, + }, interaction_profile{ - "/interaction_profiles/bytedance/pico4_controller", - {"XR_BD_controller_interaction"}, - { + .profile_name = "/interaction_profiles/bytedance/pico4_controller", + .required_extensions = {"XR_BD_controller_interaction"}, + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -421,11 +430,12 @@ static std::vector interaction_profiles{ "/user/hand/right/input/thumbstick/touch", "/user/hand/right/input/squeeze/click", "/user/hand/right/input/squeeze/value", - }}, + }, + }, interaction_profile{ - "/interaction_profiles/bytedance/pico4s_controller", - {"XR_BD_controller_interaction"}, - { + .profile_name = "/interaction_profiles/bytedance/pico4s_controller", + .required_extensions = {"XR_BD_controller_interaction"}, + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -463,11 +473,12 @@ static std::vector interaction_profiles{ "/user/hand/right/input/thumbstick/touch", "/user/hand/right/input/squeeze/click", "/user/hand/right/input/squeeze/value", - }}, + }, + }, interaction_profile{ - "/interaction_profiles/htc/vive_focus3_controller", - {"XR_HTC_vive_focus3_controller_interaction"}, - { + .profile_name = "/interaction_profiles/htc/vive_focus3_controller", + .required_extensions = {"XR_HTC_vive_focus3_controller_interaction"}, + .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -504,18 +515,48 @@ static std::vector interaction_profiles{ "/user/hand/right/input/thumbstick/click", "/user/hand/right/input/thumbstick/touch", "/user/hand/right/input/thumbrest/touch", - }}, - interaction_profile{ - "/interaction_profiles/htc/vive_xr_tracker", - {"XR_HTC_vive_xr_tracker_interaction", "XR_HTC_path_enumeration"}, - {}, + }, }, interaction_profile{ - "/interaction_profiles/ext/eye_gaze_interaction", - {"XR_EXT_eye_gaze_interaction"}, - { + .profile_name = "/interaction_profiles/ext/hand_interaction_ext", + .required_extensions = {"XR_EXT_hand_interaction"}, + .input_sources = { + "/user/hand/left/input/aim/pose", + "/user/hand/left/input/grip/pose", + + "/user/hand/left/input/pinch_ext/pose", + "/user/hand/left/input/pinch_ext/value", + "/user/hand/left/input/pinch_ext/ready_ext", + "/user/hand/left/input/poke_ext/pose", + "/user/hand/left/input/aim_activate_ext/value", + "/user/hand/left/input/aim_activate_ext/ready_ext", + "/user/hand/left/input/grasp_ext/value", + "/user/hand/left/input/grasp_ext/ready_ext", + + "/user/hand/right/input/aim/pose", + "/user/hand/right/input/grip/pose", + + "/user/hand/right/input/pinch_ext/pose", + "/user/hand/right/input/pinch_ext/value", + "/user/hand/right/input/pinch_ext/ready_ext", + "/user/hand/right/input/poke_ext/pose", + "/user/hand/right/input/aim_activate_ext/value", + "/user/hand/right/input/aim_activate_ext/ready_ext", + "/user/hand/right/input/grasp_ext/value", + "/user/hand/right/input/grasp_ext/ready_ext", + }, + }, + interaction_profile{ + .profile_name = "/interaction_profiles/htc/vive_xr_tracker", + .required_extensions = {"XR_HTC_vive_xr_tracker_interaction", "XR_HTC_path_enumeration"}, + }, + interaction_profile{ + .profile_name = "/interaction_profiles/ext/eye_gaze_interaction", + .required_extensions = {"XR_EXT_eye_gaze_interaction"}, + .input_sources = { "/user/eyes_ext/input/gaze_ext/pose", - }}, + }, + }, }; static const std::pair action_suffixes[] = @@ -544,6 +585,9 @@ static const std::pair action_suffixes[] = {"/joystick", XR_ACTION_TYPE_VECTOR2F_INPUT}, {"/trackball", XR_ACTION_TYPE_VECTOR2F_INPUT}, + // XR_EXT_hand_interaction + {"/ready_ext", XR_ACTION_TYPE_BOOLEAN_INPUT}, + // Output paths {"/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, {"/haptic_trigger", XR_ACTION_TYPE_VIBRATION_OUTPUT}, @@ -683,9 +727,10 @@ void application::initialize_vulkan() bool debug_utils_found = false; #endif spdlog::info("Available Vulkan instance extensions:"); + std::vector> extensions; for (vk::ExtensionProperties & i: vk_context.enumerateInstanceExtensionProperties(nullptr)) { - spdlog::info(" {} (version {})", i.extensionName.data(), i.specVersion); + extensions.emplace_back(i.extensionName.data(), i.specVersion); #ifndef NDEBUG if (!strcmp(i.extensionName, VK_EXT_DEBUG_REPORT_EXTENSION_NAME)) @@ -695,6 +740,9 @@ void application::initialize_vulkan() debug_utils_found = true; #endif } + std::ranges::sort(extensions); + for (const auto & [extension_name, spec_version]: extensions) + spdlog::info(" {} (version {})", extension_name, spec_version); #ifndef NDEBUG if (debug_utils_found && debug_report_found) @@ -773,11 +821,16 @@ void application::initialize_vulkan() vk_physical_device = xr_system_id.physical_device(vk_instance); physical_device_properties = vk_physical_device.getProperties(); - spdlog::info("Available Vulkan device extensions:"); + extensions.clear(); for (vk::ExtensionProperties & i: vk_physical_device.enumerateDeviceExtensionProperties()) + extensions.emplace_back(i.extensionName.data(), i.specVersion); + std::ranges::sort(extensions); + + spdlog::info("Available Vulkan device extensions:"); + for (const auto & [extension_name, spec_version]: extensions) { - spdlog::info(" {}", i.extensionName.data()); - if (auto it = optional_device_extensions.find(i.extensionName); it != optional_device_extensions.end()) + spdlog::info(" {} (version {})", extension_name, spec_version); + if (auto it = optional_device_extensions.find(extension_name); it != optional_device_extensions.end()) vk_device_extensions.push_back(it->data()); } @@ -909,23 +962,69 @@ void application::initialize_actions() std::unordered_map> suggested_bindings; + XrVersion api_version = xr_instance.get_api_version(); // Build the list of all possible input sources, without duplicates, // checking which profiles are supported by the runtime std::vector sources; for (auto & profile: interaction_profiles) { - profile.available = utils::contains_all(xr_extensions, profile.required_extensions); + profile.available = utils::contains_all(xr_extensions, profile.required_extensions) and profile.min_version <= api_version and profile.max_version > api_version; + + if (profile.profile_name.ends_with("khr/simple_controller")) + { + switch (guess_model()) + { + // Quest hand tracking creates a fake khr/simple_controller when hand tracking + // is enabled, this messes with native hand tracking + case model::meta_quest_3: + case model::meta_quest_pro: + case model::meta_quest_3s: + case model::oculus_quest_2: + profile.available = false; + default: + break; + } + } if (!profile.available) continue; - // Patch profile to add palm_ext - if (utils::contains(xr_extensions, XR_EXT_PALM_POSE_EXTENSION_NAME) // - and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") // - and not utils::contains(profile.input_sources, "/user/hand/left/input/palm_ext/pose")) + // Patch profile to add grip_surface or palm_ext + bool add_palms = true; + if (profile.profile_name.ends_with("ext/hand_interaction_ext")) { - profile.input_sources.push_back("/user/hand/left/input/palm_ext/pose"); - profile.input_sources.push_back("/user/hand/right/input/palm_ext/pose"); + switch (guess_model()) + { + // Quest breaks spec and does not support grip_surface for ext/hand_interaction_ext + case model::meta_quest_3: + case model::meta_quest_pro: + case model::meta_quest_3s: + case model::oculus_quest_2: + case model::oculus_quest: + add_palms = false; + break; + default: + break; + } + } + if (add_palms) + { + if ((api_version >= XR_MAKE_VERSION(1, 1, 0) or utils::contains(xr_extensions, XR_KHR_MAINTENANCE1_EXTENSION_NAME)) // + and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") // + and not utils::contains(profile.input_sources, "/user/hand/left/input/grip_surface/pose")) + { + spdlog::info("Adding grip_surface/pose for interaction profile {}", profile.profile_name); + profile.input_sources.push_back("/user/hand/left/input/grip_surface/pose"); + profile.input_sources.push_back("/user/hand/right/input/grip_surface/pose"); + } + else if (utils::contains(xr_extensions, XR_EXT_PALM_POSE_EXTENSION_NAME) // + and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") // + and not utils::contains(profile.input_sources, "/user/hand/left/input/palm_ext/pose")) + { + spdlog::info("Adding palm_ext/pose for interaction profile {}", profile.profile_name); + profile.input_sources.push_back("/user/hand/left/input/palm_ext/pose"); + profile.input_sources.push_back("/user/hand/right/input/palm_ext/pose"); + } } // Dynamically add VIVE XR Trackers to the profile if available @@ -966,16 +1065,24 @@ void application::initialize_actions() spaces[size_t(xr::spaces::grip_left)] = xr_session.create_action_space(a); else if (name == "/user/hand/left/input/aim/pose") spaces[size_t(xr::spaces::aim_left)] = xr_session.create_action_space(a); + else if (name == "/user/hand/left/input/palm_ext/pose" or name == "/user/hand/left/input/grip_surface/pose") + spaces[size_t(xr::spaces::palm_left)] = xr_session.create_action_space(a); + else if (name == "/user/hand/left/input/pinch_ext/pose") + spaces[size_t(xr::spaces::pinch_left)] = xr_session.create_action_space(a); + else if (name == "/user/hand/left/input/poke_ext/pose") + spaces[size_t(xr::spaces::poke_left)] = xr_session.create_action_space(a); else if (name == "/user/hand/right/input/grip/pose") spaces[size_t(xr::spaces::grip_right)] = xr_session.create_action_space(a); else if (name == "/user/hand/right/input/aim/pose") spaces[size_t(xr::spaces::aim_right)] = xr_session.create_action_space(a); + else if (name == "/user/hand/right/input/palm_ext/pose" or name == "/user/hand/right/input/grip_surface/pose") + spaces[size_t(xr::spaces::palm_right)] = xr_session.create_action_space(a); + else if (name == "/user/hand/right/input/pinch_ext/pose") + spaces[size_t(xr::spaces::pinch_right)] = xr_session.create_action_space(a); + else if (name == "/user/hand/right/input/poke_ext/pose") + spaces[size_t(xr::spaces::poke_right)] = xr_session.create_action_space(a); else if (name == "/user/eyes_ext/input/gaze_ext/pose") spaces[size_t(xr::spaces::eye_gaze)] = xr_session.create_action_space(a); - else if (name == "/user/hand/right/input/palm_ext/pose") - spaces[size_t(xr::spaces::palm_right)] = xr_session.create_action_space(a); - else if (name == "/user/hand/left/input/palm_ext/pose") - spaces[size_t(xr::spaces::palm_left)] = xr_session.create_action_space(a); else if (name.contains("/input/entity_htc/pose") && htc_body) htc_body->add(xr_session.create_action_space(a)); } @@ -999,20 +1106,23 @@ void application::initialize_actions() for (const scene::suggested_binding & j: i->bindings) { - // Skip unsupported profiles - if (!suggested_bindings.contains(j.profile_name)) - continue; - - std::vector & xr_bindings = suggested_bindings[j.profile_name]; - - for (const scene::action_binding & k: j.paths) + for (const auto & profile: j.profile_names) { - XrAction a = i->actions_by_name[k.action_name].first; - assert(a != XR_NULL_HANDLE); + // Skip unsupported profiles + if (!suggested_bindings.contains(profile)) + continue; - xr_bindings.push_back(XrActionSuggestedBinding{ - .action = a, - .binding = string_to_path(k.input_source)}); + std::vector & xr_bindings = suggested_bindings[profile]; + + for (const scene::action_binding & k: j.paths) + { + XrAction a = i->actions_by_name[k.action_name].first; + assert(a != XR_NULL_HANDLE); + + xr_bindings.push_back(XrActionSuggestedBinding{ + .action = a, + .binding = string_to_path(k.input_source)}); + } } } } @@ -1055,8 +1165,11 @@ void application::initialize() // Optional extensions std::vector opt_extensions; + opt_extensions.push_back(XR_KHR_LOCATE_SPACES_EXTENSION_NAME); + opt_extensions.push_back(XR_KHR_MAINTENANCE1_EXTENSION_NAME); opt_extensions.push_back(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME); opt_extensions.push_back(XR_EXT_HAND_TRACKING_EXTENSION_NAME); + opt_extensions.push_back(XR_EXT_HAND_INTERACTION_EXTENSION_NAME); opt_extensions.push_back(XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME); opt_extensions.push_back(XR_FB_PASSTHROUGH_EXTENSION_NAME); opt_extensions.push_back(XR_HTC_PASSTHROUGH_EXTENSION_NAME); @@ -1072,17 +1185,12 @@ void application::initialize() opt_extensions.push_back(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME); opt_extensions.push_back(XR_FB_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME); opt_extensions.push_back(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME); + opt_extensions.push_back(XR_EXT_USER_PRESENCE_EXTENSION_NAME); opt_extensions.push_back(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME); opt_extensions.push_back(XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME); for (const auto & i: interaction_profiles) - { - for (const auto & j: i.required_extensions) - { - if (not j.starts_with("XR_VERSION")) - opt_extensions.push_back(j); - } - } + opt_extensions.insert(opt_extensions.end(), i.required_extensions.begin(), i.required_extensions.end()); for (const auto & i: xr::instance::extensions()) { @@ -1103,7 +1211,10 @@ void application::initialize() xr_instance = xr::instance(app_info.name, extensions); #endif - spdlog::info("Created OpenXR instance, runtime {}, version {}", xr_instance.get_runtime_name(), xr_instance.get_runtime_version()); + spdlog::info("Created OpenXR instance, runtime {}, version {}, API version {}", + xr_instance.get_runtime_name(), + xr_instance.get_runtime_version(), + xr::to_string(xr_instance.get_api_version())); xr_system_id = xr::system(xr_instance, app_info.formfactor); spdlog::info("Created OpenXR system for form factor {}", xr::to_string(app_info.formfactor)); @@ -1132,40 +1243,6 @@ void application::initialize() XrSystemEyeGazeInteractionPropertiesEXT eye_gaze_properties = xr_system_id.eye_gaze_interaction_properties(); spdlog::info(" Eye gaze support: {}", (bool)eye_gaze_properties.supportsEyeGazeInteraction); eye_gaze_supported = eye_gaze_properties.supportsEyeGazeInteraction; - - if (eye_gaze_supported) - { - switch (guess_model()) - { - case model::pico_4_pro: - case model::pico_4_enterprise: - pico_face_tracking_supported = true; - break; - default: - pico_face_tracking_supported = false; - break; - } - } - else - pico_face_tracking_supported = false; - - spdlog::info(" PICO face tracking support: {}", (bool)pico_face_tracking_supported); - } - - if (utils::contains(xr_extensions, XR_FB_FACE_TRACKING2_EXTENSION_NAME)) - { - XrSystemFaceTrackingProperties2FB fb_face2_properties = xr_system_id.fb_face_tracking2_properties(); - spdlog::info(" FB face tracking support: {}", (bool)fb_face2_properties.supportsVisualFaceTracking); - fb_face_tracking2_supported = fb_face2_properties.supportsVisualFaceTracking; - } - - if (utils::contains(xr_extensions, XR_HTC_FACIAL_TRACKING_EXTENSION_NAME)) - { - XrSystemFacialTrackingPropertiesHTC htc_face_properties = xr_system_id.htc_face_tracking_properties(); - spdlog::info(" HTC eye tracking support: {}", (bool)htc_face_properties.supportEyeFacialTracking); - spdlog::info(" HTC lip tracking support: {}", (bool)htc_face_properties.supportLipFacialTracking); - htc_face_tracking_eye_supported = htc_face_properties.supportEyeFacialTracking; - htc_face_tracking_lip_supported = htc_face_properties.supportLipFacialTracking; } if (utils::contains(xr_extensions, XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME)) @@ -1212,24 +1289,35 @@ void application::initialize() right_hand = xr_session.create_hand_tracker(XR_HAND_RIGHT_EXT); } - if (fb_face_tracking2_supported) + if (utils::contains(xr_extensions, XR_FB_FACE_TRACKING2_EXTENSION_NAME)) { - fb_face_tracker2 = xr_session.create_fb_face_tracker2(); + XrSystemFaceTrackingProperties2FB fb_face2_properties = xr_system_id.fb_face_tracking2_properties(); + spdlog::info(" FB face tracking support: {}", (bool)fb_face2_properties.supportsVisualFaceTracking); + if (fb_face2_properties.supportsVisualFaceTracking) + face_tracker.emplace(xr_instance, xr_session); } - if (htc_face_tracking_eye_supported) + if (std::holds_alternative(face_tracker) && utils::contains(xr_extensions, XR_HTC_FACIAL_TRACKING_EXTENSION_NAME)) { - htc_face_tracker_eye = xr_session.create_htc_face_tracker(XR_FACIAL_TRACKING_TYPE_EYE_DEFAULT_HTC); + XrSystemFacialTrackingPropertiesHTC htc_face_properties = xr_system_id.htc_face_tracking_properties(); + spdlog::info(" HTC eye tracking support: {}", (bool)htc_face_properties.supportEyeFacialTracking); + spdlog::info(" HTC lip tracking support: {}", (bool)htc_face_properties.supportLipFacialTracking); + if (htc_face_properties.supportEyeFacialTracking || htc_face_properties.supportLipFacialTracking) + face_tracker.emplace(xr_instance, xr_session, htc_face_properties.supportEyeFacialTracking, htc_face_properties.supportLipFacialTracking); } - if (htc_face_tracking_lip_supported) + if (std::holds_alternative(face_tracker) && eye_gaze_supported) { - htc_face_tracker_lip = xr_session.create_htc_face_tracker(XR_FACIAL_TRACKING_TYPE_LIP_DEFAULT_HTC); - } - - if (pico_face_tracking_supported) - { - pico_face_tracker = xr_session.create_pico_face_tracker(); + switch (guess_model()) + { + case model::pico_4_pro: + case model::pico_4_enterprise: + spdlog::info(" PICO face tracking support: true"); + face_tracker.emplace(xr_instance, xr_session); + break; + default: + break; + } } if (utils::contains_all(xr_extensions, std::array{XR_FB_BODY_TRACKING_EXTENSION_NAME, XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME, XR_META_BODY_TRACKING_FIDELITY_EXTENSION_NAME})) @@ -1237,13 +1325,13 @@ void application::initialize() XrSystemBodyTrackingPropertiesFB fb_body_properties = xr_system_id.fb_body_tracking_properties(); spdlog::info(" FB body tracking support: {}", (bool)fb_body_properties.supportsBodyTracking); if (fb_body_properties.supportsBodyTracking) - body_tracker = xr_session.create_fb_body_tracker(); + body_tracker.emplace(xr_instance, xr_session); } if (std::holds_alternative(body_tracker) && utils::contains_all(xr_extensions, std::array{XR_HTC_PATH_ENUMERATION_EXTENSION_NAME, XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME})) { spdlog::info(" HTC body tracking support: true"); - body_tracker = xr_session.create_htc_body_tracker(); + body_tracker.emplace(xr_instance, xr_session); } if (std::holds_alternative(body_tracker) && utils::contains(xr_extensions, XR_BD_BODY_TRACKING_EXTENSION_NAME)) @@ -1251,7 +1339,7 @@ void application::initialize() XrSystemBodyTrackingPropertiesBD bd_body_properties = xr_system_id.bd_body_tracking_properties(); spdlog::info(" PICO body tracking support: {}", (bool)bd_body_properties.supportsBodyTracking); if (bd_body_properties.supportsBodyTracking) - body_tracker = xr_session.create_pico_body_tracker(); + body_tracker.emplace(xr_instance, xr_session); } vk::CommandPoolCreateInfo cmdpool_create_info; diff --git a/client/application.h b/client/application.h index 6a2d8af2..377749c1 100644 --- a/client/application.h +++ b/client/application.h @@ -129,17 +129,7 @@ class application : public singleton xr::hand_tracker left_hand; xr::hand_tracker right_hand; - bool fb_face_tracking2_supported = false; - xr::fb_face_tracker2 fb_face_tracker2; - - bool htc_face_tracking_eye_supported = false; - xr::htc_face_tracker htc_face_tracker_eye; - bool htc_face_tracking_lip_supported = false; - xr::htc_face_tracker htc_face_tracker_lip; - - bool pico_face_tracking_supported = false; - xr::pico_face_tracker pico_face_tracker; - + std::variant face_tracker; std::variant body_tracker; bool eye_gaze_supported = false; @@ -430,24 +420,9 @@ public: return instance().hand_tracking_supported; } - static bool get_fb_face_tracking2_supported() + static bool get_face_tracking_supported() { - return instance().fb_face_tracking2_supported; - } - - static bool get_htc_face_tracking_eye_supported() - { - return instance().htc_face_tracking_eye_supported; - } - - static bool get_htc_face_tracking_lip_supported() - { - return instance().htc_face_tracking_lip_supported; - } - - static bool get_pico_face_tracking_supported() - { - return instance().pico_face_tracking_supported; + return !std::holds_alternative(instance().face_tracker); } static bool get_body_tracking_supported() @@ -475,24 +450,9 @@ public: return instance().right_hand; } - static xr::fb_face_tracker2 & get_fb_face_tracker2() + static auto & get_face_tracker() { - return instance().fb_face_tracker2; - } - - static xr::htc_face_tracker & get_htc_face_tracker_eye() - { - return instance().htc_face_tracker_eye; - } - - static xr::htc_face_tracker & get_htc_face_tracker_lip() - { - return instance().htc_face_tracker_lip; - } - - static xr::pico_face_tracker & get_pico_face_tracker() - { - return instance().pico_face_tracker; + return instance().face_tracker; } static auto & get_body_tracker() @@ -516,6 +476,11 @@ public: return *instance().config; } + static XrSessionState get_session_state() + { + return instance().session_state; + } + static boost::locale::gnu_gettext::messages_info & get_messages_info() { return instance().messages_info; diff --git a/client/audio/android/audio.cpp b/client/audio/android/audio.cpp index 43afd64c..62f94799 100644 --- a/client/audio/android/audio.cpp +++ b/client/audio/android/audio.cpp @@ -291,7 +291,7 @@ void wivrn::android::audio::operator()(wivrn::audio_data && data) buffer_size_bytes.fetch_add(size); } -void wivrn::android::audio::set_mic_sate(bool running) +void wivrn::android::audio::set_mic_state(bool running) { if (not microphone) return; diff --git a/client/audio/android/audio.h b/client/audio/android/audio.h index 11edda85..a3eab804 100644 --- a/client/audio/android/audio.h +++ b/client/audio/android/audio.h @@ -78,7 +78,7 @@ public: void operator()(wivrn::audio_data &&); - void set_mic_sate(bool running); + void set_mic_state(bool running); static void get_audio_description(wivrn::from_headset::headset_info_packet & info); }; diff --git a/client/audio/audio.h b/client/audio/audio.h index 11189b2e..1564f065 100644 --- a/client/audio/audio.h +++ b/client/audio/audio.h @@ -42,7 +42,7 @@ public: ~audio() = default; void operator()(wivrn::audio_data &&) {} - void set_mic_sate(bool running) {} + void set_mic_state(bool running) {} static void get_audio_description(wivrn::from_headset::headset_info_packet & info) {} }; diff --git a/client/configuration.cpp b/client/configuration.cpp index 82b1f140..abe7f15e 100644 --- a/client/configuration.cpp +++ b/client/configuration.cpp @@ -106,18 +106,17 @@ bool configuration::check_feature(feature f) const { case model::htc_vive_focus_3: case model::htc_vive_focus_vision: - [[fallthrough]]; case model::htc_vive_xr_elite: - if (not(application::get_htc_face_tracking_eye_supported() or application::get_htc_face_tracking_lip_supported())) + if (not std::holds_alternative(application::get_face_tracker())) return false; break; case model::pico_4_pro: case model::pico_4_enterprise: - if (not application::get_pico_face_tracking_supported()) + if (not std::holds_alternative(application::get_face_tracker())) return false; break; default: - if (not application::get_fb_face_tracking2_supported()) + if (not std::holds_alternative(application::get_face_tracker())) return false; break; } @@ -206,9 +205,6 @@ configuration::configuration(xr::system & system) servers.emplace(data.service.txt["cookie"], data); } - if (auto val = root["show_performance_metrics"]; val.is_bool()) - show_performance_metrics = val.get_bool(); - if (auto val = root["preferred_refresh_rate"]; val.is_double()) preferred_refresh_rate = val.get_double(); @@ -246,6 +242,18 @@ configuration::configuration(xr::system & system) if (system.passthrough_supported() == xr::system::passthrough_type::no_passthrough) passthrough_enabled = false; + + if (auto val = root["override_foveation_enable"]; val.is_bool()) + override_foveation_enable = val.get_bool(); + + if (auto val = root["override_foveation_pitch"]; val.is_double()) + override_foveation_pitch = val.get_double(); + + if (auto val = root["override_foveation_distance"]; val.is_double()) + override_foveation_distance = val.get_double(); + + if (auto val = root["first_run"]; val.is_bool()) + first_run = val.get_bool(); } catch (std::exception & e) { @@ -258,7 +266,6 @@ configuration::configuration(xr::system & system) resolution_scale = 1.4; sgsr = {}; openxr_post_processing = {}; - show_performance_metrics = false; passthrough_enabled = system.passthrough_supported() == xr::system::passthrough_type::color; } } @@ -344,8 +351,7 @@ void configuration::save() std::ofstream json(application::get_config_path() / "client.json"); - json << "{\"servers\":[" << servers_str << "]," - << "\"show_performance_metrics\":" << std::boolalpha << show_performance_metrics; + json << "{\"servers\":[" << servers_str << "]"; if (preferred_refresh_rate) json << ",\"preferred_refresh_rate\":" << *preferred_refresh_rate; if (minimum_refresh_rate) @@ -362,5 +368,9 @@ void configuration::save() for (auto & [key, value]: features) json << "," << key << ":" << std::boolalpha << value; json << ",\"virtual_keyboard_layout\":" << json_string(virtual_keyboard_layout); + json << ",\"override_foveation_enable\":" << std::boolalpha << override_foveation_enable; + json << ",\"override_foveation_pitch\":" << override_foveation_pitch; + json << ",\"override_foveation_distance\":" << override_foveation_distance; + json << ",\"first_run\":" << std::boolalpha << first_run; json << "}"; } diff --git a/client/configuration.h b/client/configuration.h index cdfdd8f5..8d34faae 100644 --- a/client/configuration.h +++ b/client/configuration.h @@ -50,7 +50,6 @@ public: std::optional preferred_refresh_rate; std::optional minimum_refresh_rate; float resolution_scale = 1.4; - bool show_performance_metrics = false; bool passthrough_enabled = false; bool mic_unprocessed_audio = false; @@ -78,6 +77,12 @@ public: std::string virtual_keyboard_layout = "QWERTY"; + bool override_foveation_enable = false; + float override_foveation_pitch = 10 * M_PI / 180; + float override_foveation_distance = 3; + + bool first_run = true; + bool check_feature(feature f) const; void set_feature(feature f, bool state); @@ -90,6 +95,7 @@ private: public: configuration(xr::system &); + configuration() = default; void save(); }; diff --git a/client/constants.h b/client/constants.h index ad0b8222..69d817d8 100644 --- a/client/constants.h +++ b/client/constants.h @@ -18,7 +18,6 @@ #pragma once -#include #include #include #include @@ -91,7 +90,7 @@ constexpr float recenter_action_distance = 0.3; constexpr float initial_gui_distance = 0.5; // Skybox color -constexpr std::array sky_color = {0, 0.25, 0.5, 1}; +constexpr XrColor4f sky_color = {0, 0.25, 0.5, 1}; // Dimming scale/bias when a popup window is shown constexpr XrColor4f dimming_scale = {0.5, 0.5, 0.5, 1}; @@ -105,6 +104,16 @@ constexpr int zindex_controllers = 1; constexpr int zindex_recenter_tip = 2; } // namespace constants::lobby +namespace constants::stream +{ +constexpr float fade_delay = 3; +constexpr float fade_duration = 0.25; + +// Dimming for the streamed video when the GUI is interactable +constexpr float dimming_scale = 0.7; +constexpr float dimming_bias = 0.15; +} // namespace constants::stream + namespace constants::style { constexpr ImVec2 window_padding = {20, 20}; diff --git a/client/hardware.cpp b/client/hardware.cpp index c12960de..745be7bf 100644 --- a/client/hardware.cpp +++ b/client/hardware.cpp @@ -348,6 +348,24 @@ std::pair controller_offset(std::string_view profile, xr:: default: break; } + else if (profile == "meta-quest-touch-plus") + { + switch (space) + { + case xr::spaces::grip_left: + case xr::spaces::grip_right: + return {{0, -0.010, -0.025}, glm::angleAxis(glm::radians(-12.f), glm::vec3{1, 0, 0})}; + + case xr::spaces::aim_left: + return {{0, 0, 0.03}, {1, 0, 0, 0}}; + + case xr::spaces::aim_right: + return {{0, 0, 0.03}, {1, 0, 0, 0}}; + + default: + break; + } + } else if (profile == "htc-vive-focus-3") switch (space) { @@ -367,7 +385,7 @@ std::pair controller_offset(std::string_view profile, xr:: { case xr::spaces::grip_left: case xr::spaces::grip_right: - return {{0, -0.030, -0.040}, glm::angleAxis(glm::radians(-35.f), glm::vec3{1, 0, 0})}; + return {{0, -0.014, -0.048}, glm::angleAxis(glm::radians(-35.060f), glm::vec3{1, 0, 0})}; default: break; diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index c38be677..3ff6186f 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -382,46 +382,9 @@ imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii: style.Colors[ImGuiCol_ModalWindowDimBg] = {0, 0, 0, 0}; } -void imgui_context::add_chars(std::string_view sv) -{ - for (auto it = sv.begin(); it != sv.end();) - { - ImWchar c = (ImWchar)*it; - if (c < 0x80) - ++it; - else - it += ImTextCharFromUtf8(&c, it, sv.end()); - - if (!glyph_range_builder.GetBit(c)) - { - glyph_range_builder.AddChar(c); - glyph_range_dirty = true; - } - } -} - #ifdef __ANDROID__ -static std::vector find_font(const ImFontGlyphRangesBuilder & glyph_range_builder, const std::string & locale) +static std::vector find_font(std::u16string_view sample_text, const std::string & locale) { - std::u16string wtext; - std::u16string_view wtextview; - for (int i = 0; i < glyph_range_builder.UsedChars.Size; ++i) - { - std::uint32_t used_chars = glyph_range_builder.UsedChars[i]; - if (used_chars == 0) - continue; - - for (int j = 0; j < 32; ++j) - { - ImWchar c = i * 32 + j; - if (used_chars & (1 << j)) - { - wtext += c; - } - } - } - wtextview = wtext; - AFontMatcher * font_matcher = AFontMatcher_create(); if (!font_matcher) throw std::runtime_error("AFontMatcher_create"); @@ -432,18 +395,18 @@ static std::vector find_font(const ImFontGlyphRangesBuilder & glyph std::vector fonts; - while (!wtextview.empty()) + while (!sample_text.empty()) { uint32_t runlength = 0; - AFont * font = AFontMatcher_match(font_matcher, "sans-serif", (uint16_t *)wtextview.data(), wtextview.size(), &runlength); + AFont * font = AFontMatcher_match(font_matcher, "sans-serif", (uint16_t *)sample_text.data(), sample_text.size(), &runlength); fonts.emplace_back(AFont_getFontFilePath(font)); AFont_close(font); if (runlength == 0) break; - wtextview = wtextview.substr(runlength); + sample_text = sample_text.substr(runlength); } AFontMatcher_destroy(font_matcher); @@ -451,7 +414,7 @@ static std::vector find_font(const ImFontGlyphRangesBuilder & glyph return fonts; } #else -static std::vector find_font(ImFontGlyphRangesBuilder glyph_range_builder, const std::string & locale) +static std::vector find_font(std::u16string sample_text, const std::string & locale) { // See https://www.camconn.cc/post/how-to-fontconfig-lib-c/ @@ -470,21 +433,8 @@ static std::vector find_font(ImFontGlyphRangesBuilder glyph_range_b // Add the text to the pattern (to determine appropriate characters) FcCharSet * charset = FcCharSetCreate(); - for (int i = 8; i < glyph_range_builder.UsedChars.Size; ++i) - { - std::uint32_t used_chars = glyph_range_builder.UsedChars[i]; - if (used_chars == 0) - continue; - - for (int j = 0; j < 32; ++j) - { - ImWchar c = i * 32 + j; - if (used_chars & (1 << j)) - { - FcCharSetAddChar(charset, c); - } - } - } + for (char16_t c: sample_text) + FcCharSetAddChar(charset, c); FcPatternAddCharSet(pattern, FC_CHARSET, charset); FcCharSetDestroy(charset); @@ -513,28 +463,26 @@ static std::vector find_font(ImFontGlyphRangesBuilder glyph_range_b continue; bool keep_this_font = false; - for (int i = 0; i < glyph_range_builder.UsedChars.Size; ++i) - { - std::uint32_t & used_chars = glyph_range_builder.UsedChars[i]; - if (used_chars == 0) - continue; - for (int j = 0; j < 32; ++j) + std::u16string tmp = sample_text; + for (int i = 0; i < tmp.size();) + { + char16_t c = tmp[i]; + + if (FcCharSetHasChar(font_charset, c)) { - ImWchar c = i * 32 + j; - if (used_chars & (1 << j)) - { - if (FcCharSetHasChar(font_charset, c)) - { - keep_this_font = true; - used_chars &= ~(1 << j); - } - } + keep_this_font = true; + + tmp[i] = tmp[tmp.size() - 1]; + tmp.resize(tmp.size() - 1); } + else + ++i; } if (keep_this_font) fonts.emplace_back((const char *)font_file); + break; } FcFontSetDestroy(fs); @@ -546,29 +494,19 @@ static std::vector find_font(ImFontGlyphRangesBuilder glyph_range_b void imgui_context::initialize_fonts() { - glyph_ranges.clear(); + std::u16string sample_text = u"Hello world"; - // Always include Basic Latin and Latin-1 Supplement without control characters - ImWchar default_ranges[] = {0x20, 0x7f, 0xa0, 0xff, 0}; - glyph_range_builder.AddRanges(default_ranges); + const auto & locale = application::get_messages_info(); + auto it = glyph_set_per_language.find(locale.language + "_" + locale.country); + if (it == glyph_set_per_language.end()) + it = glyph_set_per_language.find(locale.language); - { - const auto & locale = application::get_messages_info(); - auto it = glyph_set_per_language.find(locale.language + "_" + locale.country); - if (it == glyph_set_per_language.end()) - it = glyph_set_per_language.find(locale.language); - - if (it != glyph_set_per_language.end()) - { - for (ImWchar c: it->second) - glyph_range_builder.AddChar(c); - } - } - - glyph_range_builder.BuildRanges(&glyph_ranges); + if (it != glyph_set_per_language.end()) + for (char16_t c: it->second) + sample_text += c; // Load Fonts - auto fonts = find_font(glyph_range_builder, application::get_messages_info().language); + auto fonts = find_font(sample_text, application::get_messages_info().language); for (auto & i: fonts) { spdlog::info("Font {}", i); @@ -577,40 +515,20 @@ void imgui_context::initialize_fonts() asset font_awesome_regular("Font Awesome 6 Free-Regular-400.otf"); asset font_awesome_solid("Font Awesome 6 Free-Solid-900.otf"); - IM_DELETE(io.Fonts); - io.Fonts = IM_NEW(ImFontAtlas); + ImFontConfig config; + config.FontDataOwnedByAtlas = false; + for (auto & font: fonts) { - ImFontConfig config; - config.FontDataOwnedByAtlas = false; - - for (auto & font: fonts) - { - spdlog::info("Using font {}", font, application::get_messages_info().language); - io.Fonts->AddFontFromFileTTF(font.c_str(), constants::gui::font_size_small, &config, glyph_ranges.Data); - config.MergeMode = true; - } - + spdlog::info("Using font {}", font, application::get_messages_info().language); + io.Fonts->AddFontFromFileTTF(font.c_str(), constants::gui::font_size_small, &config); config.MergeMode = true; - config.GlyphMinAdvanceX = 40; // Use if you want to make the icon monospaced - static const ImWchar icon_ranges[] = {ICON_MIN_FA, ICON_MAX_FA, 0}; - io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_regular.data()), font_awesome_regular.size(), constants::gui::font_size_small, &config, icon_ranges); - io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_solid.data()), font_awesome_solid.size(), constants::gui::font_size_small, &config, icon_ranges); } - { - ImFontConfig config; - config.FontDataOwnedByAtlas = false; - for (auto & font: fonts) - { - large_font = io.Fonts->AddFontFromFileTTF(font.c_str(), constants::gui::font_size_large, &config, glyph_ranges.Data); - config.MergeMode = true; - } - } - - glyph_range_dirty = false; - - ImGui_ImplVulkan_CreateFontsTexture(); + config.MergeMode = true; + config.GlyphMinAdvanceX = 40; // Use if you want to make the icon monospaced + io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_regular.data()), font_awesome_regular.size(), constants::gui::font_size_small, &config); + io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_solid.data()), font_awesome_solid.size(), constants::gui::font_size_small, &config); } std::vector imgui_context::read_controllers_state(XrTime display_time) @@ -627,6 +545,9 @@ std::vector imgui_context::read_controllers_sta controller_state & new_state = new_states.emplace_back(); + if (not controllers_enabled) + continue; + if (ctrl.hand) { if (auto joints = ctrl.hand->locate(world, display_time)) @@ -841,24 +762,6 @@ void imgui_context::new_frame(XrTime display_time) controller.second = next_state; } - // Force recreation of the font atlas - if (glyph_range_dirty) - { - // Wait for fences before ImGui_ImplVulkan_DestroyFontsTexture is called - std::vector fences; - for (auto & f: command_buffers) - { - fences.push_back(*f.fence); - } - - if (auto result = device.waitForFences(fences, true, 1'000'000'000); result != vk::Result::eSuccess) - spdlog::error("vkWaitForfences: {}", vk::to_string(result)); - - ImGui_ImplVulkan_DestroyFontsTexture(); - initialize_fonts(); - ImGui_ImplVulkan_CreateFontsTexture(); - } - // Start the Dear ImGui frame ImGui_ImplVulkan_NewFrame(); @@ -876,10 +779,20 @@ void imgui_context::new_frame(XrTime display_time) image_index = swapchain.acquire(); swapchain.wait(); + + hovered_item_prev = hovered_item; + hovered_item = 0; } std::vector> imgui_context::end_frame() { + if (hovered_item != hovered_item_prev && hovered_item != 0) + { + size_t controller = get_focused_controller(); + if (auto haptic_output = controllers[controller].first.haptic_output; haptic_output != XR_NULL_HANDLE) + application::haptic_start(haptic_output, XR_NULL_PATH, 10'000'000, 1000, 1); + } + vk::Image destination = swapchain.images()[image_index].image; ImGui::SetCurrentContext(context); @@ -1070,6 +983,17 @@ std::vector> imgui_context::end_frame() return quads; } +void imgui_context::vibrate_on_hover() +{ + if (ImGui::IsItemHovered()) + hovered_item = ImGui::GetItemID(); +} + +void imgui_context::set_hovered_item() +{ + hovered_item = ImGui::GetItemID(); +} + imgui_context::~imgui_context() { ImGui::SetCurrentContext(context); @@ -1119,7 +1043,7 @@ ImTextureID imgui_context::load_texture(const std::string & filename, vk::raii:: device.updateDescriptorSets(ds_write, nullptr); - ImTextureID id = *ds; + ImTextureID id = reinterpret_cast(VkDescriptorSet(*ds)); textures.emplace( id, @@ -1159,6 +1083,11 @@ void imgui_context::set_current() ImPlot::SetCurrentContext(plot_context); } +void imgui_context::set_controllers_enabled(bool value) +{ + controllers_enabled = value; +} + bool imgui_context::is_modal_popup_shown() const { return ImGui::GetTopMostAndVisiblePopupModal() != nullptr; @@ -1174,3 +1103,50 @@ imgui_context::viewport & imgui_context::layer(ImVec2 position) return layers_.front(); } + +void imgui_context::tooltip(std::string_view text) +{ + // FIXME: this is incorrect if we use the docking branch of imgui + ImGuiViewport * viewport = ImGui::GetMainViewport(); + auto & current_layer = layer(ImGui::GetMousePos()); + auto pos_backup = viewport->Pos; + auto size_backup = viewport->Size; + viewport->Pos = ImVec2(current_layer.vp_origin.x, current_layer.vp_origin.y); + viewport->Size = ImVec2(current_layer.vp_size.x, current_layer.vp_size.y); + + ImVec2 pos{ + (ImGui::GetItemRectMin().x + ImGui::GetItemRectMax().x) / 2, + ImGui::GetItemRectMin().y - constants::style::tooltip_distance, + }; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::tooltip_padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::tooltip_rounding); + + // Clamp position to avoid overflowing on the left or the right + auto & style = ImGui::GetStyle(); + const ImVec2 text_size = ImGui::CalcTextSize(text.data(), text.data() + text.size(), true); + const ImVec2 size = {text_size.x + style.WindowPadding.x * 2.0f, text_size.y + style.WindowPadding.y * 2.0f}; + pos.x = std::clamp(pos.x, viewport->Pos.x + size.x / 2, viewport->Pos.x + viewport->Size.x - size.x / 2); + ImVec2 pivot = {0.5, 1}; + + // Move tooltip below the item if it overflows on the top + if (pos.y - size.y <= viewport->Pos.y) + { + pos.y = ImGui::GetItemRectMax().y + constants::style::tooltip_distance; + pivot.y = 0; + } + + ImGui::SetNextWindowPos(pos, ImGuiCond_Always, pivot); + if (ImGui::BeginTooltip()) + { + ImGui::PushStyleColor(ImGuiCol_Text, 0xffffffff); + ImGui::TextUnformatted(text.data(), text.data() + text.size()); + ImGui::PopStyleColor(); + ImGui::EndTooltip(); + } + + ImGui::PopStyleVar(2); + + viewport->Pos = pos_backup; + viewport->Size = size_backup; +} diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h index 95a507c9..cedb31a1 100644 --- a/client/render/imgui_impl.h +++ b/client/render/imgui_impl.h @@ -67,6 +67,8 @@ public: XrAction scroll; // XR_ACTION_TYPE_VECTOR2F_INPUT // TODO: thresholds? + XrAction haptic_output; + xr::hand_tracker * hand = nullptr; }; @@ -153,13 +155,13 @@ private: XrSpace world; size_t focused_controller = (size_t)-1; XrTime last_display_time = 0; + bool controllers_enabled = true; bool button_pressed = false; bool fingertip_touching = false; - ImFontGlyphRangesBuilder glyph_range_builder; - ImVector glyph_ranges; - bool glyph_range_dirty = true; + ImGuiID hovered_item = 0; // Hovered item in the current frame, reset at the beginning of the frame + ImGuiID hovered_item_prev = 0; // Hovered item at the previous frame #if WIVRN_SHOW_IMGUI_DEMO_WINDOW bool show_demo_window = true; @@ -192,7 +194,6 @@ public: void new_frame(XrTime display_time); std::vector> end_frame(); - ImFont * large_font; size_t get_focused_controller() const { return focused_controller; @@ -209,6 +210,10 @@ public: void free_texture(ImTextureID); void set_current(); - void add_chars(std::string_view sv); bool is_modal_popup_shown() const; + + void vibrate_on_hover(); + void set_hovered_item(); + void set_controllers_enabled(bool value); + void tooltip(std::string_view text); }; diff --git a/client/render/scene_components.cpp b/client/render/scene_components.cpp new file mode 100644 index 00000000..b1b35dba --- /dev/null +++ b/client/render/scene_components.cpp @@ -0,0 +1,79 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * + * 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 "scene_components.h" +#include +#include + +entt::entity find_node_by_name(entt::registry & scene, std::string_view name) +{ + for (auto && [entity, node]: scene.view().each()) + { + if (node.name == name) + return entity; + } + + // TODO custom exception + throw std::runtime_error("Node \"" + (std::string)name + "\" not found"); +} + +entt::entity find_node_by_name(entt::registry & scene, std::string_view name, entt::entity parent) +{ + for (auto && [entity, node]: scene.view().each()) + { + if (node.name != name) + continue; + + auto current_parent = node.parent; + + do + { + if (current_parent == parent) + return entity; + assert(current_parent != scene.get(current_parent).parent); + current_parent = scene.get(current_parent).parent; + + } while (current_parent != entt::null); + } + + // TODO custom exception + throw std::runtime_error("Node \"" + (std::string)name + "\" not found"); +} + +std::string get_node_name(const entt::registry & scene, entt::entity entity) +{ + auto name_parent = [&](entt::entity entity) -> std::pair { + const auto & node = scene.get(entity); + if (node.name == "") + return {std::to_string((int)entity), node.parent}; + else + return {node.name, node.parent}; + }; + + std::string name; + std::tie(name, entity) = name_parent(entity); + + while (entity != entt::null) + { + std::string tmp; + std::tie(tmp, entity) = name_parent(entity); + name = tmp + "/" + name; + } + + return name; +} diff --git a/client/render/scene_components.h b/client/render/scene_components.h new file mode 100644 index 00000000..9b594947 --- /dev/null +++ b/client/render/scene_components.h @@ -0,0 +1,187 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 Guillaume Meunier + * + * 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 +#include + +#include +#include +#include +#include + +#include "utils/magic_hash.h" +#include "vk/allocation.h" + +namespace renderer +{ +struct sampler_info +{ + vk::Filter mag_filter = vk::Filter::eLinear; + vk::Filter min_filter = vk::Filter::eLinear; + vk::SamplerMipmapMode min_filter_mipmap = vk::SamplerMipmapMode::eLinear; + vk::SamplerAddressMode wrapS = vk::SamplerAddressMode::eRepeat; + vk::SamplerAddressMode wrapT = vk::SamplerAddressMode::eRepeat; + + bool operator==(const sampler_info & other) const noexcept = default; +}; + +struct texture +{ + std::shared_ptr image_view; + sampler_info sampler; +}; + +struct material +{ + struct gpu_data + { + glm::vec4 base_color_factor = glm::vec4(1, 1, 1, 1); + glm::vec4 base_emissive_factor = glm::vec4(0, 0, 0, 0); + float metallic_factor = 1; + float roughness_factor = 1; + float occlusion_strength = 0; + float normal_scale = 0; + + uint32_t base_color_texcoord = 0; + uint32_t metallic_roughness_texcoord = 0; + uint32_t occlusion_texcoord = 0; + uint32_t emissive_texcoord = 0; + uint32_t normal_texcoord = 0; + + // TODO: add fastgltf::TextureTransform? + }; + + std::shared_ptr base_color_texture; + std::shared_ptr metallic_roughness_texture; + std::shared_ptr occlusion_texture; + std::shared_ptr emissive_texture; + std::shared_ptr normal_texture; + + // Disable back face culling with this material + bool double_sided = true; + + // TODO transparency + // fastgltf::AlphaMode alphaMode; + // float alpha_cutoff; + + gpu_data staging; + + // Resources used by this material + std::shared_ptr buffer; + size_t offset; + + // The descriptor set is managed by the scene renderer, it is updated whenever ds_dirty is true + // Bindings 0-4: textures + // Binding 5: uniform buffer + std::shared_ptr ds; + + // Set to true to update the descriptor set at the next frame + bool ds_dirty; + + std::string name; + std::string shader_name = "lit"; + bool blend_enable = true; +}; + +struct primitive +{ + bool indexed; + uint32_t index_count; + uint32_t vertex_count; + vk::IndexType index_type; + vk::DeviceSize index_offset; + vk::DeviceSize vertex_offset; + + // See also material::double_sided + vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone; + vk::FrontFace front_face = vk::FrontFace::eClockwise; + vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList; + + std::shared_ptr material_; +}; + +struct mesh +{ + std::vector primitives; + std::shared_ptr buffer; +}; + +// TODO move vertex class in .cpp, put vertex description in the primitive +struct vertex +{ + glm::vec3 position; + glm::vec3 normal; + glm::vec3 tangent; + std::array texcoord; + glm::vec4 color; + std::array joints; + std::array weights; + + struct description + { + vk::VertexInputBindingDescription binding; + std::vector attributes; + std::vector attribute_names; + + vk::PipelineVertexInputStateCreateFlags flags{}; + }; + + static description describe(); +}; +} // namespace renderer + +namespace std +{ +template <> +struct hash : utils::magic_hash +{}; +} // namespace std + +namespace components +{ +struct node +{ + entt::entity parent = entt::null; + std::string name; + std::shared_ptr mesh; + + glm::vec3 position = {0, 0, 0}; + glm::quat orientation = {1, 0, 0, 0}; + glm::vec3 scale = {1, 1, 1}; + bool visible = true; + uint32_t layer_mask = -1; + + std::array clipping_planes; + + // TODO: separate component? + std::vector> joints; // Node index, inverse bind matrix of each joint + + // For internal use by the renderer + glm::mat4 transform_to_root; + bool global_visible; + bool reverse_side; + uint32_t global_layer_mask; +}; +} // namespace components + +entt::entity find_node_by_name(entt::registry & scene, std::string_view name); +entt::entity find_node_by_name(entt::registry & scene, std::string_view name, entt::entity parent); +std::string get_node_name(const entt::registry & scene, entt::entity entity); diff --git a/client/render/scene_data.cpp b/client/render/scene_data.cpp index 03fe7212..e69de29b 100644 --- a/client/render/scene_data.cpp +++ b/client/render/scene_data.cpp @@ -1,992 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * 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/scene_data.h" - -#include "image_loader.h" -#include "render/gpu_buffer.h" -#include "utils/fmt_glm.h" -#include "utils/ranges.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "asset.h" - -template -constexpr vk::Format vk_attribute_format = vk::Format::eUndefined; -template <> -constexpr vk::Format vk_attribute_format = vk::Format::eR32Sfloat; -template <> -constexpr vk::Format vk_attribute_format = vk::Format::eR32G32Sfloat; -template <> -constexpr vk::Format vk_attribute_format = vk::Format::eR32G32B32Sfloat; -template <> -constexpr vk::Format vk_attribute_format = vk::Format::eR32G32B32A32Sfloat; -template -constexpr vk::Format vk_attribute_format> = vk_attribute_format; - -template -constexpr size_t nb_attributes = 1; -template -constexpr size_t nb_attributes> = N; - -template -struct remove_array -{ - using type = T; -}; -template -struct remove_array> -{ - using type = T; -}; -template -using remove_array_t = remove_array::type; - -template -struct is_array : std::false_type -{ -}; - -template -struct is_array> : std::true_type -{ -}; - -template -constexpr bool is_array_v = is_array::value; - -scene_data::vertex::description scene_data::vertex::describe() -{ - scene_data::vertex::description desc; - - desc.binding = vk::VertexInputBindingDescription{ - .binding = 0, - .stride = sizeof(vertex), - .inputRate = vk::VertexInputRate::eVertex, - }; - - vk::VertexInputAttributeDescription attribute{ - .location = 0, - .binding = 0, - }; - -#define VERTEX_ATTR(member) \ - attribute.format = vk_attribute_format; \ - for (size_t i = 0; i < nb_attributes; i++) \ - { \ - attribute.offset = offsetof(vertex, member) + i * sizeof(remove_array_t); \ - desc.attributes.push_back(attribute); \ - attribute.location++; \ - if (is_array_v) \ - { \ - desc.attribute_names.push_back(#member "_" + std::to_string(i)); \ - } \ - else \ - { \ - desc.attribute_names.push_back(#member); \ - } \ - } - - VERTEX_ATTR(position); - VERTEX_ATTR(normal); - VERTEX_ATTR(tangent); - VERTEX_ATTR(texcoord); - VERTEX_ATTR(color); - VERTEX_ATTR(joints); - VERTEX_ATTR(weights); - - static_assert(vertex{}.joints.size() == vertex{}.weights.size()); - - return desc; -} - -// Conversion functions gltf -> vulkan -namespace -{ -fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory) -{ - fastgltf::Parser parser(fastgltf::Extensions::KHR_texture_basisu); - - auto gltf_options = - fastgltf::Options::DontRequireValidAssetMember | - fastgltf::Options::AllowDouble | - fastgltf::Options::LoadGLBBuffers | - fastgltf::Options::DecomposeNodeMatrices; - - auto expected_asset = parser.loadGltf(&buffer, directory, gltf_options); - - if (auto error = expected_asset.error(); error != fastgltf::Error::None) - throw std::runtime_error(std::string(fastgltf::getErrorMessage(error))); - - return std::move(expected_asset.get()); -} - -std::pair convert(fastgltf::Filter filter) -{ - switch (filter) - { - case fastgltf::Filter::Nearest: - case fastgltf::Filter::NearestMipMapNearest: - return {vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest}; - - case fastgltf::Filter::Linear: - case fastgltf::Filter::LinearMipMapNearest: - return {vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest}; - - case fastgltf::Filter::NearestMipMapLinear: - return {vk::Filter::eNearest, vk::SamplerMipmapMode::eLinear}; - - case fastgltf::Filter::LinearMipMapLinear: - return {vk::Filter::eLinear, vk::SamplerMipmapMode::eLinear}; - } - - throw std::invalid_argument("filter"); -} - -vk::SamplerAddressMode convert(fastgltf::Wrap wrap) -{ - switch (wrap) - { - case fastgltf::Wrap::ClampToEdge: - return vk::SamplerAddressMode::eClampToEdge; - - case fastgltf::Wrap::MirroredRepeat: - return vk::SamplerAddressMode::eMirroredRepeat; - - case fastgltf::Wrap::Repeat: - return vk::SamplerAddressMode::eRepeat; - } - - throw std::invalid_argument("wrap"); -} - -sampler_info convert(fastgltf::Sampler & sampler) -{ - sampler_info info; - - info.mag_filter = convert(sampler.magFilter.value_or(fastgltf::Filter::Linear)).first; - - std::tie(info.min_filter, info.min_filter_mipmap) = convert(sampler.minFilter.value_or(fastgltf::Filter::LinearMipMapLinear)); - - info.wrapS = convert(sampler.wrapS); - info.wrapT = convert(sampler.wrapT); - - return info; -} - -vk::PrimitiveTopology convert(fastgltf::PrimitiveType type) -{ - switch (type) - { - case fastgltf::PrimitiveType::Points: - return vk::PrimitiveTopology::ePointList; - - case fastgltf::PrimitiveType::Lines: - return vk::PrimitiveTopology::eLineList; - - case fastgltf::PrimitiveType::LineLoop: - throw std::runtime_error("Unimplemented"); - - case fastgltf::PrimitiveType::LineStrip: - return vk::PrimitiveTopology::eLineStrip; - - case fastgltf::PrimitiveType::Triangles: - return vk::PrimitiveTopology::eTriangleList; - - case fastgltf::PrimitiveType::TriangleStrip: - return vk::PrimitiveTopology::eTriangleStrip; - - case fastgltf::PrimitiveType::TriangleFan: - return vk::PrimitiveTopology::eTriangleFan; - } - - throw std::invalid_argument("type"); -} - -glm::vec4 convert(const std::array & v) -{ - return {v[0], v[1], v[2], v[3]}; -} - -glm::vec3 convert(const std::array & v) -{ - return {v[0], v[1], v[2]}; -} -} // namespace - -template - requires is_array_v -void copy_vertex_attributes( - const fastgltf::Asset & asset, - const fastgltf::Primitive & primitive, - std::string attribute_name, - std::vector & vertices, - T scene_data::vertex::*attribute) -{ - using U = T::value_type; - constexpr size_t N = std::tuple_size_v; - - for (size_t i = 0; i < N; i++) - { - auto it = primitive.findAttribute(attribute_name + std::to_string(i)); - - if (it == primitive.attributes.end()) - continue; - - const fastgltf::Accessor & accessor = asset.accessors.at(it->second); - - if (vertices.size() < accessor.count) - vertices.resize(accessor.count, {}); - - fastgltf::iterateAccessorWithIndex(asset, accessor, [&](U value, std::size_t idx) { - (vertices[idx].*attribute)[i] = value; - }); - } -} - -template - requires(!is_array_v) -void copy_vertex_attributes( - const fastgltf::Asset & asset, - const fastgltf::Primitive & primitive, - std::string attribute_name, - std::vector & vertices, - T scene_data::vertex::*attribute) -{ - auto it = primitive.findAttribute(attribute_name); - - if (it == primitive.attributes.end()) - return; - - const fastgltf::Accessor & accessor = asset.accessors.at(it->second); - - if (vertices.size() < accessor.count) - vertices.resize(accessor.count, {}); - - fastgltf::iterateAccessorWithIndex(asset, accessor, [&](T value, std::size_t idx) { - vertices[idx].*attribute = value; - }); -} - -namespace -{ -constexpr bool starts_with(std::span data, std::span prefix) -{ - return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size()); -} - -fastgltf::MimeType guess_mime_type(std::span image_data) -{ - const uint8_t jpeg_magic[] = {0xFF, 0xD8, 0xFF}; - const uint8_t png_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; - const uint8_t ktx1_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; - const uint8_t ktx2_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; - - if (starts_with(image_data, png_magic)) - return fastgltf::MimeType::PNG; - else if (starts_with(image_data, jpeg_magic)) - return fastgltf::MimeType::JPEG; - else if (starts_with(image_data, ktx1_magic)) - return fastgltf::MimeType::KTX2; - else if (starts_with(image_data, ktx2_magic)) - return fastgltf::MimeType::KTX2; - else - return fastgltf::MimeType::None; -} - -std::shared_ptr do_load_image( - vk::raii::PhysicalDevice & physical_device, - vk::raii::Device & device, - vk::raii::Queue & queue, - vk::raii::CommandPool & cb_pool, - std::span image_data, - bool srgb) -{ - switch (guess_mime_type(image_data)) - { - case fastgltf::MimeType::JPEG: - case fastgltf::MimeType::PNG: - case fastgltf::MimeType::KTX2: { - try - { - image_loader loader(physical_device, device, queue, cb_pool); - loader.load(image_data, srgb); - - spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps); - return loader.image_view; - } - catch (std::exception & e) - { - spdlog::info("Cannot load image: {}", e.what()); - return {}; - } - } - - default: - spdlog::error("Unsupported image MIME type"); - return {}; - } -} - -class loader_context -{ - std::filesystem::path base_directory; - fastgltf::Asset & gltf; - vk::raii::PhysicalDevice physical_device; - vk::raii::Device & device; - vk::raii::Queue & queue; - vk::raii::CommandPool & cb_pool; - - std::vector loaded_assets; - asset & load_from_asset(const std::filesystem::path & path) - { - return loaded_assets.emplace_back(path); - } - -public: - loader_context(std::filesystem::path base_directory, - fastgltf::Asset & gltf, - vk::raii::PhysicalDevice physical_device, - vk::raii::Device & device, - vk::raii::Queue & queue, - vk::raii::CommandPool & cb_pool) : - base_directory(base_directory), - gltf(gltf), - physical_device(physical_device), - device(device), - queue(queue), - cb_pool(cb_pool) - { - } - - fastgltf::span load(const fastgltf::URI & uri) - { - auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path()); - std::span bytes; - - bytes = load_from_asset(path); - - return fastgltf::span(bytes.data(), bytes.size()); - } - - fastgltf::span load(const fastgltf::sources::URI & uri) - { - return load(uri.uri); - } - - template - fastgltf::span subspan(fastgltf::span span, size_t offset, size_t count = fastgltf::dynamic_extent) - { - assert(offset < span.size()); - assert(count == fastgltf::dynamic_extent || count <= span.size() - offset); - - if (count == fastgltf::dynamic_extent) - count = span.size() - offset; - - return fastgltf::span{span.data() + offset, count}; - } - - fastgltf::sources::ByteView visit_source(fastgltf::DataSource & source) - { - using return_type = fastgltf::sources::ByteView; - - return std::visit(fastgltf::visitor{ - [&](std::monostate) -> return_type { - throw std::runtime_error("Invalid source"); - }, - [&](fastgltf::sources::Fallback) -> return_type { - throw std::runtime_error("Invalid source"); - }, - [&](const fastgltf::sources::BufferView & buffer_view) -> return_type { - fastgltf::BufferView & view = gltf.bufferViews.at(buffer_view.bufferViewIndex); - - fastgltf::Buffer & buffer = gltf.buffers.at(view.bufferIndex); - - auto buffer2 = visit_source(buffer.data); - - return {subspan(buffer2.bytes, view.byteOffset, view.byteLength), buffer_view.mimeType}; - }, - [&](const fastgltf::sources::URI & uri) -> return_type { - if (!uri.uri.isLocalPath()) - throw std::runtime_error("Non local paths are not supported"); // TODO ? - - fastgltf::span data = load(uri); - - // Don't use the MIME type from fastgltf, it's not initialized for URIs - return {subspan(data, uri.fileByteOffset), fastgltf::MimeType::None}; - }, - [&](const fastgltf::sources::Vector & vector) -> return_type { - fastgltf::span data{reinterpret_cast(vector.bytes.data()), vector.bytes.size()}; - return {data, vector.mimeType}; - }, - [&](const fastgltf::sources::Array & array) -> return_type { - fastgltf::span data{reinterpret_cast(array.bytes.data()), array.bytes.size()}; - return {data, array.mimeType}; - }, - [&](const fastgltf::sources::CustomBuffer & custom_buffer) -> return_type { - throw std::runtime_error("Unimplemented source CustomBuffer"); - // TODO ? - }, - [&](fastgltf::sources::ByteView & byte_view) -> return_type { - return {byte_view.bytes, byte_view.mimeType}; - }}, - source); - } - - std::unordered_map> images; - std::shared_ptr load_image(int index, bool srgb) - { - auto it = images.find(index); - if (it != images.end()) - return it->second; - - try - { - auto [image_data, mime_type] = visit_source(gltf.images[index].data); - auto image = do_load_image(physical_device, device, queue, cb_pool, image_data, srgb); - - images.emplace(index, image); - return image; - } - catch (...) - { - return nullptr; - } - } - - std::vector> load_all_textures() - { - // Determine which texture is sRGB - std::vector srgb_array; - srgb_array.resize(gltf.textures.size(), false); - for (const fastgltf::Material & gltf_material: gltf.materials) - { - if (gltf_material.pbrData.baseColorTexture) - srgb_array.at(gltf_material.pbrData.baseColorTexture->textureIndex) = true; - - if (gltf_material.emissiveTexture) - srgb_array.at(gltf_material.emissiveTexture->textureIndex) = true; - } - - std::vector> textures; - textures.reserve(gltf.textures.size()); - for (auto && [srgb, gltf_texture]: std::views::zip(srgb_array, gltf.textures)) - { - auto & texture_ref = *textures.emplace_back(std::make_shared()); - - if (gltf_texture.samplerIndex) - { - fastgltf::Sampler & sampler = gltf.samplers.at(*gltf_texture.samplerIndex); - texture_ref.sampler = convert(sampler); - } - - if (gltf_texture.basisuImageIndex) - { - texture_ref.image_view = load_image(*gltf_texture.basisuImageIndex, srgb); - if (texture_ref.image_view) - continue; - } - - // if (gltf_texture.ddsImageIndex) - // { - // // TODO - // } - - // if (gltf_texture.webpImageIndex) - // { - // // TODO - // } - - if (gltf_texture.imageIndex) - { - texture_ref.image_view = load_image(*gltf_texture.imageIndex, srgb); - if (texture_ref.image_view) - continue; - } - - throw std::runtime_error("Unsupported image type"); - } - - return textures; - } - - void load_all_buffers() - { - for (fastgltf::Buffer & buffer: gltf.buffers) - { - if (std::holds_alternative(buffer.data)) - { - fastgltf::sources::URI uri = std::get(buffer.data); - - // Don't use the MIME type from fastgltf, it's not initialized for URIs - buffer.data = fastgltf::sources::ByteView(load(uri), fastgltf::MimeType::None); - } - } - } - - std::vector> load_all_materials(std::vector> & textures, gpu_buffer & staging_buffer, const scene_data::material & default_material) - { - std::vector> materials; - materials.reserve(gltf.materials.size()); - for (const fastgltf::Material & gltf_material: gltf.materials) - { - // Copy the default material, without references to its buffer or descriptor set - auto & material_ref = *materials.emplace_back(std::make_shared(default_material)); - material_ref.name = gltf_material.name; - spdlog::info("Loading material \"{}\"", material_ref.name); - material_ref.buffer.reset(); - material_ref.ds.reset(); - - material_ref.double_sided = gltf_material.doubleSided; - - scene_data::material::gpu_data & material_data = material_ref.staging; - - material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor); - material_data.base_emissive_factor = glm::vec4(convert(gltf_material.emissiveFactor), 0); - material_data.metallic_factor = gltf_material.pbrData.metallicFactor; - material_data.roughness_factor = gltf_material.pbrData.roughnessFactor; - - if (gltf_material.pbrData.baseColorTexture) - { - material_ref.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex); - material_data.base_color_texcoord = gltf_material.pbrData.baseColorTexture->texCoordIndex; - } - - if (gltf_material.pbrData.metallicRoughnessTexture) - { - material_ref.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex); - material_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex; - } - - if (gltf_material.occlusionTexture) - { - material_ref.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex); - material_data.occlusion_texcoord = gltf_material.occlusionTexture->texCoordIndex; - material_data.occlusion_strength = gltf_material.occlusionTexture->strength; - } - - if (gltf_material.emissiveTexture) - { - material_ref.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex); - material_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex; - } - - if (gltf_material.normalTexture) - { - material_ref.normal_texture = textures.at(gltf_material.normalTexture->textureIndex); - material_data.normal_texcoord = gltf_material.normalTexture->texCoordIndex; - material_data.normal_scale = gltf_material.normalTexture->scale; - } - - material_ref.offset = staging_buffer.add_uniform(material_data); - } - - return materials; - } - - std::vector load_all_meshes(std::vector> & materials, gpu_buffer & staging_buffer) - { - std::vector meshes; - meshes.reserve(gltf.meshes.size()); - for (const fastgltf::Mesh & gltf_mesh: gltf.meshes) - { - auto & mesh_ref = meshes.emplace_back(); - - mesh_ref.primitives.reserve(gltf_mesh.primitives.size()); - - for (const fastgltf::Primitive & gltf_primitive: gltf_mesh.primitives) - { - auto & primitive_ref = mesh_ref.primitives.emplace_back(); - - if (gltf_primitive.indicesAccessor) - { - fastgltf::Accessor & indices_accessor = gltf.accessors.at(*gltf_primitive.indicesAccessor); - - primitive_ref.indexed = true; - primitive_ref.index_offset = staging_buffer.add_indices(indices_accessor); - primitive_ref.index_count = indices_accessor.count; - - switch (indices_accessor.componentType) - { - case fastgltf::ComponentType::Byte: - case fastgltf::ComponentType::UnsignedByte: - primitive_ref.index_type = vk::IndexType::eUint8EXT; - break; - - case fastgltf::ComponentType::Short: - case fastgltf::ComponentType::UnsignedShort: - primitive_ref.index_type = vk::IndexType::eUint16; - break; - - case fastgltf::ComponentType::Int: - case fastgltf::ComponentType::UnsignedInt: - primitive_ref.index_type = vk::IndexType::eUint32; - break; - - default: - throw std::runtime_error("Invalid index type"); - break; - } - } - else - { - primitive_ref.indexed = false; - } - - std::vector vertices; - - copy_vertex_attributes(gltf, gltf_primitive, "POSITION", vertices, &scene_data::vertex::position); - copy_vertex_attributes(gltf, gltf_primitive, "NORMAL", vertices, &scene_data::vertex::normal); - copy_vertex_attributes(gltf, gltf_primitive, "TANGENT", vertices, &scene_data::vertex::tangent); - copy_vertex_attributes(gltf, gltf_primitive, "TEXCOORD_", vertices, &scene_data::vertex::texcoord); - copy_vertex_attributes(gltf, gltf_primitive, "COLOR", vertices, &scene_data::vertex::color); - copy_vertex_attributes(gltf, gltf_primitive, "JOINTS_", vertices, &scene_data::vertex::joints); - copy_vertex_attributes(gltf, gltf_primitive, "WEIGHTS_", vertices, &scene_data::vertex::weights); - - primitive_ref.vertex_offset = staging_buffer.add_vertices(vertices); - primitive_ref.vertex_count = vertices.size(); - - primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC - primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC - primitive_ref.topology = convert(gltf_primitive.type); - - if (gltf_primitive.materialIndex) - primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex); - } - } - - return meshes; - } - - std::vector load_all_nodes() - { - std::vector unsorted_objects; - unsorted_objects.resize(gltf.nodes.size(), {.parent_id = scene_data::node::root_id}); - - for (const auto & [index, gltf_node]: utils::enumerate(gltf.nodes)) - { - if (gltf_node.meshIndex) - unsorted_objects[index].mesh_id = *gltf_node.meshIndex; - - if (gltf_node.skinIndex) - { - auto & skin = gltf.skins.at(*gltf_node.skinIndex); - - unsorted_objects[index].joints.resize(skin.joints.size()); - - for (auto [i, joint_index]: utils::enumerate(skin.joints)) - unsorted_objects[index].joints.at(i).first = joint_index; - - if (skin.inverseBindMatrices) - { - const fastgltf::Accessor & accessor = gltf.accessors.at(*skin.inverseBindMatrices); - - fastgltf::iterateAccessorWithIndex(gltf, accessor, [&](const glm::mat4 & value, std::size_t idx) { - unsorted_objects[index].joints.at(idx).second = value; - }); - } - } - - for (size_t child: gltf_node.children) - { - unsorted_objects[child].parent_id = index; - } - - auto TRS = std::get(gltf_node.transform); - - unsorted_objects[index].position = glm::make_vec3(TRS.translation.data()); - unsorted_objects[index].orientation = glm::make_quat(TRS.rotation.data()); - unsorted_objects[index].scale = glm::make_vec3(TRS.scale.data()); - unsorted_objects[index].visible = true; - unsorted_objects[index].name = gltf_node.name; - std::ranges::fill(unsorted_objects[index].clipping_planes, glm::vec4{0, 0, 0, 1}); - } - - return unsorted_objects; - } - - std::vector topological_sort(const std::vector & unsorted_nodes) - { - std::vector sorted_nodes; - std::vector new_index; - std::vector already_sorted; - - sorted_nodes.reserve(unsorted_nodes.size()); - already_sorted.resize(unsorted_nodes.size(), false); - new_index.resize(unsorted_nodes.size(), scene_data::node::root_id); - - [[maybe_unused]] bool loop_detected = true; - - while (sorted_nodes.size() < unsorted_nodes.size()) - { - for (size_t i = 0; i < unsorted_nodes.size(); i++) - { - if (already_sorted[i]) - continue; - - if (unsorted_nodes[i].parent_id == scene_data::node::root_id) - { - sorted_nodes.push_back(unsorted_nodes[i]); - already_sorted[i] = true; - new_index[i] = sorted_nodes.size() - 1; - loop_detected = false; - } - else if (already_sorted[unsorted_nodes[i].parent_id]) - { - sorted_nodes.emplace_back(unsorted_nodes[i]).parent_id = new_index[unsorted_nodes[i].parent_id]; - already_sorted[i] = true; - new_index[i] = sorted_nodes.size() - 1; - loop_detected = false; - } - } - - assert(!loop_detected); - } - - // renumber joint indices - for (auto & node: sorted_nodes) - { - for (auto & joint: node.joints) - { - joint.first = new_index[joint.first]; - } - } - - assert(sorted_nodes.size() == unsorted_nodes.size()); - for (size_t i = 0; i < sorted_nodes.size(); i++) - { - assert(sorted_nodes[i].parent_id == scene_data::node::root_id || sorted_nodes[i].parent_id < i); - } - - return sorted_nodes; - } -}; - -} // namespace - -scene_data scene_loader::operator()(const std::filesystem::path & gltf_path) -{ - vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties(); - vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{ - .flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer, - .queueFamilyIndex = queue_family_index, - }}; - - scene_data data; - - asset asset_file(gltf_path); - fastgltf::GltfDataBuffer data_buffer; - data_buffer.copyBytes(reinterpret_cast(asset_file.data()), asset_file.size()); - - fastgltf::Asset asset = load_gltf_asset(data_buffer, gltf_path.parent_path()); - loader_context ctx(gltf_path.parent_path(), asset, physical_device, device, queue, cb_pool); - -#ifndef NDEBUG - if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None) - throw std::runtime_error(std::string(fastgltf::getErrorMessage(error))); -#endif - - // Load all buffers from URIs - ctx.load_all_buffers(); - - gpu_buffer staging_buffer(physical_device_properties, asset); - - // Load all textures - auto textures = ctx.load_all_textures(); - - // Load all materials - auto materials = ctx.load_all_materials(textures, staging_buffer, *default_material); - - // Load all meshes - data.meshes = ctx.load_all_meshes(materials, staging_buffer); - - data.scene_nodes = ctx.topological_sort(ctx.load_all_nodes()); - - // Copy the staging buffer to the GPU - spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size()); - auto buffer = std::make_shared(staging_buffer.copy_to_gpu()); - - for (auto & i: materials) - i->buffer = buffer; - - for (auto & i: data.meshes) - i.buffer = buffer; - - return data; -} - -scene_data & scene_data::import(scene_data && other, node_handle parent) -{ - assert(parent.scene == this || parent.id == node::root_id); - - size_t mesh_offset = meshes.size(); - size_t nodes_offset = scene_nodes.size(); - - for (auto & mesh: other.meshes) - meshes.push_back(std::move(mesh)); - - for (auto node: other.scene_nodes) - { - assert(!node.mesh_id || *node.mesh_id < other.meshes.size()); - - if (node.mesh_id) - *node.mesh_id += mesh_offset; - - for (auto & joint: node.joints) - { - joint.first += nodes_offset; - } - - if (node.parent_id == node::root_id) - { - node.parent_id = parent.id; - } - else - { - assert(node.parent_id < other.scene_nodes.size()); - node.parent_id += nodes_offset; - } - - scene_nodes.push_back(node); - } - - other.meshes.clear(); - other.scene_nodes.clear(); - - return *this; -} - -scene_data & scene_data::import(scene_data && other) -{ - return import(std::move(other), {}); -} - -node_handle scene_data::new_node() -{ - size_t id = scene_nodes.size(); - - scene_nodes.push_back(node{ - .parent_id = node::root_id, - .position = {0, 0, 0}, - .orientation = {1, 0, 0, 0}, - .scale = {1, 1, 1}, - .visible = true}); - - return {id, this}; -} - -node_handle scene_data::find_node(std::string_view name) -{ - for (auto && [index, node]: utils::enumerate(scene_nodes)) - { - if (node.name == name) - { - return {index, this}; - } - } - - // TODO custom exception - throw std::runtime_error("Node " + std::string(name) + " not found"); -} - -node_handle scene_data::find_node(node_handle root, std::string_view name) -{ - assert(root.id < scene_nodes.size()); - assert(root.scene == this); - - std::vector flag(scene_nodes.size(), false); - - flag[root.id] = true; - - for (size_t index = root.id; index < scene_nodes.size(); index++) - { - size_t parent = scene_nodes[index].parent_id; - - if (parent == node::root_id) - continue; - - if (!flag[parent]) - continue; - - if (scene_nodes[index].name == name) - return {index, this}; - - flag[index] = true; - } - - // TODO custom exception - throw std::runtime_error("Node " + std::string(name) + " not found"); -} - -std::vector scene_data::find_children(node_handle root) -{ - assert(root.id < scene_nodes.size()); - assert(root.scene == this); - - std::vector flag(scene_nodes.size(), false); - - flag[root.id] = true; - - std::vector nodes; - - for (size_t index = root.id; index < scene_nodes.size(); index++) - { - size_t parent = scene_nodes[index].parent_id; - - if (parent == node::root_id) - continue; - - if (!flag[parent]) - continue; - - nodes.emplace_back(index, this); - - flag[index] = true; - } - - return nodes; -} - -std::shared_ptr scene_data::find_material(std::string_view name) -{ - for (auto & mesh: meshes) - { - for (auto & primitive: mesh.primitives) - { - if (primitive.material_ && primitive.material_->name == name) - return primitive.material_; - } - } - - return {}; -} diff --git a/client/render/scene_data.h b/client/render/scene_data.h index b51671b1..e69de29b 100644 --- a/client/render/scene_data.h +++ b/client/render/scene_data.h @@ -1,295 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2022 Guillaume Meunier - * Copyright (C) 2022 Patrick Nicolas - * - * 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/magic_hash.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct sampler_info -{ - vk::Filter mag_filter = vk::Filter::eLinear; - vk::Filter min_filter = vk::Filter::eLinear; - vk::SamplerMipmapMode min_filter_mipmap = vk::SamplerMipmapMode::eLinear; - vk::SamplerAddressMode wrapS = vk::SamplerAddressMode::eRepeat; - vk::SamplerAddressMode wrapT = vk::SamplerAddressMode::eRepeat; - - bool operator==(const sampler_info & other) const noexcept = default; -}; - -namespace std -{ -template <> -struct hash : utils::magic_hash -{}; -} // namespace std - -class node_handle; - -struct scene_data -{ - struct texture - { - std::shared_ptr image_view; - sampler_info sampler; - }; - - struct material - { - struct gpu_data - { - glm::vec4 base_color_factor = glm::vec4(1, 1, 1, 1); - glm::vec4 base_emissive_factor = glm::vec4(0, 0, 0, 0); - float metallic_factor = 1; - float roughness_factor = 1; - float occlusion_strength = 0; - float normal_scale = 0; - - uint32_t base_color_texcoord = 0; - uint32_t metallic_roughness_texcoord = 0; - uint32_t occlusion_texcoord = 0; - uint32_t emissive_texcoord = 0; - uint32_t normal_texcoord = 0; - - // TODO: add fastgltf::TextureTransform? - }; - - std::shared_ptr base_color_texture; - std::shared_ptr metallic_roughness_texture; - std::shared_ptr occlusion_texture; - std::shared_ptr emissive_texture; - std::shared_ptr normal_texture; - - // Disable back face culling with this material - bool double_sided = true; - - // TODO transparency - // fastgltf::AlphaMode alphaMode; - // float alpha_cutoff; - - gpu_data staging; - - // Resources used by this material - std::shared_ptr buffer; - size_t offset; - - // The descriptor set is managed by the scene renderer, it is updated whenever ds_dirty is true - // Bindings 0-4: textures - // Binding 5: uniform buffer - std::shared_ptr ds; - - // Set to true to update the descriptor set at the next frame - bool ds_dirty; - - std::string name; - std::string shader_name = "lit"; - bool blend_enable = true; - }; - - struct vertex - { - glm::vec3 position; - glm::vec3 normal; - glm::vec3 tangent; - std::array texcoord; - glm::vec4 color; - std::array joints; - std::array weights; - - struct description - { - vk::VertexInputBindingDescription binding; - std::vector attributes; - std::vector attribute_names; - - vk::PipelineVertexInputStateCreateFlags flags{}; - }; - - static description describe(); - }; - - struct primitive - { - bool indexed; - uint32_t index_count; - uint32_t vertex_count; - vk::IndexType index_type; - vk::DeviceSize index_offset; - vk::DeviceSize vertex_offset; - - // See also material::double_sided - vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone; - vk::FrontFace front_face = vk::FrontFace::eClockwise; - vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList; - - std::shared_ptr material_; - }; - - struct mesh - { - std::vector primitives; - std::shared_ptr buffer; - }; - - struct node - { - static constexpr size_t root_id = size_t(-1); - - size_t parent_id; - std::optional mesh_id; - - glm::vec3 position; - glm::quat orientation; - glm::vec3 scale; - - std::string name; - bool visible; - - std::array clipping_planes; - - uint32_t layer_mask = 1; - - std::vector> joints; // Node index, inverse bind matrix of each joint - }; - - // TODO: lights - // TODO: skybox - - std::vector meshes; - std::vector scene_nodes; - - scene_data() = default; - scene_data(const scene_data &) = delete; - scene_data(scene_data &&) = default; - scene_data & operator=(const scene_data &) = delete; - scene_data & operator=(scene_data &&) = default; - - scene_data & import(scene_data && other, node_handle parent); - scene_data & import(scene_data && other); - - node_handle new_node(); - node_handle find_node(std::string_view name); - node_handle find_node(node_handle parent, std::string_view name); - std::vector find_children(node_handle parent); - - std::shared_ptr find_material(std::string_view name); -}; - -class scene_loader -{ - vk::raii::Device & device; - vk::raii::PhysicalDevice physical_device; - vk::raii::Queue & queue; - uint32_t queue_family_index; - std::shared_ptr default_material; - -public: - scene_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, uint32_t queue_family_index, std::shared_ptr default_material) : - device(device), - physical_device(physical_device), - queue(queue), - queue_family_index(queue_family_index), - default_material(default_material) - {} - - scene_data operator()(const std::filesystem::path & gltf_path); -}; - -class node_handle -{ - friend struct scene_data; - size_t id = scene_data::node::root_id; - scene_data * scene = nullptr; - -public: - node_handle() = default; - node_handle(size_t id, scene_data * scene) : - id(id), scene(scene) {} - node_handle(const node_handle &) = default; - node_handle & operator=(const node_handle &) = default; - - scene_data::node & operator*() - { - assert(scene != nullptr); - assert(id < scene->scene_nodes.size()); - return scene->scene_nodes[id]; - } - - const scene_data::node & operator*() const - { - assert(scene != nullptr); - assert(id < scene->scene_nodes.size()); - return scene->scene_nodes[id]; - } - - scene_data::node * operator->() - { - assert(scene != nullptr); - assert(id < scene->scene_nodes.size()); - return &scene->scene_nodes[id]; - } - - const scene_data::node * operator->() const - { - assert(scene != nullptr); - assert(id < scene->scene_nodes.size()); - return &scene->scene_nodes[id]; - } - - node_handle parent() - { - assert(scene != nullptr); - assert(id < scene->scene_nodes.size()); - - return {scene->scene_nodes[id].parent_id, scene}; - } - - const node_handle parent() const - { - assert(scene != nullptr); - assert(id < scene->scene_nodes.size()); - - return {scene->scene_nodes[id].parent_id, scene}; - } - - std::vector children() - { - assert(scene != nullptr); - - return scene->find_children(*this); - } - - operator bool() const - { - return id != scene_data::node::root_id; - } -}; diff --git a/client/render/scene_loader.cpp b/client/render/scene_loader.cpp new file mode 100644 index 00000000..8a00a5c2 --- /dev/null +++ b/client/render/scene_loader.cpp @@ -0,0 +1,840 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 Guillaume Meunier + * + * 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 "scene_loader.h" + +#include "asset.h" +#include "gpu_buffer.h" +#include "image_loader.h" +#include "render/scene_components.h" +#include "utils/ranges.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +// BEGIN Utility functions +template +constexpr vk::Format vk_attribute_format = vk::Format::eUndefined; +template <> +constexpr vk::Format vk_attribute_format = vk::Format::eR32Sfloat; +template <> +constexpr vk::Format vk_attribute_format = vk::Format::eR32G32Sfloat; +template <> +constexpr vk::Format vk_attribute_format = vk::Format::eR32G32B32Sfloat; +template <> +constexpr vk::Format vk_attribute_format = vk::Format::eR32G32B32A32Sfloat; +template +constexpr vk::Format vk_attribute_format> = vk_attribute_format; + +template +constexpr size_t nb_attributes = 1; +template +constexpr size_t nb_attributes> = N; + +template +struct remove_array +{ + using type = T; +}; +template +struct remove_array> +{ + using type = T; +}; +template +using remove_array_t = remove_array::type; + +template +struct is_array : std::false_type +{ +}; + +template +struct is_array> : std::true_type +{ +}; + +template +constexpr bool is_array_v = is_array::value; +// END + +// BEGIN GLTF -> Vulkan conversion functions +std::pair convert(fastgltf::Filter filter) +{ + switch (filter) + { + case fastgltf::Filter::Nearest: + case fastgltf::Filter::NearestMipMapNearest: + return {vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest}; + + case fastgltf::Filter::Linear: + case fastgltf::Filter::LinearMipMapNearest: + return {vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest}; + + case fastgltf::Filter::NearestMipMapLinear: + return {vk::Filter::eNearest, vk::SamplerMipmapMode::eLinear}; + + case fastgltf::Filter::LinearMipMapLinear: + return {vk::Filter::eLinear, vk::SamplerMipmapMode::eLinear}; + } + + throw std::invalid_argument("filter"); +} + +vk::SamplerAddressMode convert(fastgltf::Wrap wrap) +{ + switch (wrap) + { + case fastgltf::Wrap::ClampToEdge: + return vk::SamplerAddressMode::eClampToEdge; + + case fastgltf::Wrap::MirroredRepeat: + return vk::SamplerAddressMode::eMirroredRepeat; + + case fastgltf::Wrap::Repeat: + return vk::SamplerAddressMode::eRepeat; + } + + throw std::invalid_argument("wrap"); +} + +renderer::sampler_info convert(fastgltf::Sampler & sampler) +{ + renderer::sampler_info info; + + info.mag_filter = convert(sampler.magFilter.value_or(fastgltf::Filter::Linear)).first; + + std::tie(info.min_filter, info.min_filter_mipmap) = convert(sampler.minFilter.value_or(fastgltf::Filter::LinearMipMapLinear)); + + info.wrapS = convert(sampler.wrapS); + info.wrapT = convert(sampler.wrapT); + + return info; +} + +vk::PrimitiveTopology convert(fastgltf::PrimitiveType type) +{ + switch (type) + { + case fastgltf::PrimitiveType::Points: + return vk::PrimitiveTopology::ePointList; + + case fastgltf::PrimitiveType::Lines: + return vk::PrimitiveTopology::eLineList; + + case fastgltf::PrimitiveType::LineLoop: + throw std::runtime_error("Unimplemented"); + + case fastgltf::PrimitiveType::LineStrip: + return vk::PrimitiveTopology::eLineStrip; + + case fastgltf::PrimitiveType::Triangles: + return vk::PrimitiveTopology::eTriangleList; + + case fastgltf::PrimitiveType::TriangleStrip: + return vk::PrimitiveTopology::eTriangleStrip; + + case fastgltf::PrimitiveType::TriangleFan: + return vk::PrimitiveTopology::eTriangleFan; + } + + throw std::invalid_argument("type"); +} + +glm::vec4 convert(const std::array & v) +{ + return {v[0], v[1], v[2], v[3]}; +} + +glm::vec3 convert(const std::array & v) +{ + return {v[0], v[1], v[2]}; +} +// END + +// BEGIN Vertex attributes loading +template + requires is_array_v +void copy_vertex_attributes( + const fastgltf::Asset & asset, + const fastgltf::Primitive & primitive, + std::string attribute_name, + std::vector & vertices, + T renderer::vertex::*attribute) +{ + using U = T::value_type; + constexpr size_t N = std::tuple_size_v; + + for (size_t i = 0; i < N; i++) + { + auto it = primitive.findAttribute(attribute_name + std::to_string(i)); + + if (it == primitive.attributes.end()) + continue; + + const fastgltf::Accessor & accessor = asset.accessors.at(it->second); + + if (vertices.size() < accessor.count) + vertices.resize(accessor.count, {}); + + fastgltf::iterateAccessorWithIndex(asset, accessor, [&](U value, std::size_t idx) { + (vertices[idx].*attribute)[i] = value; + }); + } +} + +template + requires(!is_array_v) +void copy_vertex_attributes( + const fastgltf::Asset & asset, + const fastgltf::Primitive & primitive, + std::string attribute_name, + std::vector & vertices, + T renderer::vertex::*attribute) +{ + auto it = primitive.findAttribute(attribute_name); + + if (it == primitive.attributes.end()) + return; + + const fastgltf::Accessor & accessor = asset.accessors.at(it->second); + + if (vertices.size() < accessor.count) + vertices.resize(accessor.count, {}); + + fastgltf::iterateAccessorWithIndex(asset, accessor, [&](T value, std::size_t idx) { + vertices[idx].*attribute = value; + }); +} +// END + +// BEGIN Image loading +constexpr bool starts_with(std::span data, std::span prefix) +{ + return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size()); +} + +fastgltf::MimeType guess_mime_type(std::span image_data) +{ + const uint8_t jpeg_magic[] = {0xFF, 0xD8, 0xFF}; + const uint8_t png_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; + const uint8_t ktx1_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; + const uint8_t ktx2_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; + + if (starts_with(image_data, png_magic)) + return fastgltf::MimeType::PNG; + else if (starts_with(image_data, jpeg_magic)) + return fastgltf::MimeType::JPEG; + else if (starts_with(image_data, ktx1_magic)) + return fastgltf::MimeType::KTX2; + else if (starts_with(image_data, ktx2_magic)) + return fastgltf::MimeType::KTX2; + else + return fastgltf::MimeType::None; +} + +std::shared_ptr do_load_image( + vk::raii::PhysicalDevice & physical_device, + vk::raii::Device & device, + vk::raii::Queue & queue, + vk::raii::CommandPool & cb_pool, + std::span image_data, + bool srgb) +{ + switch (guess_mime_type(image_data)) + { + case fastgltf::MimeType::JPEG: + case fastgltf::MimeType::PNG: + case fastgltf::MimeType::KTX2: { + try + { + image_loader loader(physical_device, device, queue, cb_pool); + loader.load(image_data, srgb); + + spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps); + return loader.image_view; + } + catch (std::exception & e) + { + spdlog::info("Cannot load image: {}", e.what()); + return {}; + } + } + + default: + spdlog::error("Unsupported image MIME type"); + return {}; + } +} +// END + +fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory) +{ + fastgltf::Parser parser(fastgltf::Extensions::KHR_texture_basisu); + + auto gltf_options = + fastgltf::Options::DontRequireValidAssetMember | + fastgltf::Options::AllowDouble | + fastgltf::Options::LoadGLBBuffers | + fastgltf::Options::DecomposeNodeMatrices; + + auto expected_asset = parser.loadGltf(&buffer, directory, gltf_options); + + if (auto error = expected_asset.error(); error != fastgltf::Error::None) + throw std::runtime_error(std::string(fastgltf::getErrorMessage(error))); + + return std::move(expected_asset.get()); +} + +class loader_context +{ + std::filesystem::path base_directory; + fastgltf::Asset & gltf; + vk::raii::PhysicalDevice physical_device; + vk::raii::Device & device; + vk::raii::Queue & queue; + vk::raii::CommandPool & cb_pool; + + std::vector loaded_assets; + asset & load_from_asset(const std::filesystem::path & path) + { + return loaded_assets.emplace_back(path); + } + +public: + loader_context(std::filesystem::path base_directory, + fastgltf::Asset & gltf, + vk::raii::PhysicalDevice physical_device, + vk::raii::Device & device, + vk::raii::Queue & queue, + vk::raii::CommandPool & cb_pool) : + base_directory(base_directory), + gltf(gltf), + physical_device(physical_device), + device(device), + queue(queue), + cb_pool(cb_pool) + { + } + + fastgltf::span load(const fastgltf::URI & uri) + { + auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path()); + std::span bytes; + + bytes = load_from_asset(path); + + return fastgltf::span(bytes.data(), bytes.size()); + } + + fastgltf::span load(const fastgltf::sources::URI & uri) + { + return load(uri.uri); + } + + template + fastgltf::span subspan(fastgltf::span span, size_t offset, size_t count = fastgltf::dynamic_extent) + { + assert(offset < span.size()); + assert(count == fastgltf::dynamic_extent || count <= span.size() - offset); + + if (count == fastgltf::dynamic_extent) + count = span.size() - offset; + + return fastgltf::span{span.data() + offset, count}; + } + + fastgltf::sources::ByteView visit_source(fastgltf::DataSource & source) + { + using return_type = fastgltf::sources::ByteView; + + return std::visit(fastgltf::visitor{ + [&](std::monostate) -> return_type { + throw std::runtime_error("Invalid source"); + }, + [&](fastgltf::sources::Fallback) -> return_type { + throw std::runtime_error("Invalid source"); + }, + [&](const fastgltf::sources::BufferView & buffer_view) -> return_type { + fastgltf::BufferView & view = gltf.bufferViews.at(buffer_view.bufferViewIndex); + + fastgltf::Buffer & buffer = gltf.buffers.at(view.bufferIndex); + + auto buffer2 = visit_source(buffer.data); + + return {subspan(buffer2.bytes, view.byteOffset, view.byteLength), buffer_view.mimeType}; + }, + [&](const fastgltf::sources::URI & uri) -> return_type { + if (!uri.uri.isLocalPath()) + throw std::runtime_error("Non local paths are not supported"); // TODO ? + + fastgltf::span data = load(uri); + + // Don't use the MIME type from fastgltf, it's not initialized for URIs + return {subspan(data, uri.fileByteOffset), fastgltf::MimeType::None}; + }, + [&](const fastgltf::sources::Vector & vector) -> return_type { + fastgltf::span data{reinterpret_cast(vector.bytes.data()), vector.bytes.size()}; + return {data, vector.mimeType}; + }, + [&](const fastgltf::sources::Array & array) -> return_type { + fastgltf::span data{reinterpret_cast(array.bytes.data()), array.bytes.size()}; + return {data, array.mimeType}; + }, + [&](const fastgltf::sources::CustomBuffer & custom_buffer) -> return_type { + throw std::runtime_error("Unimplemented source CustomBuffer"); + // TODO ? + }, + [&](fastgltf::sources::ByteView & byte_view) -> return_type { + return {byte_view.bytes, byte_view.mimeType}; + }}, + source); + } + + std::unordered_map> images; + std::shared_ptr load_image(int index, bool srgb) + { + auto it = images.find(index); + if (it != images.end()) + return it->second; + + try + { + auto [image_data, mime_type] = visit_source(gltf.images[index].data); + auto image = do_load_image(physical_device, device, queue, cb_pool, image_data, srgb); + + images.emplace(index, image); + return image; + } + catch (...) + { + return nullptr; + } + } + + std::vector> load_all_textures() + { + // Determine which texture is sRGB + std::vector srgb_array; + srgb_array.resize(gltf.textures.size(), false); + for (const fastgltf::Material & gltf_material: gltf.materials) + { + if (gltf_material.pbrData.baseColorTexture) + srgb_array.at(gltf_material.pbrData.baseColorTexture->textureIndex) = true; + + if (gltf_material.emissiveTexture) + srgb_array.at(gltf_material.emissiveTexture->textureIndex) = true; + } + + std::vector> textures; + textures.reserve(gltf.textures.size()); + for (auto && [srgb, gltf_texture]: std::views::zip(srgb_array, gltf.textures)) + { + auto & texture_ref = *textures.emplace_back(std::make_shared()); + + if (gltf_texture.samplerIndex) + { + fastgltf::Sampler & sampler = gltf.samplers.at(*gltf_texture.samplerIndex); + texture_ref.sampler = convert(sampler); + } + + if (gltf_texture.basisuImageIndex) + { + texture_ref.image_view = load_image(*gltf_texture.basisuImageIndex, srgb); + if (texture_ref.image_view) + continue; + } + + // if (gltf_texture.ddsImageIndex) + // { + // // TODO + // } + + // if (gltf_texture.webpImageIndex) + // { + // // TODO + // } + + if (gltf_texture.imageIndex) + { + texture_ref.image_view = load_image(*gltf_texture.imageIndex, srgb); + if (texture_ref.image_view) + continue; + } + + throw std::runtime_error("Unsupported image type"); + } + + return textures; + } + + void load_all_buffers() + { + for (fastgltf::Buffer & buffer: gltf.buffers) + { + if (std::holds_alternative(buffer.data)) + { + fastgltf::sources::URI uri = std::get(buffer.data); + + // Don't use the MIME type from fastgltf, it's not initialized for URIs + buffer.data = fastgltf::sources::ByteView(load(uri), fastgltf::MimeType::None); + } + } + } + + std::vector> load_all_materials(std::vector> & textures, gpu_buffer & staging_buffer, const renderer::material & default_material) + { + std::vector> materials; + materials.reserve(gltf.materials.size()); + for (const fastgltf::Material & gltf_material: gltf.materials) + { + // Copy the default material, without references to its buffer or descriptor set + auto & material_ref = *materials.emplace_back(std::make_shared(default_material)); + material_ref.name = gltf_material.name; + spdlog::info("Loading material \"{}\"", material_ref.name); + material_ref.buffer.reset(); + material_ref.ds.reset(); + + material_ref.double_sided = gltf_material.doubleSided; + material_ref.blend_enable = gltf_material.alphaMode == fastgltf::AlphaMode::Blend; // TODO handle alpha cut off mode + + renderer::material::gpu_data & material_data = material_ref.staging; + + material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor); + material_data.base_emissive_factor = glm::vec4(convert(gltf_material.emissiveFactor), 0); + material_data.metallic_factor = gltf_material.pbrData.metallicFactor; + material_data.roughness_factor = gltf_material.pbrData.roughnessFactor; + + if (gltf_material.pbrData.baseColorTexture) + { + material_ref.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex); + material_data.base_color_texcoord = gltf_material.pbrData.baseColorTexture->texCoordIndex; + } + + if (gltf_material.pbrData.metallicRoughnessTexture) + { + material_ref.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex); + material_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex; + } + + if (gltf_material.occlusionTexture) + { + material_ref.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex); + material_data.occlusion_texcoord = gltf_material.occlusionTexture->texCoordIndex; + material_data.occlusion_strength = gltf_material.occlusionTexture->strength; + } + + if (gltf_material.emissiveTexture) + { + material_ref.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex); + material_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex; + } + + if (gltf_material.normalTexture) + { + material_ref.normal_texture = textures.at(gltf_material.normalTexture->textureIndex); + material_data.normal_texcoord = gltf_material.normalTexture->texCoordIndex; + material_data.normal_scale = gltf_material.normalTexture->scale; + } + + material_ref.offset = staging_buffer.add_uniform(material_data); + } + + return materials; + } + + std::vector> load_all_meshes(std::vector> & materials, gpu_buffer & staging_buffer) + { + std::vector> meshes; + meshes.reserve(gltf.meshes.size()); + for (const fastgltf::Mesh & gltf_mesh: gltf.meshes) + { + std::shared_ptr & mesh_ref = meshes.emplace_back(); + mesh_ref = std::make_shared(); + + mesh_ref->primitives.reserve(gltf_mesh.primitives.size()); + + for (const fastgltf::Primitive & gltf_primitive: gltf_mesh.primitives) + { + auto & primitive_ref = mesh_ref->primitives.emplace_back(); + + if (gltf_primitive.indicesAccessor) + { + fastgltf::Accessor & indices_accessor = gltf.accessors.at(*gltf_primitive.indicesAccessor); + + primitive_ref.indexed = true; + primitive_ref.index_offset = staging_buffer.add_indices(indices_accessor); + primitive_ref.index_count = indices_accessor.count; + + switch (indices_accessor.componentType) + { + case fastgltf::ComponentType::Byte: + case fastgltf::ComponentType::UnsignedByte: + primitive_ref.index_type = vk::IndexType::eUint8EXT; + break; + + case fastgltf::ComponentType::Short: + case fastgltf::ComponentType::UnsignedShort: + primitive_ref.index_type = vk::IndexType::eUint16; + break; + + case fastgltf::ComponentType::Int: + case fastgltf::ComponentType::UnsignedInt: + primitive_ref.index_type = vk::IndexType::eUint32; + break; + + default: + throw std::runtime_error("Invalid index type"); + break; + } + } + else + { + primitive_ref.indexed = false; + } + + std::vector vertices; + + copy_vertex_attributes(gltf, gltf_primitive, "POSITION", vertices, &renderer::vertex::position); + copy_vertex_attributes(gltf, gltf_primitive, "NORMAL", vertices, &renderer::vertex::normal); + copy_vertex_attributes(gltf, gltf_primitive, "TANGENT", vertices, &renderer::vertex::tangent); + copy_vertex_attributes(gltf, gltf_primitive, "TEXCOORD_", vertices, &renderer::vertex::texcoord); + copy_vertex_attributes(gltf, gltf_primitive, "COLOR", vertices, &renderer::vertex::color); + copy_vertex_attributes(gltf, gltf_primitive, "JOINTS_", vertices, &renderer::vertex::joints); + copy_vertex_attributes(gltf, gltf_primitive, "WEIGHTS_", vertices, &renderer::vertex::weights); + + primitive_ref.vertex_offset = staging_buffer.add_vertices(vertices); + primitive_ref.vertex_count = vertices.size(); + + primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC + primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC + primitive_ref.topology = convert(gltf_primitive.type); + + if (gltf_primitive.materialIndex) + primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex); + } + } + + return meshes; + } + + entt::registry load_all_nodes(const std::vector> & meshes) + { + entt::registry registry; + + std::vector entities{gltf.nodes.size()}; + registry.create(entities.begin(), entities.end()); + + // Create all node components first + registry.insert(entities.begin(), entities.end()); + + for (const auto & [entity, gltf_node]: std::ranges::zip_view(entities, gltf.nodes)) + { + components::node & node = registry.get(entity); + node.name = gltf_node.name; + + if (gltf_node.meshIndex) + node.mesh = meshes[*gltf_node.meshIndex]; + + if (gltf_node.skinIndex) + { + auto & skin = gltf.skins.at(*gltf_node.skinIndex); + + node.joints.resize(skin.joints.size()); + + for (auto [i, joint_index]: utils::enumerate(skin.joints)) + node.joints.at(i).first = entities[joint_index]; + + if (skin.inverseBindMatrices) + { + const fastgltf::Accessor & accessor = gltf.accessors.at(*skin.inverseBindMatrices); + + fastgltf::iterateAccessorWithIndex(gltf, accessor, [&](const glm::mat4 & value, std::size_t idx) { + node.joints.at(idx).second = value; + }); + } + } + + for (size_t child: gltf_node.children) + { + registry.get(entities[child]).parent = entity; + } + + auto TRS = std::get(gltf_node.transform); + + node.position = glm::make_vec3(TRS.translation.data()); + node.orientation = glm::make_quat(TRS.rotation.data()); + node.scale = glm::make_vec3(TRS.scale.data()); + node.visible = true; + std::ranges::fill(node.clipping_planes, glm::vec4{0, 0, 0, 1}); + } + + return registry; + } +}; + +} // namespace + +renderer::vertex::description renderer::vertex::describe() +{ + renderer::vertex::description desc; + + desc.binding = vk::VertexInputBindingDescription{ + .binding = 0, + .stride = sizeof(vertex), + .inputRate = vk::VertexInputRate::eVertex, + }; + + vk::VertexInputAttributeDescription attribute{ + .location = 0, + .binding = 0, + }; + +#define VERTEX_ATTR(member) \ + attribute.format = vk_attribute_format; \ + for (size_t i = 0; i < nb_attributes; i++) \ + { \ + attribute.offset = offsetof(vertex, member) + i * sizeof(remove_array_t); \ + desc.attributes.push_back(attribute); \ + attribute.location++; \ + if (is_array_v) \ + { \ + desc.attribute_names.push_back(#member "_" + std::to_string(i)); \ + } \ + else \ + { \ + desc.attribute_names.push_back(#member); \ + } \ + } + + VERTEX_ATTR(position); + VERTEX_ATTR(normal); + VERTEX_ATTR(tangent); + VERTEX_ATTR(texcoord); + VERTEX_ATTR(color); + VERTEX_ATTR(joints); + VERTEX_ATTR(weights); + + static_assert(vertex{}.joints.size() == vertex{}.weights.size()); + + return desc; +} + +entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path) +{ + vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties(); + vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{ + .flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer, + .queueFamilyIndex = queue_family_index, + }}; + + spdlog::debug("Loading {}", gltf_path.native()); + + asset asset_file(gltf_path); + fastgltf::GltfDataBuffer data_buffer; + data_buffer.copyBytes(reinterpret_cast(asset_file.data()), asset_file.size()); + + fastgltf::Asset asset = load_gltf_asset(data_buffer, gltf_path.parent_path()); + loader_context ctx(gltf_path.parent_path(), asset, physical_device, device, queue, cb_pool); + +#ifndef NDEBUG + if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None) + throw std::runtime_error(std::string(fastgltf::getErrorMessage(error))); +#endif + + // Load all buffers from URIs + ctx.load_all_buffers(); + + gpu_buffer staging_buffer(physical_device_properties, asset); + + // Load all textures + auto textures = ctx.load_all_textures(); + + // Load all materials + auto materials = ctx.load_all_materials(textures, staging_buffer, *default_material); + + // Load all meshes + auto meshes = ctx.load_all_meshes(materials, staging_buffer); + + // Load all nodes + entt::registry loaded_scene = ctx.load_all_nodes(meshes); + + // Copy the staging buffer to the GPU + spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size()); + auto buffer = std::make_shared(staging_buffer.copy_to_gpu()); + + for (auto & i: materials) + i->buffer = buffer; + + for (auto & i: meshes) + i->buffer = buffer; + + return loaded_scene; +} + +template +void copy_components(entt::registry & scene, const entt::registry & prefab, const std::unordered_map & entity_map) +{ + for (const auto & [entity, component]: prefab.view().each()) + { + scene.emplace(entity_map.at(entity), component); + } +} + +void scene_loader::add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root) +{ + assert(scene.valid(root) or root == entt::null); + + auto prefab_entities = prefab.view(); + + std::vector scene_entities{prefab_entities.size()}; + scene.create(scene_entities.begin(), scene_entities.end()); + + std::unordered_map entity_map; // key: prefab entity, value: scene entity + + entity_map.emplace(entt::null, root); + for (auto [prefab_entity, scene_entity]: std::ranges::zip_view(prefab_entities, scene_entities)) + entity_map.emplace(prefab_entity, scene_entity); + + copy_components(scene, prefab, entity_map); + + // update links + for (auto [prefab_entity, scene_entity]: entity_map) + { + if (prefab_entity == entt::null) + continue; + + auto & node = scene.get(scene_entity); + + node.parent = entity_map.at(node.parent); + + for (auto & joint: node.joints) + { + joint.first = entity_map.at(joint.first); + } + } +} diff --git a/client/render/scene_loader.h b/client/render/scene_loader.h new file mode 100644 index 00000000..e1b165a4 --- /dev/null +++ b/client/render/scene_loader.h @@ -0,0 +1,46 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 Guillaume Meunier + * + * 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 + +#include "scene_components.h" + +class scene_loader +{ + vk::raii::Device & device; + vk::raii::PhysicalDevice physical_device; + vk::raii::Queue & queue; + uint32_t queue_family_index; + std::shared_ptr default_material; + +public: + scene_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, uint32_t queue_family_index, std::shared_ptr default_material) : + device(device), + physical_device(physical_device), + queue(queue), + queue_family_index(queue_family_index), + default_material(default_material) + {} + + entt::registry operator()(const std::filesystem::path & gltf_path); + + void add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root = entt::null); +}; diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index e2d8dc34..279252e3 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -21,7 +21,7 @@ #include "application.h" #include "render/growable_descriptor_pool.h" #include "render/image_loader.h" -#include "render/scene_data.h" +#include "render/scene_components.h" #include "utils/alignment.h" #include "utils/fmt_glm.h" #include "utils/ranges.h" @@ -29,6 +29,8 @@ #include "vk/pipeline.h" #include "vk/shader.h" #include +#include +#include #include #include #include @@ -37,6 +39,8 @@ #include #include #include +#include +#include extern const std::map> shaders; @@ -74,7 +78,7 @@ vk::Format scene_renderer::find_usable_image_format( return vk::Format::eUndefined; } -std::shared_ptr scene_renderer::create_default_texture(vk::raii::CommandPool & cb_pool, std::vector pixel) +std::shared_ptr scene_renderer::create_default_texture(vk::raii::CommandPool & cb_pool, std::vector pixel) { vk::Format format; @@ -99,12 +103,12 @@ std::shared_ptr scene_renderer::create_default_texture(vk:: std::shared_ptr image_view = loader.image_view; - return std::make_shared(image_view, sampler_info{}); + return std::make_shared(image_view, renderer::sampler_info{}); } -std::shared_ptr scene_renderer::create_default_material(vk::raii::CommandPool & cb_pool) +std::shared_ptr scene_renderer::create_default_material(vk::raii::CommandPool & cb_pool) { - auto default_material = std::make_shared(); + auto default_material = std::make_shared(); default_material->name = "default"; default_material->base_color_texture = create_default_texture(cb_pool, {255, 255, 255, 255}); @@ -200,23 +204,14 @@ scene_renderer::scene_renderer( vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool, - vk::Extent2D output_size, - vk::Format output_format, - // std::span depth_formats, - vk::Format depth_format, - int frames_in_flight, - bool keep_depth_buffer) : + int frames_in_flight) : physical_device(physical_device), device(device), physical_device_properties(physical_device.getProperties()), queue(queue), - output_size(output_size), - output_format(output_format), - depth_format(depth_format), layout_0(create_descriptor_set_layout(layout_bindings_0, vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR)), layout_1(create_descriptor_set_layout(layout_bindings_1)), - ds_pool_material(device, layout_1, layout_bindings_1, 100), // TODO tunable - keep_depth_buffer(keep_depth_buffer) + ds_pool_material(device, layout_1, layout_bindings_1, 100) // TODO tunable { // Create the default material default_material = create_default_material(cb_pool); @@ -243,8 +238,6 @@ scene_renderer::scene_renderer( .queryCount = uint32_t(2 * frames_in_flight), }); - renderpass = create_renderpass(); - std::array layouts{*layout_0, *layout_1}; pipeline_layout = create_pipeline_layout(layouts); } @@ -264,40 +257,40 @@ void scene_renderer::wait_idle() throw std::runtime_error("vkWaitForfences: " + vk::to_string(result)); } -// #define MSAA_4x +vk::raii::RenderPass & scene_renderer::get_renderpass(const renderpass_info & info) +{ + auto it = renderpasses.find(info); + if (it != renderpasses.end()) + return it->second; -#ifdef MSAA_4x -#define MSAA_SAMPLES vk::SampleCountFlagBits::e4 -#else -#define MSAA_SAMPLES vk::SampleCountFlagBits::e1 -#endif + return renderpasses.emplace(info, create_renderpass(info)).first->second; +} -vk::raii::RenderPass scene_renderer::create_renderpass() +vk::raii::RenderPass scene_renderer::create_renderpass(const renderpass_info & info_) { vk::RenderPassCreateInfo info; std::array attachments = { vk::AttachmentDescription{ - .format = output_format, - .samples = MSAA_SAMPLES, + .format = info_.color_format, + .samples = info_.msaa_samples, .loadOp = vk::AttachmentLoadOp::eClear, .storeOp = vk::AttachmentStoreOp::eStore, .initialLayout = vk::ImageLayout::eUndefined, .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, }, vk::AttachmentDescription{ - .format = depth_format, - .samples = MSAA_SAMPLES, + .format = info_.depth_format, + .samples = info_.msaa_samples, .loadOp = vk::AttachmentLoadOp::eClear, - .storeOp = keep_depth_buffer ? vk::AttachmentStoreOp::eStore : vk::AttachmentStoreOp::eDontCare, + .storeOp = info_.keep_depth_buffer ? vk::AttachmentStoreOp::eStore : vk::AttachmentStoreOp::eDontCare, .stencilLoadOp = vk::AttachmentLoadOp::eClear, .stencilStoreOp = vk::AttachmentStoreOp::eDontCare, .initialLayout = vk::ImageLayout::eUndefined, .finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal, }, -#ifdef MSAA_4x vk::AttachmentDescription{ - .format = output_format, + .format = info_.color_format, .samples = vk::SampleCountFlagBits::e1, .loadOp = vk::AttachmentLoadOp::eDontCare, .storeOp = vk::AttachmentStoreOp::eStore, @@ -306,10 +299,17 @@ vk::raii::RenderPass scene_renderer::create_renderpass() .initialLayout = vk::ImageLayout::eUndefined, .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, - } -#endif - }; - info.setAttachments(attachments); + }}; + + if (info_.msaa_samples != vk::SampleCountFlagBits::e1) + { + info.setAttachments(attachments); + } + else + { + info.setPAttachments(attachments.data()); + info.setAttachmentCount(2); + } vk::AttachmentReference color_attachment{ .attachment = 0, @@ -321,22 +321,22 @@ vk::raii::RenderPass scene_renderer::create_renderpass() .layout = vk::ImageLayout::eDepthStencilAttachmentOptimal, }; -#ifdef MSAA_4x + // Only used if MSAA is enabled vk::AttachmentReference resolve_attachment{ .attachment = 2, .layout = vk::ImageLayout::eColorAttachmentOptimal, }; -#endif vk::SubpassDescription subpasses{ .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, .colorAttachmentCount = 1, .pColorAttachments = &color_attachment, -#ifdef MSAA_4x - .pResolveAttachments = &resolve_attachment, -#endif .pDepthStencilAttachment = &depth_attachment, }; + + if (info_.msaa_samples != vk::SampleCountFlagBits::e1) + subpasses.pResolveAttachments = &resolve_attachment; + info.setSubpasses(subpasses); std::array dependencies{ @@ -361,53 +361,53 @@ vk::raii::RenderPass scene_renderer::create_renderpass() return vk::raii::RenderPass(device, info); } -scene_renderer::output_image & scene_renderer::get_output_image_data(vk::Image output_color, vk::Image output_depth) +scene_renderer::output_image & scene_renderer::get_output_image_data(const output_image_info & info) { - std::pair images{output_color, output_depth}; - auto it = output_images.find(images); + auto it = output_images.find(info); if (it != output_images.end()) return it->second; - return output_images.emplace(images, create_output_image_data(output_color, output_depth)).first->second; + return output_images.emplace(info, create_output_image_data(info)).first->second; } -scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image output_color, vk::Image output_depth) +scene_renderer::output_image scene_renderer::create_output_image_data(const output_image_info & info) { output_image out; // TODO: use image view from xr::swapchain out.image_view = vk::raii::ImageView( device, vk::ImageViewCreateInfo{ - .image = output_color, + .image = info.color, .viewType = vk::ImageViewType::e2D, - .format = output_format, + .format = info.renderpass.color_format, .components{}, .subresourceRange = { .aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, - .baseArrayLayer = 0, + .baseArrayLayer = info.base_array_layer, .layerCount = 1, }, }); // TODO: check requiredFlags - if (not output_depth) + if (not info.depth) out.depth_buffer = image_allocation{ device, vk::ImageCreateInfo{ .imageType = vk::ImageType::e2D, - .format = depth_format, + .format = info.renderpass.depth_format, .extent = { - .width = output_size.width, - .height = output_size.height, + .width = info.output_size.width, + .height = info.output_size.height, .depth = 1, }, .mipLevels = 1, .arrayLayers = 1, - .samples = MSAA_SAMPLES, + .samples = info.renderpass.msaa_samples, .tiling = vk::ImageTiling::eOptimal, - .usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment}, + .usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment, + }, VmaAllocationCreateInfo{ .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, .usage = VMA_MEMORY_USAGE_AUTO, @@ -417,77 +417,87 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image out.depth_view = vk::raii::ImageView( device, vk::ImageViewCreateInfo{ - .image = output_depth ? output_depth : out.depth_buffer, + .image = info.depth ? info.depth : out.depth_buffer, .viewType = vk::ImageViewType::e2D, - .format = depth_format, + .format = info.renderpass.depth_format, .components{}, .subresourceRange = { .aspectMask = vk::ImageAspectFlagBits::eDepth, .baseMipLevel = 0, .levelCount = 1, - .baseArrayLayer = 0, + .baseArrayLayer = info.depth ? info.base_array_layer : 0, .layerCount = 1, }, }); -#ifdef MSAA_4x - out.multisample_image = image_allocation{vk::ImageCreateInfo{ - .imageType = vk::ImageType::e2D, - .format = output_format, - .extent = { - .width = output_size.width, - .height = output_size.height, - .depth = 1, - }, - .mipLevels = 1, - .arrayLayers = 1, - .samples = MSAA_SAMPLES, - .tiling = vk::ImageTiling::eOptimal, - .usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment, - }, - VmaAllocationCreateInfo{ - .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check - .preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT, - }}; + if (info.renderpass.msaa_samples != vk::SampleCountFlagBits::e1) + { + out.multisample_image = image_allocation{ + device, + vk::ImageCreateInfo{ + .imageType = vk::ImageType::e2D, + .format = info.renderpass.color_format, + .extent = { + .width = info.output_size.width, + .height = info.output_size.height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .samples = info.renderpass.msaa_samples, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment, + }, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check + .preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT, + }}; - out.multisample_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ - .image = out.multisample_image, - .viewType = vk::ImageViewType::e2D, - .format = output_format, - .components{}, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }); -#endif + out.multisample_view = vk::raii::ImageView( + device, + vk::ImageViewCreateInfo{ + .image = out.multisample_image, + .viewType = vk::ImageViewType::e2D, + .format = info.renderpass.color_format, + .components{}, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); + } vk::FramebufferCreateInfo fb_info{ - .renderPass = *renderpass, - .width = output_size.width, - .height = output_size.height, + .renderPass = *get_renderpass(info.renderpass), + .width = info.output_size.width, + .height = info.output_size.height, .layers = 1, }; -#ifdef MSAA_4x - std::array attachments{ - vk::ImageView{*out.multisample_view}, - vk::ImageView{*out.depth_view}, - vk::ImageView{*out.image_view}, - }; -#else - std::array attachments{ - vk::ImageView{*out.image_view}, - vk::ImageView{*out.depth_view}, - }; -#endif - fb_info.setAttachments(attachments); - out.framebuffer = vk::raii::Framebuffer(device, fb_info); + if (info.renderpass.msaa_samples != vk::SampleCountFlagBits::e1) + { + std::array attachments{ + vk::ImageView{*out.multisample_view}, + vk::ImageView{*out.depth_view}, + vk::ImageView{*out.image_view}, + }; + fb_info.setAttachments(attachments); + out.framebuffer = vk::raii::Framebuffer(device, fb_info); + } + else + { + std::array attachments{ + vk::ImageView{*out.image_view}, + vk::ImageView{*out.depth_view}, + }; + fb_info.setAttachments(attachments); + out.framebuffer = vk::raii::Framebuffer(device, fb_info); + } return out; } @@ -518,7 +528,7 @@ vk::raii::PipelineLayout scene_renderer::create_pipeline_layout(std::span & texture) { + auto f = [&](std::shared_ptr & texture) { return vk::DescriptorImageInfo{ .sampler = get_sampler(texture->sampler), .imageView = **texture->image_view, @@ -741,7 +745,7 @@ void scene_renderer::update_material_descriptor_set(scene_data::material & mater vk::DescriptorBufferInfo write_ds_buffer{ .buffer = *material.buffer, .offset = material.offset, - .range = sizeof(scene_data::material::gpu_data), + .range = sizeof(renderer::material::gpu_data), }; // Write each descriptor separately because the HTC XR Elite needs it for some reason @@ -793,24 +797,74 @@ void scene_renderer::update_material_descriptor_set(scene_data::material & mater device.updateDescriptorSets(write_ds, {}); } -// static void print_scene_hierarchy(const scene_data& scene, std::span model_matrices, size_t root = scene_data::node::root_id, int level = 0) +static void print_scene_hierarchy(const entt::registry & scene, entt::entity root = entt::null, int level = 0) +{ + if (level == 0) + spdlog::info("Node hierarchy:"); + + for (auto && [entity, node]: scene.view().each()) + { + if (node.parent != root) + continue; + + // glm::mat4 M = model_matrices[index]; + // glm::vec4 pos = glm::column(M, 3); + // spdlog::info("{:{}} {} pos={}, rot={}, pos to root={}", "", level * 2, node.name, node.translation, node.rotation, glm::vec3(pos)); + + spdlog::info("{:{}} {} ({}, visible: {}, {})", "", level * 2, node.name, (int)entity, node.visible, node.global_visible); + + print_scene_hierarchy(scene, entity, level + 1); + } + if (level == 0) + spdlog::info("---------------"); +} + +// Topological sort of all nodes +// static std::vector sort_nodes(entt::registry & scene) // { -// for(const auto&& [index, node]: utils::enumerate(scene.scene_nodes)) +// std::vector> unsorted; // first: child, second: parent +// std::unordered_set processed; +// std::vector sorted; +// +// for(auto && [entity, node]: scene.view().each()) // { -// if (node.parent_id != root) -// continue; -// -// // glm::mat4 M = model_matrices[index]; -// // glm::vec4 pos = glm::column(M, 3); -// // spdlog::info("{:{}} {} pos={}, rot={}, pos to root={}", "", level * 2, node.name, node.translation, node.rotation, glm::vec3(pos)); -// -// spdlog::info("{:{}} {}", "", level * 2, node.name); -// -// print_scene_hierarchy(scene, model_matrices, index, level + 1); +// if (scene.valid(node.parent)) +// unsorted.push_back({entity, node.parent}); +// else +// { +// processed.emplace(entity); +// sorted.push_back(entity); +// } // } +// +// while(not unsorted.empty()) +// { +// for(auto it = unsorted.begin(); it != unsorted.end(); ) +// { +// if (processed.contains(it->second)) +// { +// processed.emplace(it->first); +// sorted.push_back(it->first); +// it = unsorted.erase(it); +// } +// else +// ++it; +// } +// } +// +// return sorted; // } -void scene_renderer::render(scene_data & scene, const std::array & clear_color, std::span frames) +void scene_renderer::render( + entt::registry & scene, + const std::array & clear_color, + uint32_t layer_mask, + vk::Extent2D output_size, + vk::Format color_format, + vk::Format depth_format, + vk::Image color_buffer, + vk::Image depth_buffer, + std::span frames) { per_frame_resources & resources = current_frame(); @@ -826,41 +880,48 @@ void scene_renderer::render(scene_data & scene, const std::array & cle vk::ClearDepthStencilValue{0.0, 0}, }; - auto vertex_layout = scene_data::vertex::describe(); - - std::vector transform_to_root(scene.scene_nodes.size()); - std::vector reverse_side(scene.scene_nodes.size()); - std::vector visible(scene.scene_nodes.size()); - - for (const auto & [index, object]: utils::enumerate(scene.scene_nodes)) + // TODO once per frame, even if render is called several times + for (auto && [entity, node]: scene.view().each()) { - glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), object.position) * (glm::mat4)object.orientation * glm::scale(glm::mat4(1), object.scale); - float det = object.scale.x * object.scale.y * object.scale.z; + glm::mat4 transform_to_root{1.0}; // Identity + bool visible = true; + bool reverse_side = false; + uint32_t layers = -1; - if (object.parent_id == scene_data::node::root_id) + for (auto i = &node; i != nullptr and visible; i = scene.try_get(i->parent)) { - transform_to_root[index] = transform_to_parent; - reverse_side[index] = det < 0; - visible[index] = object.visible; + float det = i->scale.x * i->scale.y * i->scale.z; + glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), i->position) * (glm::mat4)i->orientation * glm::scale(glm::mat4(1), i->scale); + + transform_to_root = transform_to_parent * transform_to_root; + reverse_side = reverse_side ^ (det < 0); + visible = visible and i->visible; + layers = layers bitand i->layer_mask; } - else - { - size_t parent = object.parent_id; - assert(parent < index); - transform_to_root[index] = transform_to_root.at(parent) * transform_to_parent; - - reverse_side[index] = reverse_side[parent] ^ (det < 0); - - visible[index] = visible[parent] && object.visible; - } + node.transform_to_root = transform_to_root; + node.global_visible = visible; + node.reverse_side = reverse_side; + node.global_layer_mask = layers; } - // print_scene_hierarchy(scene, transform_to_root); + // print_scene_hierarchy(scene); for (const auto && [frame_index, frame]: utils::enumerate(frames)) { - scene_renderer::output_image & output = get_output_image_data(frame.destination, frame.depth_buffer); + scene_renderer::output_image & output = get_output_image_data(output_image_info{ + .renderpass = { + .color_format = color_format, + .depth_format = depth_format, + .keep_depth_buffer = depth_buffer != vk::Image{}, + .msaa_samples = vk::SampleCountFlagBits::e1, + // .msaa_samples = vk::SampleCountFlagBits::e4, // FIXME: MSAA does not work + }, + .output_size = output_size, + .color = color_buffer, + .depth = depth_buffer, + .base_array_layer = (uint32_t)frame_index, + }); glm::mat4 viewproj = frame.projection * frame.view; vk::DeviceSize frame_ubo_offset = resources.uniform_buffer_offset; @@ -873,13 +934,19 @@ void scene_renderer::render(scene_data & scene, const std::array & cle // frame_ubo.ambient_color = glm::vec4(0.2,0.2,0.2,0); // TODO // frame_ubo.light_color = glm::vec4(0.8,0.8,0.8,0); // TODO - frame_ubo.ambient_color = glm::vec4(0, 0, 0, 0); // TODO - frame_ubo.light_color = glm::vec4(0.8, 0.8, 0.8, 0); // TODO + frame_ubo.ambient_color = glm::vec4(0.1, 0.1, 0.1, 0); // TODO + frame_ubo.light_color = glm::vec4(0.8, 0.8, 0.8, 0); // TODO frame_ubo.light_position = glm::vec4(1, 1, 1, 0); // TODO frame_ubo.proj = frame.projection; frame_ubo.view = frame.view; + vk::raii::RenderPass & renderpass = get_renderpass(renderpass_info{ + .color_format = color_format, + .depth_format = depth_format, + .keep_depth_buffer = depth_buffer != vk::Image{}, + }); + cb.beginRenderPass( vk::RenderPassBeginInfo{ .renderPass = *renderpass, @@ -893,17 +960,46 @@ void scene_renderer::render(scene_data & scene, const std::array & cle }, vk::SubpassContents::eInline); - for (const auto & [index, node]: utils::enumerate(scene.scene_nodes)) + // Accumulate all visible primitives + std::vector> primitives; // TODO keep it between frames + for (auto && [entity, node]: scene.view().each()) { - if (!node.mesh_id) + if (not node.global_visible or not node.mesh or (node.global_layer_mask & layer_mask) == 0) continue; - if (!visible[index]) - continue; + // Position relative to the camera + glm::vec4 position = frame.view * node.transform_to_root * glm::vec4(0, 0, 0, 1); - scene_data::mesh & mesh = scene.meshes.at(*node.mesh_id); - glm::mat4 & transform = transform_to_root[index]; + for (renderer::primitive & primitive: node.mesh->primitives) + { + renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material; + primitives.emplace_back(material.blend_enable, position.z, &node, &primitive); + } + } + // Sort by blending / distance + // TODO add frustum culling + std::ranges::stable_sort(primitives, [](const auto & a, const auto & b) -> bool { + // Put the opaque objects first + if (std::get<0>(a) < std::get<0>(b)) + return true; + if (std::get<0>(a) > std::get<0>(b)) + return false; + + // If blending is disabled (std::get<0> == false), put the closest objects first + // If blending is enabled (std::get<0> == true), put the farthest objeccts first + return std::get<0>(a) ^ (std::get<1>(a) > std::get<1>(b)); + }); + + // TODO try to add a depth pre-pass + for (auto & [blend_enable, distance, node_ptr, primitive_ptr]: primitives) + { + components::node & node = *node_ptr; + renderer::primitive & primitive = *primitive_ptr; + + glm::mat4 & transform = node.transform_to_root; + + // TODO: reuse the UBO if another primitive of the same mesh has already been drawn vk::DeviceSize instance_ubo_offset = resources.uniform_buffer_offset; instance_gpu_data & object_ubo = *reinterpret_cast(ubo + resources.uniform_buffer_offset); resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(instance_gpu_data)); @@ -918,7 +1014,8 @@ void scene_renderer::render(scene_data & scene, const std::array & cle for (auto && [idx, joint]: utils::enumerate(node.joints)) { - joint_matrices[idx] = glm::inverse(transform) * transform_to_root[joint.first] * joint.second; + glm::mat4 & joint_transform = scene.get(joint.first).transform_to_root; + joint_matrices[idx] = glm::inverse(transform) * joint_transform * joint.second; } } @@ -927,87 +1024,102 @@ void scene_renderer::render(scene_data & scene, const std::array & cle object_ubo.modelviewproj = viewproj * transform; object_ubo.clipping_planes = node.clipping_planes; - for (scene_data::primitive & primitive: mesh.primitives) - { - // Get the material - std::shared_ptr material = primitive.material_ ? primitive.material_ : default_material; + // Get the material + std::shared_ptr material = primitive.material_ ? primitive.material_ : default_material; - if (material->ds_dirty || !material->ds) - update_material_descriptor_set(*material); + if (material->ds_dirty || !material->ds) + update_material_descriptor_set(*material); - // Get the pipeline - pipeline_info info{ - .shader_name = material->shader_name, - .cull_mode = primitive.cull_mode, - .front_face = primitive.front_face, - .topology = primitive.topology, - .blend_enable = material->blend_enable, + // Get the pipeline + pipeline_info info{ + .renderpass = { + .color_format = color_format, + .depth_format = depth_format, + .keep_depth_buffer = depth_buffer != vk::Image{}}, + .shader_name = material->shader_name, + .cull_mode = primitive.cull_mode, + .front_face = primitive.front_face, + .topology = primitive.topology, + .blend_enable = material->blend_enable, - .nb_texcoords = 2, // TODO - .skinning = !node.joints.empty(), - }; + .nb_texcoords = 2, // TODO + .skinning = !node.joints.empty(), + }; - if (material->double_sided) - info.cull_mode = vk::CullModeFlagBits::eNone; + if (material->double_sided) + info.cull_mode = vk::CullModeFlagBits::eNone; - if (reverse_side[index]) - info.front_face = reverse(info.front_face); + if (node.reverse_side) + info.front_face = reverse(info.front_face); - cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info)); + cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info)); - if (primitive.indexed) - cb.bindIndexBuffer(*mesh.buffer, primitive.index_offset, primitive.index_type); + cb.setViewport(0, vk::Viewport{ + .x = 0, + .y = 0, + .width = (float)output_size.width, + .height = (float)output_size.height, + .minDepth = 0, + .maxDepth = 1, + }); - cb.bindVertexBuffers(0, (vk::Buffer)*mesh.buffer, primitive.vertex_offset); + cb.setScissor(0, vk::Rect2D{ + .offset = {0, 0}, + .extent = output_size, + }); - vk::DescriptorBufferInfo buffer_info_1{ - .buffer = resources.uniform_buffer, - .offset = frame_ubo_offset, - .range = sizeof(frame_gpu_data) + if (primitive.indexed) + cb.bindIndexBuffer(*node.mesh->buffer, primitive.index_offset, primitive.index_type); - }; - vk::DescriptorBufferInfo buffer_info_2{ - .buffer = resources.uniform_buffer, - .offset = instance_ubo_offset, - .range = sizeof(instance_gpu_data)}; - vk::DescriptorBufferInfo buffer_info_3{ - .buffer = resources.uniform_buffer, - .offset = joints_ubo_offset, - .range = sizeof(glm::mat4) * 32}; + cb.bindVertexBuffers(0, (vk::Buffer)*node.mesh->buffer, primitive.vertex_offset); - std::array descriptors{ - vk::WriteDescriptorSet{ - .dstBinding = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &buffer_info_1, - }, - vk::WriteDescriptorSet{ - .dstBinding = 1, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &buffer_info_2, - }, - vk::WriteDescriptorSet{ - .dstBinding = 2, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &buffer_info_3, - }, - }; + vk::DescriptorBufferInfo buffer_info_1{ + .buffer = resources.uniform_buffer, + .offset = frame_ubo_offset, + .range = sizeof(frame_gpu_data) - cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors); + }; + vk::DescriptorBufferInfo buffer_info_2{ + .buffer = resources.uniform_buffer, + .offset = instance_ubo_offset, + .range = sizeof(instance_gpu_data)}; + vk::DescriptorBufferInfo buffer_info_3{ + .buffer = resources.uniform_buffer, + .offset = joints_ubo_offset, + .range = sizeof(glm::mat4) * 32}; - // Set 1: material - cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 1, **material->ds, {}); + std::array descriptors{ + vk::WriteDescriptorSet{ + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info_1, + }, + vk::WriteDescriptorSet{ + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info_2, + }, + vk::WriteDescriptorSet{ + .dstBinding = 2, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info_3, + }, + }; - if (primitive.indexed) - cb.drawIndexed(primitive.index_count, 1, 0, 0, 0); - else - cb.draw(primitive.vertex_count, 1, 0, 0); + cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors); - resources.resources.push_back(material->ds); - } + // Set 1: material + cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 1, **material->ds, {}); + + if (primitive.indexed) + cb.drawIndexed(primitive.index_count, 1, 0, 0, 0); + else + cb.draw(primitive.vertex_count, 1, 0, 0); + + resources.resources.push_back(material->ds); } cb.endRenderPass(); } diff --git a/client/render/scene_renderer.h b/client/render/scene_renderer.h index 3a0e3d7e..562bf945 100644 --- a/client/render/scene_renderer.h +++ b/client/render/scene_renderer.h @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -34,10 +33,22 @@ #include "vk/allocation.h" #include "render/growable_descriptor_pool.h" -#include "render/scene_data.h" +#include "render/scene_components.h" + +struct renderpass_info +{ + vk::Format color_format; + vk::Format depth_format; + bool keep_depth_buffer; + vk::SampleCountFlagBits msaa_samples = vk::SampleCountFlagBits::e1; + + bool operator==(const renderpass_info & other) const noexcept = default; +}; struct pipeline_info { + renderpass_info renderpass; + std::string shader_name; vk::CullModeFlags cull_mode = vk::CullModeFlagBits::eNone; @@ -56,11 +67,35 @@ struct pipeline_info bool operator==(const pipeline_info & other) const noexcept = default; }; +struct output_image_info +{ + renderpass_info renderpass; + + vk::Extent2D output_size; + VkImage color; + VkImage depth; + uint32_t base_array_layer; + + bool operator==(const output_image_info & other) const noexcept = default; +}; + namespace std { +template <> +struct hash : utils::magic_hash +{}; + template <> struct hash : utils::magic_hash {}; + +template <> +struct hash : utils::magic_hash +{}; + +template <> +struct hash : utils::magic_hash +{}; } // namespace std class scene_renderer @@ -70,11 +105,6 @@ class scene_renderer vk::PhysicalDeviceProperties physical_device_properties; vk::raii::Queue & queue; - // Scene format - const vk::Extent2D output_size; - const vk::Format output_format; - const vk::Format depth_format; - // Destination images struct output_image { @@ -84,26 +114,28 @@ class scene_renderer image_allocation depth_buffer; vk::raii::ImageView depth_view = nullptr; - // image_allocation multisample_image; - // vk::raii::ImageView multisample_view = nullptr; + image_allocation multisample_image; + vk::raii::ImageView multisample_view = nullptr; }; // Initialization functions - output_image create_output_image_data(vk::Image output_color, vk::Image output_depth); - vk::raii::RenderPass create_renderpass(); + output_image create_output_image_data(const output_image_info & info); + vk::raii::RenderPass create_renderpass(const renderpass_info & info); vk::raii::PipelineLayout create_pipeline_layout(std::span layouts); vk::raii::Pipeline create_pipeline(const pipeline_info & info); - std::shared_ptr create_default_texture(vk::raii::CommandPool & cb_pool, std::vector pixel); - std::shared_ptr create_default_material(vk::raii::CommandPool & cb_pool); + std::shared_ptr create_default_texture(vk::raii::CommandPool & cb_pool, std::vector pixel); + std::shared_ptr create_default_material(vk::raii::CommandPool & cb_pool); vk::raii::DescriptorSetLayout create_descriptor_set_layout(std::span bindings, vk::DescriptorSetLayoutCreateFlags flags = {}); // Caches - std::/*unordered_*/ map, output_image> output_images; // TODO: use an unordered_map, create a hash for std::pair + std::unordered_map renderpasses; + std::unordered_map output_images; std::unordered_map pipelines; - output_image & get_output_image_data(vk::Image output_color, vk::Image output_depth); + output_image & get_output_image_data(const output_image_info & info); vk::raii::Pipeline & get_pipeline(const pipeline_info & info); + vk::raii::RenderPass & get_renderpass(const renderpass_info & info); vk::raii::DescriptorSetLayout layout_0; // Descriptor set 0: per-frame/view data (UBO) and per-instance data (UBO + SSBO) vk::raii::DescriptorSetLayout layout_1; // Descriptor set 1: per-material data (5 combined image samplers and 1 uniform buffer) @@ -114,11 +146,8 @@ class scene_renderer vk::raii::PipelineLayout pipeline_layout = nullptr; // Texture samplers - std::unordered_map> samplers; - vk::Sampler get_sampler(const sampler_info & info); - - // Render pass - vk::raii::RenderPass renderpass = nullptr; + std::unordered_map> samplers; + vk::Sampler get_sampler(const renderer::sampler_info & info); // Default material and textures // This material has 1x1 textures with the following values: @@ -134,7 +163,7 @@ class scene_renderer // roughness_factor 1.0 // occlusion_strength 0.0 // normal_scale 0.0 - std::shared_ptr default_material; + std::shared_ptr default_material; struct frame_gpu_data { @@ -170,11 +199,10 @@ class scene_renderer int current_frame_index; vk::raii::QueryPool query_pool = nullptr; double gpu_time_s = 0; - bool keep_depth_buffer = false; per_frame_resources & current_frame(); - void update_material_descriptor_set(scene_data::material & material); + void update_material_descriptor_set(renderer::material & material); public: static vk::Format find_usable_image_format( @@ -191,24 +219,27 @@ public: vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool, - vk::Extent2D output_size, - vk::Format output_format, - vk::Format depth_format, - int frames_in_flight = 2, - bool keep_depth_buffer = false); + int frames_in_flight = 2); ~scene_renderer(); struct frame_info { - vk::Image destination; - vk::Image depth_buffer; glm::mat4 projection; glm::mat4 view; }; void start_frame(); - void render(scene_data & scene, const std::array & clear_color, std::span info); + void render( + entt::registry & scene, + const std::array & clear_color, + uint32_t layer_mask, + vk::Extent2D output_size, + vk::Format output_format, + vk::Format depth_format, + vk::Image color_buffer, + vk::Image depth_buffer, + std::span info); void end_frame(); double get_gpu_time() const @@ -216,7 +247,7 @@ public: return gpu_time_s; } - std::shared_ptr get_default_material() + std::shared_ptr get_default_material() { return default_material; } diff --git a/client/scene.cpp b/client/scene.cpp index 3f2e126e..feeb29fe 100644 --- a/client/scene.cpp +++ b/client/scene.cpp @@ -19,14 +19,25 @@ #include "scene.h" #include "application.h" +#include "render/scene_loader.h" +#include "utils/contains.h" +#include "utils/i18n.h" +#include "utils/overloaded.h" +#include "utils/ranges.h" +#include #include #include +#include +#include + +// TODO remove constants +#include "constants.h" std::vector scene::scene_registry; scene::~scene() {} -scene::scene(key, const meta & current_meta) : +scene::scene(key, const meta & current_meta, std::span supported_color_formats, std::span supported_depth_formats) : instance(application::instance().xr_instance), system(application::instance().xr_system_id), session(application::instance().xr_session), @@ -40,7 +51,46 @@ scene::scene(key, const meta & current_meta) : queue_family_index(application::instance().vk_queue_family_index), current_meta(current_meta) { + passthrough_supported = system.passthrough_supported(); + + swapchain_format = vk::Format::eUndefined; + spdlog::info("Supported swapchain formats:"); + + for (auto format: session.get_swapchain_formats()) + { + spdlog::info(" {}", vk::to_string(format)); + } + + for (auto format: session.get_swapchain_formats()) + { + if (utils::contains(supported_color_formats, format)) + { + swapchain_format = format; + break; + } + } + + if (swapchain_format == vk::Format::eUndefined) + throw std::runtime_error(_("No supported swapchain format")); + + auto views = system.view_configuration_views(viewconfig); + depth_format = scene_renderer::find_usable_image_format( + physical_device, + supported_depth_formats, + { + views[0].recommendedImageRectWidth, + views[0].recommendedImageRectHeight, + 1, + }, + vk::ImageUsageFlagBits::eDepthStencilAttachment); + + composition_layer_depth_test_supported = + instance.has_extension(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME) and + instance.has_extension(XR_FB_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME); + + composition_layer_color_scale_bias_supported = instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME); } + void scene::set_focused(bool status) { if (status != focused) @@ -53,6 +103,353 @@ void scene::set_focused(bool status) } } +glm::mat4 scene::projection_matrix(XrFovf fov, float zn) +{ + float r = tan(fov.angleRight); + float l = tan(fov.angleLeft); + float t = tan(fov.angleUp); + float b = tan(fov.angleDown); + + // reversed Z projection, infinite far plane + + // clang-format off + return glm::mat4{ + { 2/(r-l), 0, 0, 0 }, + { 0, 2/(b-t), 0, 0 }, + { (l+r)/(r-l), (t+b)/(b-t), 0, -1 }, + { 0, 0, zn, 0 } + }; + // clang-format on +} + +glm::mat4 scene::view_matrix(XrPosef pose) +{ + XrQuaternionf q = pose.orientation; + XrVector3f pos = pose.position; + + glm::mat4 inv_view_matrix = glm::mat4_cast(glm::quat(q.w, q.x, q.y, q.z)); + + inv_view_matrix = glm::translate(glm::mat4(1), glm::vec3(pos.x, pos.y, pos.z)) * inv_view_matrix; + + return glm::inverse(inv_view_matrix); +} + +void scene::render_world( + XrCompositionLayerFlags flags, + XrSpace space, + std::span views, + uint32_t width, + uint32_t height, + bool keep_depth_buffer, + uint32_t layer_mask, + XrColor4f clear_color) +{ + std::vector frames; + frames.reserve(views.size()); + + // TODO inplace vector + std::vector composition_layer_color; + std::vector composition_layer_depth; + + composition_layer_color.reserve(views.size()); + if (keep_depth_buffer) + composition_layer_depth.reserve(views.size()); + + auto [color_swapchain, color_image] = [&]() -> std::pair { + xr::swapchain & color_swapchain = get_swapchain(swapchain_format, width, height, 1, views.size()); + + int color_image_index = color_swapchain.acquire(); + vk::Image color_image = color_swapchain.images()[color_image_index].image; + color_swapchain.wait(); + return {color_swapchain, color_image}; + }(); + + auto [depth_swapchain, depth_image] = [&]() -> std::pair { + if (keep_depth_buffer) + { + xr::swapchain & depth_swapchain = get_swapchain(depth_format, width, height, 1, views.size()); + + int depth_image_index = depth_swapchain.acquire(); + vk::Image depth_image = depth_swapchain.images()[depth_image_index].image; + depth_swapchain.wait(); + return {depth_swapchain, depth_image}; + } + else + return {}; + }(); + + for (auto && [index, view]: utils::enumerate(views)) + { + frames.push_back({ + .projection = projection_matrix(view.fov, constants::lobby::near_plane), + .view = view_matrix(view.pose), + }); + + composition_layer_color.push_back({ + .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, + .pose = view.pose, + .fov = view.fov, + .subImage = { + .swapchain = color_swapchain, + .imageRect = { + .offset = {0, 0}, + .extent = {(int)width, (int)height}, + }, + .imageArrayIndex = (uint32_t)index, + }, + }); + + if (keep_depth_buffer) + { + composition_layer_depth.push_back({ + .type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, + .subImage = { + .swapchain = depth_swapchain, + .imageRect = { + .offset = {0, 0}, + .extent = {(int)width, (int)height}, + }, + .imageArrayIndex = (uint32_t)index, + }, + .minDepth = 0, + .maxDepth = 1, + .nearZ = std::numeric_limits::infinity(), + .farZ = constants::lobby::near_plane, + }); + } + } + + // TODO: compute transforms only once + + renderer->render( + world, + {clear_color.r, clear_color.g, clear_color.b, clear_color.a}, + layer_mask, + vk::Extent2D{width, height}, + swapchain_format, + depth_format, + color_image, + depth_image, + frames); + + add_projection_layer( + XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + space, + std::move(composition_layer_color), + std::move(composition_layer_depth)); +} + +xr::swapchain & scene::get_swapchain(vk::Format format, int32_t width, int32_t height, int sample_count, uint32_t array_size) +{ + for (swapchain_entry & entry: swapchains) + { + if (not entry.used and + entry.format == format and + entry.width == width and + entry.height == height and + entry.sample_count == sample_count and + entry.array_size == array_size) + { + entry.used = true; + return entry.swapchain; + } + } + + spdlog::info("Creating new swapchain: {}, {}x{}, {} sample(s), {} level(s)", magic_enum::enum_name(format), width, height, sample_count, array_size); + + return swapchains.emplace_back(swapchain_entry{ + .format = format, + .width = width, + .height = height, + .sample_count = sample_count, + .array_size = array_size, + .used = true, + .swapchain = xr::swapchain(session, device, format, width, height, sample_count, array_size), + }) + .swapchain; +} + +void scene::clear_swapchains() +{ + swapchains.clear(); +} + +void scene::render_start(bool passthrough, XrTime predicted_display_time_) +{ + blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; + predicted_display_time = predicted_display_time_; + layers.clear(); + openxr_layers.clear(); + + for (swapchain_entry & swapchain: swapchains) + swapchain.used = false; + + if (renderer) + renderer->start_frame(); + + if (passthrough) + { + std::visit( + utils::overloaded{ + [&](std::monostate &) { + assert(false); + }, + [&](xr::passthrough_alpha_blend & p) { + blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND; + }, + [&](auto & p) { + layers.push_back(layer{ + .composition_layer = p.layer(), + }); + }}, + session.get_passthrough()); + } +} + +void scene::add_projection_layer( + XrCompositionLayerFlags flags, + XrSpace space, + std::vector && color_views, + std::vector && depth_views) +{ + layers.push_back(layer{ + .composition_layer = XrCompositionLayerProjection{ + .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION, + .next = nullptr, + .layerFlags = flags, + .space = space, + .viewCount = (uint32_t)color_views.size(), + .views = nullptr, + }, + .color_views = std::move(color_views), + .depth_views = std::move(depth_views), + }); +} + +void scene::add_quad_layer( + XrCompositionLayerFlags flags, + XrSpace space, + XrEyeVisibility eyeVisibility, + XrSwapchainSubImage subImage, + XrPosef pose, + XrExtent2Df size) +{ + layers.push_back(layer{ + .composition_layer = XrCompositionLayerQuad{ + .type = XR_TYPE_COMPOSITION_LAYER_QUAD, + .next = nullptr, + .layerFlags = flags, + .space = space, + .eyeVisibility = eyeVisibility, + .subImage = subImage, + .pose = pose, + .size = size, + }, + }); +} + +void scene::set_color_scale_bias(XrColor4f scale, XrColor4f bias) +{ + assert(not layers.empty()); + layers.back().color_scale_bias = XrCompositionLayerColorScaleBiasKHR{ + .type = XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR, + .colorScale = scale, + .colorBias = bias, + }; +} + +void scene::set_depth_test(bool write, XrCompareOpFB op) +{ + assert(not layers.empty()); + layers.back().depth_test = XrCompositionLayerDepthTestFB{ + .type = XR_TYPE_COMPOSITION_LAYER_DEPTH_TEST_FB, + .depthMask = write, + .compareOp = op, + }; +} + +void scene::set_layer_settings(XrCompositionLayerSettingsFlagsFB flags) +{ + assert(not layers.empty()); + layers.back().settings = XrCompositionLayerSettingsFB{ + .type = XR_TYPE_COMPOSITION_LAYER_SETTINGS_FB, + .layerFlags = flags, + }; +} + +void scene::render_end() +{ + // Fixup all pointers + for (auto & i: layers) + { + XrCompositionLayerBaseHeader * base = std::visit( + utils::overloaded{ + [&](XrCompositionLayerProjection & layer) { + layer.views = i.color_views.data(); + + for (auto [color, depth]: std::views::zip(i.color_views, i.depth_views)) + color.next = &depth; + + return reinterpret_cast(&layer); + }, + [&](XrCompositionLayerQuad & layer) { + return reinterpret_cast(&layer); + }, + [&](XrCompositionLayerBaseHeader * layer) { + return layer; + }, + }, + i.composition_layer); + + if (i.color_scale_bias) + { + i.color_scale_bias->next = base->next; + base->next = &*i.color_scale_bias; + } + + if (i.depth_test) + { + i.depth_test->next = base->next; + base->next = &*i.depth_test; + } + + if (i.settings) + { + i.settings->type = XR_TYPE_COMPOSITION_LAYER_SETTINGS_FB; + i.settings->next = base->next; + base->next = &*i.settings; + } + + openxr_layers.push_back(base); + } + + if (renderer) + renderer->end_frame(); + + // Release all swapchains after the renderer has submitted the command buffers + for (auto & swapchain: swapchains) + { + if (swapchain.used) + swapchain.swapchain.release(); + } + + session.end_frame(predicted_display_time, openxr_layers, blend_mode); +} + +std::pair scene::load_gltf(const std::filesystem::path & path, uint32_t layer_mask) +{ + auto entity = world.create(); + auto & node = world.emplace(entity); + node.layer_mask = layer_mask; + + assert(renderer); + scene_loader loader(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material()); + + loader.add_prefab(world, loader(path), entity); + + return {entity, node}; +} + void scene::on_unfocused() {} void scene::on_focused() {} void scene::on_xr_event(const xr::event &) {} diff --git a/client/scene.h b/client/scene.h index 7d2533cb..65098358 100644 --- a/client/scene.h +++ b/client/scene.h @@ -19,16 +19,25 @@ #pragma once +#include "render/scene_loader.h" #include "xr/actionset.h" #include "xr/instance.h" #include "xr/session.h" #include "xr/swapchain.h" +#include "xr/system.h" #include +#include +#include #include #include #include +#include "render/imgui_impl.h" +#include "render/scene_renderer.h" +#include +#include + // See http://www.nirfriedman.com/2018/04/29/unforgettable-factory/ // for automatic registration of scenes @@ -43,7 +52,7 @@ public: struct suggested_binding { - std::string profile_name; + std::vector profile_names; std::vector paths; }; @@ -86,6 +95,18 @@ protected: const meta & current_meta; + std::optional renderer; + +public: + std::optional loader; + +protected: + vk::Format swapchain_format; + vk::Format depth_format; + xr::system::passthrough_type passthrough_supported; + bool composition_layer_depth_test_supported; + bool composition_layer_color_scale_bias_supported; + std::pair get_action(const std::string & name) { return current_meta.actions_by_name.at(name); @@ -96,17 +117,94 @@ protected: return current_meta.spaces_by_name.at(name); } + // Helper functions + static glm::mat4 projection_matrix(XrFovf fov, float zn = 0.02); + static glm::mat4 view_matrix(XrPosef pose); + + // Layer rendering + XrEnvironmentBlendMode blend_mode; + XrTime predicted_display_time; + + struct layer + { + std::variant composition_layer; + + // TODO in place vectors + std::vector color_views; // Used by XrCompositionLayerProjection + std::vector depth_views; // Used by XrCompositionLayerProjection + + std::optional color_scale_bias; + std::optional depth_test; + std::optional settings; + }; + + std::vector layers; + std::vector openxr_layers; + + struct swapchain_entry + { + vk::Format format; + int32_t width; + int32_t height; + int sample_count; + uint32_t array_size; + + bool used; + xr::swapchain swapchain; + }; + std::vector swapchains; + + // The returned reference is valid until the next call to get_swapchain + xr::swapchain & get_swapchain(vk::Format format, int32_t width, int32_t height, int sample_count, uint32_t array_size); + void clear_swapchains(); + + void render_start(bool passthrough, XrTime predicted_display_time); + + void add_projection_layer( + XrCompositionLayerFlags flags, + XrSpace space, + std::vector && color_views, + std::vector && depth_views = {}); + + void add_quad_layer( + XrCompositionLayerFlags flags, + XrSpace space, + XrEyeVisibility eyeVisibility, + XrSwapchainSubImage subImage, + XrPosef pose, + XrExtent2Df size); + + void render_world( + XrCompositionLayerFlags flags, + XrSpace space, + std::span views, + uint32_t width, + uint32_t height, + bool keep_depth_buffer, + uint32_t layer_mask, + XrColor4f clear_color); + + void set_color_scale_bias(XrColor4f scale, XrColor4f bias); + void set_depth_test(bool write, XrCompareOpFB op); + void set_layer_settings(XrCompositionLayerSettingsFlagsFB flags); + + void render_end(); + virtual void on_unfocused(); virtual void on_focused(); public: - scene(key, const meta &); + scene(key, const meta &, std::span supported_color_formats, std::span supported_depth_formats); virtual ~scene(); void set_focused(bool status); virtual void render(const XrFrameState &) = 0; virtual void on_xr_event(const xr::event &); + + entt::registry world; + std::pair load_gltf(const std::filesystem::path & path, uint32_t layer_mask = -1); + void remove(entt::entity entity); // TODO }; template @@ -124,8 +222,8 @@ class scene_impl : public scene static inline bool registered = scene_impl::register_scene(); - scene_impl() : - scene(key{}, T::get_meta_scene()) + scene_impl(std::span supported_color_formats, std::span supported_depth_formats = {}) : + scene(key{}, T::get_meta_scene(), supported_color_formats, supported_depth_formats) { (void)registered; } diff --git a/client/scenes/hand_model.cpp b/client/scenes/hand_model.cpp index 3872a778..8411bcbf 100644 --- a/client/scenes/hand_model.cpp +++ b/client/scenes/hand_model.cpp @@ -18,72 +18,113 @@ #include "hand_model.h" #include "openxr/openxr.h" -#include +#include "render/scene_components.h" +#include +#include #include -hand_model::hand_model(const std::filesystem::path & gltf_path, scene_loader & loader, scene_data & scene) +namespace components { - root_node = scene.new_node(); - root_node->name = gltf_path.stem(); +struct hand_joint +{ + XrHandEXT hand; + XrHandJointEXT joint; +}; +} // namespace components - scene.import(loader(gltf_path), root_node); +static const std::array, XR_HAND_JOINT_COUNT_EXT - 1 /* No palm in gltf */> joints{{ + // clang-format off + {XR_HAND_JOINT_WRIST_EXT, "wrist"}, + {XR_HAND_JOINT_THUMB_METACARPAL_EXT, "thumb-metacarpal"}, + {XR_HAND_JOINT_THUMB_PROXIMAL_EXT, "thumb-phalanx-proximal"}, + {XR_HAND_JOINT_THUMB_DISTAL_EXT, "thumb-phalanx-distal"}, + {XR_HAND_JOINT_THUMB_TIP_EXT, "thumb-tip"}, + {XR_HAND_JOINT_INDEX_METACARPAL_EXT, "index-finger-metacarpal"}, + {XR_HAND_JOINT_INDEX_PROXIMAL_EXT, "index-finger-phalanx-proximal"}, + {XR_HAND_JOINT_INDEX_INTERMEDIATE_EXT, "index-finger-phalanx-intermediate"}, + {XR_HAND_JOINT_INDEX_DISTAL_EXT, "index-finger-phalanx-distal"}, + {XR_HAND_JOINT_INDEX_TIP_EXT, "index-finger-tip"}, + {XR_HAND_JOINT_MIDDLE_METACARPAL_EXT, "middle-finger-metacarpal"}, + {XR_HAND_JOINT_MIDDLE_PROXIMAL_EXT, "middle-finger-phalanx-proximal"}, + {XR_HAND_JOINT_MIDDLE_INTERMEDIATE_EXT, "middle-finger-phalanx-intermediate"}, + {XR_HAND_JOINT_MIDDLE_DISTAL_EXT, "middle-finger-phalanx-distal"}, + {XR_HAND_JOINT_MIDDLE_TIP_EXT, "middle-finger-tip"}, + {XR_HAND_JOINT_RING_METACARPAL_EXT, "ring-finger-metacarpal"}, + {XR_HAND_JOINT_RING_PROXIMAL_EXT, "ring-finger-phalanx-proximal"}, + {XR_HAND_JOINT_RING_INTERMEDIATE_EXT, "ring-finger-phalanx-intermediate"}, + {XR_HAND_JOINT_RING_DISTAL_EXT, "ring-finger-phalanx-distal"}, + {XR_HAND_JOINT_RING_TIP_EXT, "ring-finger-tip"}, + {XR_HAND_JOINT_LITTLE_METACARPAL_EXT, "pinky-finger-metacarpal"}, + {XR_HAND_JOINT_LITTLE_PROXIMAL_EXT, "pinky-finger-phalanx-proximal"}, + {XR_HAND_JOINT_LITTLE_INTERMEDIATE_EXT, "pinky-finger-phalanx-intermediate"}, + {XR_HAND_JOINT_LITTLE_DISTAL_EXT, "pinky-finger-phalanx-distal"}, + {XR_HAND_JOINT_LITTLE_TIP_EXT, "pinky-finger-tip"}, + // clang-format on +}}; - joints.resize(XR_HAND_JOINT_COUNT_EXT); - // clang-format off - joints[XR_HAND_JOINT_PALM_EXT] = node_handle(); - joints[XR_HAND_JOINT_WRIST_EXT] = scene.find_node(root_node, "wrist"); - joints[XR_HAND_JOINT_THUMB_METACARPAL_EXT] = scene.find_node(root_node, "thumb-metacarpal"); - joints[XR_HAND_JOINT_THUMB_PROXIMAL_EXT] = scene.find_node(root_node, "thumb-phalanx-proximal"); - joints[XR_HAND_JOINT_THUMB_DISTAL_EXT] = scene.find_node(root_node, "thumb-phalanx-distal"); - joints[XR_HAND_JOINT_THUMB_TIP_EXT] = scene.find_node(root_node, "thumb-tip"); - joints[XR_HAND_JOINT_INDEX_METACARPAL_EXT] = scene.find_node(root_node, "index-finger-metacarpal"); - joints[XR_HAND_JOINT_INDEX_PROXIMAL_EXT] = scene.find_node(root_node, "index-finger-phalanx-proximal"); - joints[XR_HAND_JOINT_INDEX_INTERMEDIATE_EXT] = scene.find_node(root_node, "index-finger-phalanx-intermediate"); - joints[XR_HAND_JOINT_INDEX_DISTAL_EXT] = scene.find_node(root_node, "index-finger-phalanx-distal"); - joints[XR_HAND_JOINT_INDEX_TIP_EXT] = scene.find_node(root_node, "index-finger-tip"); - joints[XR_HAND_JOINT_MIDDLE_METACARPAL_EXT] = scene.find_node(root_node, "middle-finger-metacarpal"); - joints[XR_HAND_JOINT_MIDDLE_PROXIMAL_EXT] = scene.find_node(root_node, "middle-finger-phalanx-proximal"); - joints[XR_HAND_JOINT_MIDDLE_INTERMEDIATE_EXT] = scene.find_node(root_node, "middle-finger-phalanx-intermediate"); - joints[XR_HAND_JOINT_MIDDLE_DISTAL_EXT] = scene.find_node(root_node, "middle-finger-phalanx-distal"); - joints[XR_HAND_JOINT_MIDDLE_TIP_EXT] = scene.find_node(root_node, "middle-finger-tip"); - joints[XR_HAND_JOINT_RING_METACARPAL_EXT] = scene.find_node(root_node, "ring-finger-metacarpal"); - joints[XR_HAND_JOINT_RING_PROXIMAL_EXT] = scene.find_node(root_node, "ring-finger-phalanx-proximal"); - joints[XR_HAND_JOINT_RING_INTERMEDIATE_EXT] = scene.find_node(root_node, "ring-finger-phalanx-intermediate"); - joints[XR_HAND_JOINT_RING_DISTAL_EXT] = scene.find_node(root_node, "ring-finger-phalanx-distal"); - joints[XR_HAND_JOINT_RING_TIP_EXT] = scene.find_node(root_node, "ring-finger-tip"); - joints[XR_HAND_JOINT_LITTLE_METACARPAL_EXT] = scene.find_node(root_node, "pinky-finger-metacarpal"); - joints[XR_HAND_JOINT_LITTLE_PROXIMAL_EXT] = scene.find_node(root_node, "pinky-finger-phalanx-proximal"); - joints[XR_HAND_JOINT_LITTLE_INTERMEDIATE_EXT] = scene.find_node(root_node, "pinky-finger-phalanx-intermediate"); - joints[XR_HAND_JOINT_LITTLE_DISTAL_EXT] = scene.find_node(root_node, "pinky-finger-phalanx-distal"); - joints[XR_HAND_JOINT_LITTLE_TIP_EXT] = scene.find_node(root_node, "pinky-finger-tip"); - // clang-format on +void hand_model::add_hand(scene & scene, + XrHandEXT hand, + const std::filesystem::path & gltf_path, + uint32_t layer_mask) +{ + auto && [entity, node] = scene.load_gltf(gltf_path, layer_mask); + + node.name = gltf_path.stem(); + + for (auto [joint, name]: joints) + { + entt::entity joint_entity = find_node_by_name(scene.world, name, entity); + + scene.world.emplace(joint_entity, hand, joint); + } + + // Fake joint to hide the hand when it should not be visible + scene.world.emplace(entity, hand, (XrHandJointEXT)-1); } -void hand_model::apply(const std::optional> & joints_location) +void hand_model::apply(entt::registry & scene, + const std::optional> & left_hand, + const std::optional> & right_hand) { - if (joints_location and xr::hand_tracker::check_flags(*joints_location, XR_SPACE_LOCATION_POSITION_VALID_BIT | XR_SPACE_LOCATION_POSITION_TRACKED_BIT, 0)) + for (auto && [entity, hj, node]: scene.view().each()) { - root_node->visible = true; + auto f = [&](const std::optional> & joints) { + if (joints.has_value()) + { + node.visible = true; - for (auto && [joint, loc]: std::views::zip(joints, *joints_location)) + if (hj.joint < 0 or hj.joint > XR_HAND_JOINT_COUNT_EXT) + return; + + const auto & pose = (*joints)[hj.joint].first.pose; + + node.position = { + pose.position.x, + pose.position.y, + pose.position.z}; + + node.orientation = { + pose.orientation.w, + pose.orientation.x, + pose.orientation.y, + pose.orientation.z}; + } + else + { + node.visible = false; + } + }; + + switch (hj.hand) { - if (!joint) - continue; - - joint->position = { - loc.first.pose.position.x, - loc.first.pose.position.y, - loc.first.pose.position.z}; - - joint->orientation = { - loc.first.pose.orientation.w, - loc.first.pose.orientation.x, - loc.first.pose.orientation.y, - loc.first.pose.orientation.z}; + case XR_HAND_LEFT_EXT: + f(left_hand); + break; + case XR_HAND_RIGHT_EXT: + f(right_hand); + break; + default: + break; } } - else - { - root_node->visible = false; - } } diff --git a/client/scenes/hand_model.h b/client/scenes/hand_model.h index 40645fe7..44d0b71e 100644 --- a/client/scenes/hand_model.h +++ b/client/scenes/hand_model.h @@ -18,16 +18,20 @@ #pragma once +#include "scene.h" #include "xr/hand_tracker.h" -#include +#include +#include #include -struct hand_model +namespace hand_model { - node_handle root_node; - std::vector joints; +void add_hand(scene & scene, + XrHandEXT hand, + const std::filesystem::path & gltf_path, + uint32_t layer_mask); - hand_model(const std::filesystem::path & gltf_path, scene_loader & loader, scene_data & scene); - - void apply(const std::optional> & joints); -}; +void apply(entt::registry & scene, + const std::optional> & left_hand, + const std::optional> & right_hand); +}; // namespace hand_model diff --git a/client/scenes/input_profile.cpp b/client/scenes/input_profile.cpp index 86b3482c..fa7db70c 100644 --- a/client/scenes/input_profile.cpp +++ b/client/scenes/input_profile.cpp @@ -21,6 +21,9 @@ #include "application.h" #include "asset.h" #include "hardware.h" +#include "render/scene_components.h" +#include "xr/space.h" +#include #include #include #include @@ -29,9 +32,47 @@ #include #include #include +#include + +namespace components +{ +namespace details +{ +struct node_state_transform +{ + glm::vec3 position; + glm::quat orientation; +}; + +struct node_state_visibility +{ +}; + +using node_state = std::variant, node_state_visibility>; +} // namespace details + +// Component added to nodes affected by actions +struct visual_response +{ + XrAction action; + XrActionType type; + int axis; // Only if type is XR_ACTION_TYPE_VECTOR2F_INPUT + float bias; + float scale; + + details::node_state state; +}; +} // namespace components namespace { + +// Component added to nodes bound to an action space +struct bound_space +{ + xr::spaces space; +}; + // clang-format off const std::unordered_map input_mappings = { {"xr-standard-squeeze" , "/input/squeeze/value" }, @@ -125,14 +166,14 @@ struct json_visual_response component_type type; component_property property; std::string target_node; - input_profile::node_state state; + components::details::node_state state; // OpenXR component path std::string component_subpath; }; } // namespace -input_profile::input_profile(const std::filesystem::path & json_profile, scene_loader & loader, scene_data & scene_controllers, scene_data & scene_rays) +input_profile::input_profile(scene & scene, const std::filesystem::path & json_profile, uint32_t layer_mask_controller, uint32_t layer_mask_ray) { std::string json = asset(json_profile); @@ -141,17 +182,20 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l id = std::string(root["profileId"]); - // Don't load them into the scene right now in case there is an exception - std::vector> models; + std::vector> models; std::vector json_responses; + // Fill models with the different models to be loaded and their name ("left" or "right") + // Don't load them into the scene right now in case there is an exception for (simdjson::dom::key_value_pair layout: simdjson::dom::object(root["layouts"])) { // TODO handle case where i.key is none and there is no left or right // std::string user_path = "/user/hand/" + std::string(layout.key); std::filesystem::path asset_path = json_profile.parent_path() / std::string(layout.value["assetPath"]); - scene_data & data = models.emplace_back(layout.key, loader(asset_path)).second; + // scene.load_gltf(asset_path); + + entt::registry & data = std::get<2>(models.emplace_back(layout.key, entt::null, (*scene.loader)(asset_path))); for (simdjson::dom::key_value_pair component: simdjson::dom::object(layout.value["components"])) { @@ -177,40 +221,38 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l vr.component_subpath = component_subpath; // Check if the node exists - data.find_node(vr.target_node); + find_node_by_name(data, vr.target_node); auto node_property = parse_value_node_property(response.value["valueNodeProperty"]); switch (node_property) { case value_node_property::transform: { - auto min_node = data.find_node(response.value["minNodeName"]); - auto max_node = data.find_node(response.value["maxNodeName"]); + auto min_node = data.get(find_node_by_name(data, std::string(response.value["minNodeName"]))); + auto max_node = data.get(find_node_by_name(data, std::string(response.value["maxNodeName"]))); - node_state_transform min{ - min_node->position, - min_node->orientation}; + components::details::node_state_transform min{ + min_node.position, + min_node.orientation}; - node_state_transform max{ - max_node->position, - max_node->orientation}; + components::details::node_state_transform max{ + max_node.position, + max_node.orientation}; vr.state = std::make_pair(min, max); } break; case value_node_property::visibility: - vr.state = node_state_visibility{}; + vr.state = components::details::node_state_visibility{}; break; } } } } - for (auto && [layout, model]: models) + // Add all models in the scene + for (auto & [layout, entity, model]: models) { - node_handle root_node = scene_controllers.new_node(); - root_node->name = layout; - xr::spaces space; if (layout == "left") space = xr::spaces::grip_left; @@ -223,9 +265,16 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l else continue; - model_handles.emplace_back(space, root_node); + entity = scene.world.create(); + scene.world.emplace(entity, space); + scene.world.emplace(entity, components::node{ + .name = layout, + .layer_mask = layer_mask_controller, + }); - scene_controllers.import(std::move(model), root_node); + scene.loader->add_prefab(scene.world, std::move(model), entity); + + spdlog::debug("Created entity {}", layout); } for (simdjson::dom::key_value_pair layout: simdjson::dom::object(root["layouts"])) @@ -238,16 +287,16 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l else continue; - node_handle root_node = scene_rays.new_node(); - root_node->name = (std::string)layout.key + "_ray"; - model_handles.emplace_back(space, root_node); + auto && [entity, node] = scene.load_gltf(controller_ray_model_name(), layer_mask_ray); + node.name = (std::string)layout.key + "_ray"; + spdlog::debug("Created entity {}", node.name); - scene_rays.import(loader(controller_ray_model_name()), root_node); + scene.world.emplace(entity, space); if (layout.key == "left") - left_ray = root_node; + left_ray = entity; else if (layout.key == "right") - right_ray = root_node; + right_ray = entity; } for (auto & json_response: json_responses) @@ -264,7 +313,7 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l continue; } - auto & response = responses.emplace_back(); + components::visual_response response; response.action = action.first; response.type = action.second; @@ -289,107 +338,101 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l break; } - node_handle controller_root_node; - for (auto && [i, j]: model_handles) + entt::entity controller_entity = entt::null; + for (const auto & [layout, entity, model]: models) { - if (j->name == json_response.layout) + if (layout == json_response.layout) { - controller_root_node = j; - assert(controller_root_node->name == json_response.layout); + controller_entity = entity; break; } } - response.target.node = scene_controllers.find_node(controller_root_node, json_response.target_node); - response.target.state = json_response.state; + response.state = json_response.state; + + auto target = find_node_by_name(scene.world, json_response.target_node, controller_entity); + scene.world.emplace(target, response); } offset.fill({{0, 0, 0}, {1, 0, 0, 0}}); } -static void apply_visual_response(node_handle node, std::pair transforms, float value) +static void apply_visual_response(components::node & node, std::pair transforms, float value) { - node->position = glm::mix(transforms.first.position, transforms.second.position, value); - node->orientation = glm::slerp(transforms.first.orientation, transforms.second.orientation, value); + node.position = glm::mix(transforms.first.position, transforms.second.position, value); + node.orientation = glm::slerp(transforms.first.orientation, transforms.second.orientation, value); } -static void apply_visual_response(node_handle node, input_profile::node_state_visibility, float value) +static void apply_visual_response(components::node & node, components::details::node_state_visibility, float value) { - node->visible = value > 0.5; + node.visible = value > 0.5; } -static void set_clipping_planes(node_handle node, std::span clipping_planes) +static void set_clipping_planes(entt::registry & scene, entt::entity entity, std::span clipping_planes) { - if (not node) - return; - // If the ray starts on the wrong side of the GUI, hide it entirely // This assumes the node is a child of the root node + components::node & node = scene.get(entity); for (glm::vec4 & plane: clipping_planes) { - if (glm::dot(plane, glm::vec4(node->position, 1)) < 0) + if (glm::dot(plane, glm::vec4(node.position, 1)) < 0) { - node->visible = false; + scene.get(entity).visible = false; return; } } - node->visible = true; - - for (auto child_node: node.children()) + // Apply the clipping planes on direct children of the target entity + for (auto && [child_entity, child_node]: scene.view().each()) { - size_t nb_clipping_planes = std::min(child_node->clipping_planes.size(), clipping_planes.size()); + if (child_node.parent == entity) + { + size_t nb_clipping_planes = std::min(child_node.clipping_planes.size(), clipping_planes.size()); - auto copy_results = std::ranges::copy_n( - clipping_planes.begin(), - nb_clipping_planes, - child_node->clipping_planes.begin()); + auto copy_results = std::ranges::copy_n( + clipping_planes.begin(), + nb_clipping_planes, + child_node.clipping_planes.begin()); - // Disable the remaining clipping planes - std::ranges::fill_n( - copy_results.out, - child_node->clipping_planes.size() - nb_clipping_planes, - glm::vec4(0, 0, 0, 1)); + // Disable the remaining clipping planes + std::ranges::fill_n( + copy_results.out, + child_node.clipping_planes.size() - nb_clipping_planes, + glm::vec4(0, 0, 0, 1)); + } } } -void input_profile::apply(XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right, std::span pointer_limits) +void input_profile::apply(entt::registry & scene, XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right, std::span pointer_limits) { - for (auto && [space, node]: model_handles) + for (auto && [entity, node, space]: scene.view().each()) { - if ((space == xr::spaces::grip_left or space == xr::spaces::aim_left) and hide_left) + if ((space.space == xr::spaces::grip_left or space.space == xr::spaces::aim_left) and hide_left) { - node->visible = false; - continue; + node.visible = false; } - - if ((space == xr::spaces::grip_right or space == xr::spaces::aim_right) and hide_right) + else if ((space.space == xr::spaces::grip_right or space.space == xr::spaces::aim_right) and hide_right) { - node->visible = false; - continue; + node.visible = false; } - - if (auto location = application::locate_controller(application::space(space), world_space, predicted_display_time); location) + else if (auto location = application::locate_controller(application::space(space.space), world_space, predicted_display_time); location) { - node->visible = true; + node.visible = true; - assert((int)space >= 0); - assert((int)space < offset.size()); - auto & [p, q] = offset[space]; + assert((int)space.space >= 0); + assert((int)space.space < offset.size()); + auto & [p, q] = offset[space.space]; - node->position = location->first + glm::mat3_cast(location->second * q) * p; - node->orientation = location->second * q; + node.position = location->first + glm::mat3_cast(location->second * q) * p; + node.orientation = location->second * q; } else { - node->visible = false; + node.visible = false; } } - set_clipping_planes(left_ray, pointer_limits); - set_clipping_planes(right_ray, pointer_limits); - - for (auto & response: responses) + for (auto && [entity, node, response]: scene.view().each()) { assert(response.action); @@ -441,20 +484,16 @@ void input_profile::apply(XrSpace world_space, XrTime predicted_display_time, bo if ((scaled_value < 0) || (scaled_value > 1)) { - std::string full_name = response.target.node->name; - - for (auto i = response.target.node; i; i = i.parent()) - { - full_name = i->name + "/" + full_name; - } - - spdlog::warn("Out of range value {} (scaled to {}) for node {}", *value, scaled_value, full_name); + spdlog::warn("Out of range value {} (scaled to {}) for node {}", *value, scaled_value, get_node_name(scene, entity)); } std::visit([&](auto & transform) { - apply_visual_response(response.target.node, transform, scaled_value); + apply_visual_response(node, transform, scaled_value); }, - response.target.state); + response.state); } } + + set_clipping_planes(scene, left_ray, pointer_limits); + set_clipping_planes(scene, right_ray, pointer_limits); } diff --git a/client/scenes/input_profile.h b/client/scenes/input_profile.h index 97ea4c53..6ffe33bd 100644 --- a/client/scenes/input_profile.h +++ b/client/scenes/input_profile.h @@ -18,58 +18,27 @@ #pragma once +#include "scene.h" +#include +#include #include #include #include -#include #include -#include #include #include struct input_profile { - struct node_state_transform - { - glm::vec3 position; - glm::quat orientation; - }; - - struct node_state_visibility - { - }; - - using node_state = std::variant, node_state_visibility>; - - struct node_target - { - node_handle node; - node_state state; - }; - - struct visual_response - { - XrAction action; - XrActionType type; - int axis; // Only if type is XR_ACTION_TYPE_VECTOR2F_INPUT - float bias; - float scale; - - node_target target; - }; - std::string id; - std::vector responses; - std::vector> model_handles; - - node_handle left_ray; - node_handle right_ray; + entt::entity left_ray; + entt::entity right_ray; magic_enum::containers::array> offset; - input_profile(const std::filesystem::path & json_profile, scene_loader & loader, scene_data & scene_controllers, scene_data & scene_rays); + input_profile(scene & scene, const std::filesystem::path & json_profile, uint32_t layer_mask_controller, uint32_t layer_mask_ray); // application::poll_actions() must have been called before - void apply(XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right, std::span pointer_limits); + void apply(entt::registry & scene, XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right, std::span pointer_limits); }; diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index 9e8cd4d6..d4d4727f 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -21,16 +21,14 @@ #include "application.h" #include "constants.h" #include "glm/geometric.hpp" +#include "hand_model.h" #include "hardware.h" #include "imgui.h" -#include "input_profile.h" #include "openxr/openxr.h" #include "protocol_version.h" #include "render/scene_data.h" -#include "render/scene_renderer.h" #include "stream.h" #include "utils/i18n.h" -#include "utils/overloaded.h" #include "wivrn_client.h" #include "wivrn_discover.h" #include "wivrn_sockets.h" @@ -38,9 +36,7 @@ #include "xr/space.h" #include -#include #include // IWYU pragma: keep -#include #include #include #include @@ -110,76 +106,37 @@ void scenes::lobby::move_gui(glm::vec3 head_position, glm::vec3 new_gui_position imgui_ctx->layers()[2].orientation = q * glm::quat(cos(keyboard_pitch / 2), sin(keyboard_pitch / 2), 0, 0); } -scenes::lobby::lobby() +scenes::lobby::lobby() : + scene_impl(supported_color_formats, supported_depth_formats) { + spdlog::info("Using formats {} and {}", vk::to_string(swapchain_format), vk::to_string(depth_format)); + // composition_layer_depth_test_supported = false; + if (composition_layer_depth_test_supported) + spdlog::info("Composition layer depth test supported"); + else + spdlog::info("Composition layer depth test NOT supported"); + + if (composition_layer_color_scale_bias_supported) + spdlog::info("Composition layer color scale/bias supported"); + else + spdlog::info("Composition layer color scale/bias NOT supported"); + if (std::getenv("WIVRN_AUTOCONNECT")) force_autoconnect = true; - passthrough_supported = system.passthrough_supported(); + auto & config = application::get_config(); - auto & servers = application::get_config().servers; + auto & servers = config.servers; spdlog::info("{} known server(s):", servers.size()); for (auto & i: servers) { spdlog::info(" {}", i.second.service.name); } - haptic_output[0] = get_action("left_haptic").first; - haptic_output[1] = get_action("right_haptic").first; + keyboard.set_layout(config.virtual_keyboard_layout); - swapchain_format = vk::Format::eUndefined; - spdlog::info("Supported swapchain formats:"); - - for (auto format: session.get_swapchain_formats()) - { - spdlog::info(" {}", vk::to_string(format)); - } - - for (auto format: session.get_swapchain_formats()) - { - if (std::find(supported_color_formats.begin(), supported_color_formats.end(), format) != supported_color_formats.end()) - { - swapchain_format = format; - break; - } - } - - if (swapchain_format == vk::Format::eUndefined) - throw std::runtime_error(_("No supported swapchain format")); - - auto views = system.view_configuration_views(viewconfig); - stream_view = override_view(views[0], guess_model()); - uint32_t width = views[0].recommendedImageRectWidth; - uint32_t height = views[0].recommendedImageRectHeight; - - depth_format = scene_renderer::find_usable_image_format( - physical_device, - supported_depth_formats, - { - width, - height, - 1, - }, - vk::ImageUsageFlagBits::eDepthStencilAttachment); - - spdlog::info("Using formats {} and {}", vk::to_string(swapchain_format), vk::to_string(depth_format)); - - composition_layer_depth_test_supported = - instance.has_extension(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME) and - instance.has_extension(XR_FB_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME); - - if (composition_layer_depth_test_supported) - spdlog::info("Composition layer depth test supported"); - else - spdlog::info("Composition layer depth test NOT supported"); - - composition_layer_color_scale_bias_supported = instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME); - if (composition_layer_color_scale_bias_supported) - spdlog::info("Composition layer color scale/bias supported"); - else - spdlog::info("Composition layer color scale/bias NOT supported"); - - keyboard.set_layout(application::get_config().virtual_keyboard_layout); + if (config.first_run) + current_tab = tab::first_run; const auto keypair_path = application::get_config_path() / "private_key.pem"; try @@ -346,37 +303,6 @@ std::unique_ptr scenes::lobby::connect_to_session(wivrn_discover: throw std::runtime_error(error); } -static glm::mat4 projection_matrix(XrFovf fov, float zn = 0.02) -{ - float r = tan(fov.angleRight); - float l = tan(fov.angleLeft); - float t = tan(fov.angleUp); - float b = tan(fov.angleDown); - - // reversed Z projection, infinite far plane - - // clang-format off - return glm::mat4{ - { 2/(r-l), 0, 0, 0 }, - { 0, 2/(b-t), 0, 0 }, - { (l+r)/(r-l), (t+b)/(b-t), 0, -1 }, - { 0, 0, zn, 0 } - }; - // clang-format on -} - -static glm::mat4 view_matrix(XrPosef pose) -{ - XrQuaternionf q = pose.orientation; - XrVector3f pos = pose.position; - - glm::mat4 inv_view_matrix = glm::mat4_cast(glm::quat(q.w, q.x, q.y, q.z)); - - inv_view_matrix = glm::translate(glm::mat4(1), glm::vec3(pos.x, pos.y, pos.z)) * inv_view_matrix; - - return glm::inverse(inv_view_matrix); -} - void scenes::lobby::update_server_list() { if (application::is_focused() && !discover) @@ -476,19 +402,27 @@ std::optional scenes::lobby::check_recenter_gesture(const std::array< std::optional scenes::lobby::check_recenter_action(XrTime predicted_display_time, glm::vec3 head_position) { std::optional> aim; + glm::vec3 offset_position; + glm::quat offset_orientation; if (application::read_action_bool(recenter_left_action).value_or(std::pair{0, false}).second) { aim = application::locate_controller(application::space(xr::spaces::aim_left), application::space(xr::spaces::world), predicted_display_time); + std::tie(offset_position, offset_orientation) = input->offset[xr::spaces::aim_left]; } if (application::read_action_bool(recenter_right_action).value_or(std::pair{0, false}).second) { aim = application::locate_controller(application::space(xr::spaces::aim_right), application::space(xr::spaces::world), predicted_display_time); + std::tie(offset_position, offset_orientation) = input->offset[xr::spaces::aim_right]; } if (aim) { + // Handle controller offset + aim->first = aim->first + glm::mat3_cast(aim->second * offset_orientation) * offset_position; + aim->second = aim->second * offset_orientation; + if (not gui_recenter_position or not gui_recenter_distance) { // First frame where the recenter action is active @@ -500,7 +434,7 @@ std::optional scenes::lobby::check_recenter_action(XrTime predicted_d imgui_ctx->compute_pointer_position(state); - if (state.pointer_position) + if (state.pointer_position) // TODO: check that the pointer is inside an imgui window { auto M = glm::mat3_cast(imgui_ctx->layers()[0].orientation); @@ -572,80 +506,6 @@ std::optional scenes::lobby::check_recenter_gui(glm::vec3 head_positi return std::nullopt; } -static std::pair, std::vector> render_layer( - std::vector & views, - std::vector & color_swapchains, - std::vector & depth_swapchains, - scene_renderer & renderer, - scene_data & data, - const std::array & clear_color) -{ - std::vector frames; - frames.reserve(views.size()); - - std::vector proj_layer_views; - std::vector depth_layer_views; - proj_layer_views.reserve(views.size()); - depth_layer_views.reserve(views.size()); - - for (auto && [view, color_swapchain, depth_swapchain]: std::views::zip(views, color_swapchains, depth_swapchains)) - { - int color_image_index = color_swapchain.acquire(); - color_swapchain.wait(); - - int depth_image_index = depth_swapchain ? depth_swapchain.acquire() : 0; - if (depth_swapchain) - depth_swapchain.wait(); - - frames.push_back({ - .destination = color_swapchain.images()[color_image_index].image, - .depth_buffer = depth_swapchain ? depth_swapchain.images()[depth_image_index].image : vk::Image{}, - .projection = projection_matrix(view.fov, constants::lobby::near_plane), - .view = view_matrix(view.pose), - }); - - proj_layer_views.push_back({ - .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, - .pose = view.pose, - .fov = view.fov, - .subImage = { - .swapchain = color_swapchain, - .imageRect = { - .offset = {0, 0}, - .extent = color_swapchain.extent(), - }, - }, - }); - - depth_layer_views.push_back({ - .type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, - .subImage = { - .swapchain = depth_swapchain, - .imageRect = { - .offset = {0, 0}, - .extent = depth_swapchain.extent(), - }, - }, - .minDepth = 0, - .maxDepth = 1, - .nearZ = std::numeric_limits::infinity(), - .farZ = constants::lobby::near_plane, - }); - } - - renderer.render(data, clear_color, frames); - - return {proj_layer_views, depth_layer_views}; -} - -static std::vector render_layer(std::vector & views, std::vector & color_swapchains, scene_renderer & renderer, scene_data & data, const std::array & clear_color) -{ - std::vector depth_swapchains; - depth_swapchains.resize(color_swapchains.size()); - - return std::get<0>(render_layer(views, color_swapchains, depth_swapchains, renderer, data, clear_color)); -} - // Return the vector v such that dot(v, x) > 0 iff x is on the side where the composition layer is visible static glm::vec4 compute_ray_limits(const XrPosef & pose, float margin = 0) { @@ -737,7 +597,8 @@ void scenes::lobby::render(const XrFrameState & frame_state) XrSpace world_space = application::space(xr::spaces::world); auto [flags, views] = session.locate_views(viewconfig, frame_state.predictedDisplayTime, world_space); - assert(views.size() == swapchains_lobby.size()); + // assert(views.size() == swapchains_lobby.size()); + assert(views.size() == 2); // FIXME bool hide_left_controller = false; bool hide_right_controller = false; @@ -753,75 +614,70 @@ void scenes::lobby::render(const XrFrameState & frame_state) if (application::get_hand_tracking_supported()) { - if (left_hand) - { - auto & hand = application::get_left_hand(); - auto joints = hand.locate(world_space, frame_state.predictedDisplayTime); - left_hand->apply(joints); + auto left = application::get_left_hand().locate(world_space, frame_state.predictedDisplayTime); + auto right = application::get_right_hand().locate(world_space, frame_state.predictedDisplayTime); - if (joints and xr::hand_tracker::check_flags(*joints, XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT, 0)) - { - hide_left_controller = true; - if (!new_gui_position) - new_gui_position = check_recenter_gesture(*joints); - } + hand_model::apply(world, left, right); + + if (left and xr::hand_tracker::check_flags(*left, XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT, 0)) + { + hide_left_controller = true; + if (!new_gui_position) + new_gui_position = check_recenter_gesture(*left); } - if (right_hand) + if (right and xr::hand_tracker::check_flags(*right, XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT, 0)) { - auto & hand = application::get_right_hand(); - auto joints = hand.locate(world_space, frame_state.predictedDisplayTime); - right_hand->apply(joints); - - if (joints and xr::hand_tracker::check_flags(*joints, XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT, 0)) - { - hide_right_controller = true; - if (!new_gui_position) - new_gui_position = check_recenter_gesture(*joints); - } + hide_right_controller = true; + if (!new_gui_position) + new_gui_position = check_recenter_gesture(*right); } } -#if WIVRN_CLIENT_DEBUG_MENU - if (display_debug_axes) - { - const xr::spaces left = display_grip_instead_of_aim ? xr::spaces::grip_left : xr::spaces::aim_left; - const xr::spaces right = display_grip_instead_of_aim ? xr::spaces::grip_right : xr::spaces::aim_right; - - if (hide_left_controller) - xyz_axes_left_controller->visible = false; - else if (auto location = application::locate_controller(application::space(left), world_space, frame_state.predictedDisplayTime)) - { - xyz_axes_left_controller->visible = true; - xyz_axes_left_controller->position = location->first; - xyz_axes_left_controller->orientation = location->second; - } - else - xyz_axes_left_controller->visible = false; - - if (hide_right_controller) - xyz_axes_right_controller->visible = false; - else if (auto location = application::locate_controller(application::space(right), world_space, frame_state.predictedDisplayTime)) - { - xyz_axes_right_controller->visible = true; - xyz_axes_right_controller->position = location->first; - xyz_axes_right_controller->orientation = location->second; - } - else - xyz_axes_right_controller->visible = false; - } - else - { - xyz_axes_left_controller->visible = false; - xyz_axes_right_controller->visible = false; - } -#endif - if (head_position && new_gui_position) { move_gui(head_position->first, *new_gui_position); } +#if WIVRN_CLIENT_DEBUG_MENU + { + auto & left_node = world.get(xyz_axes_left_controller); + auto & right_node = world.get(xyz_axes_right_controller); + if (display_debug_axes) + { + const xr::spaces left = display_grip_instead_of_aim ? xr::spaces::grip_left : xr::spaces::aim_left; + + if (hide_left_controller) + left_node.visible = false; + else if (auto location = application::locate_controller(application::space(left), world_space, frame_state.predictedDisplayTime)) + { + left_node.visible = true; + left_node.position = location->first; + left_node.orientation = location->second; + } + else + left_node.visible = false; + + const xr::spaces right = display_grip_instead_of_aim ? xr::spaces::grip_right : xr::spaces::aim_right; + if (hide_right_controller) + right_node.visible = false; + else if (auto location = application::locate_controller(application::space(right), world_space, frame_state.predictedDisplayTime)) + { + right_node.visible = true; + right_node.position = location->first; + right_node.orientation = location->second; + } + else + right_node.visible = false; + } + else + { + left_node.visible = false; + right_node.visible = false; + } + } +#endif + std::vector> imgui_layers = draw_gui(frame_state.predictedDisplayTime); // Get the planes that limit the ray size from the composition layers @@ -832,176 +688,65 @@ void scenes::lobby::render(const XrFrameState & frame_state) ray_limits.push_back(compute_ray_limits(layer.pose)); } - input->apply(world_space, frame_state.predictedDisplayTime, hide_left_controller, hide_right_controller, ray_limits); + input->apply(world, world_space, frame_state.predictedDisplayTime, hide_left_controller, hide_right_controller, ray_limits); assert(renderer); - renderer->start_frame(); - std::vector lobby_layer_views; - std::vector lobby_depth_layer_views; - std::vector controllers_layer_views; - std::vector controllers_depth_layer_views; + world.get(lobby_entity).visible = not application::get_config().passthrough_enabled; - std::array clear_color; + render_start(application::get_config().passthrough_enabled, frame_state.predictedDisplayTime); - lobby_handle->visible = not application::get_config().passthrough_enabled; - - if (application::get_config().passthrough_enabled) - clear_color = {0, 0, 0, 0}; - else - clear_color = constants::lobby::sky_color; + const XrColor4f clear_color = application::get_config().passthrough_enabled ? XrColor4f{0, 0, 0, 0} : constants::lobby::sky_color; + render_world( + XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + world_space, + views, + width, + height, + composition_layer_depth_test_supported, + composition_layer_depth_test_supported ? layer_lobby | layer_controllers : layer_lobby, + clear_color); if (composition_layer_depth_test_supported) + set_depth_test(true, XR_COMPARE_OP_ALWAYS_FB); + + bool dim_gui = imgui_ctx->is_modal_popup_shown() and composition_layer_color_scale_bias_supported; + for (auto & [z_index, layer]: imgui_layers) { - std::tie(lobby_layer_views, lobby_depth_layer_views) = render_layer( - views, - swapchains_lobby, - swapchains_lobby_depth, - *renderer, - *lobby_scene, - clear_color); - for (auto [color, depth]: std::views::zip(lobby_layer_views, lobby_depth_layer_views)) - color.next = &depth; + if (z_index < constants::lobby::zindex_recenter_tip) + { + add_quad_layer(layer.layerFlags, layer.space, layer.eyeVisibility, layer.subImage, layer.pose, layer.size); - std::tie(controllers_layer_views, controllers_depth_layer_views) = render_layer( - views, - swapchains_controllers, - swapchains_controllers_depth, - *renderer, - *controllers_scene, - {0, 0, 0, 0}); - for (auto [color, depth]: std::views::zip(controllers_layer_views, controllers_depth_layer_views)) - color.next = &depth; + if (dim_gui) + set_color_scale_bias(constants::lobby::dimming_scale, constants::lobby::dimming_bias); - renderer->end_frame(); + if (composition_layer_depth_test_supported) + set_depth_test(true, XR_COMPARE_OP_LESS_OR_EQUAL_FB); - // After end_frame because the command buffers are submitted in end_frame - for (auto & swapchain: swapchains_lobby) - swapchain.release(); - - for (auto & swapchain: swapchains_lobby_depth) - swapchain.release(); - - for (auto & swapchain: swapchains_controllers) - swapchain.release(); - - for (auto & swapchain: swapchains_controllers_depth) - swapchain.release(); - } - else - { - lobby_layer_views = render_layer( - views, - swapchains_lobby, - *renderer, - *lobby_scene, - clear_color); - - controllers_layer_views = render_layer( - views, - swapchains_controllers, - *renderer, - *controllers_scene, - {0, 0, 0, 0}); - - renderer->end_frame(); - - // After end_frame because the command buffers are submitted in end_frame - for (auto & swapchain: swapchains_lobby) - swapchain.release(); - - for (auto & swapchain: swapchains_controllers) - swapchain.release(); + dim_gui = false; // Only dim the main window + } } - XrCompositionLayerProjection lobby_layer{ - .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION, - .layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, - .space = world_space, - .viewCount = (uint32_t)lobby_layer_views.size(), - .views = lobby_layer_views.data(), - }; + render_world( + XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + world_space, + views, + width, + height, + composition_layer_depth_test_supported, + composition_layer_depth_test_supported ? layer_rays : layer_rays | layer_controllers, + {0, 0, 0, 0}); - XrCompositionLayerProjection controllers_layer{ - .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION, - .layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, - .space = world_space, - .viewCount = (uint32_t)controllers_layer_views.size(), - .views = controllers_layer_views.data(), - }; - - XrEnvironmentBlendMode blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; - std::vector> layers_with_z_index; - - if (application::get_config().passthrough_enabled) - { - std::visit( - utils::overloaded{ - [&](std::monostate &) { - assert(false); - }, - [&](xr::passthrough_alpha_blend & p) { - blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND; - }, - [&](auto & p) { - layers_with_z_index.emplace_back(constants::lobby::zindex_passthrough, p.layer()); - }}, - session.get_passthrough()); - } - - // Dimming settings if a popup window is displayed - XrCompositionLayerColorScaleBiasKHR color_scale_bias{ - .type = XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR, - .colorScale = constants::lobby::dimming_scale, - .colorBias = constants::lobby::dimming_bias, - }; - - // Add XrCompositionLayerDepthTestFB to lobby_layer and imgui_layer - // The sky in the lobby layer and the passthrough layer have the same depth, so the operation must be: - // - LESS when passthrough is enabled (to avoid overwriting the passthrough) - // - LESS_OR_EQUAL when passthrough is disabled (so that the sky is visible) - XrCompositionLayerDepthTestFB layer_depth_test{ - .type = XR_TYPE_COMPOSITION_LAYER_DEPTH_TEST_FB, - .next = nullptr, - .depthMask = true, - .compareOp = application::get_config().passthrough_enabled ? XR_COMPARE_OP_LESS_FB : XR_COMPARE_OP_LESS_OR_EQUAL_FB, - }; - - // if (composition_layer_depth_test_supported or not application::get_config().passthrough_enabled) - layers_with_z_index.emplace_back(constants::lobby::zindex_lobby, reinterpret_cast(&lobby_layer)); + if (composition_layer_depth_test_supported) + set_depth_test(true, XR_COMPARE_OP_LESS_OR_EQUAL_FB); for (auto & [z_index, layer]: imgui_layers) - layers_with_z_index.emplace_back(z_index, reinterpret_cast(&layer)); - - layers_with_z_index.emplace_back(constants::lobby::zindex_controllers, reinterpret_cast(&controllers_layer)); - - if (composition_layer_depth_test_supported) { - lobby_layer.next = &layer_depth_test; - - for (auto & [z_index, layer]: imgui_layers) - { - if (z_index != constants::lobby::zindex_recenter_tip) - layer.next = &layer_depth_test; - } - - controllers_layer.next = &layer_depth_test; + if (z_index == constants::lobby::zindex_recenter_tip) + add_quad_layer(layer.layerFlags, layer.space, layer.eyeVisibility, layer.subImage, layer.pose, layer.size); } - if (imgui_ctx->is_modal_popup_shown() and composition_layer_color_scale_bias_supported) - { - color_scale_bias.next = imgui_layers.front().second.next; - imgui_layers.front().second.next = &color_scale_bias; - } - - std::ranges::stable_sort(layers_with_z_index); - - std::vector layers; - layers.reserve(layers_with_z_index.size()); - for (auto & [z_index, layer]: layers_with_z_index) - layers.push_back(layer); - - session.end_frame(frame_state.predictedDisplayTime, layers, blend_mode); + render_end(); } void scenes::lobby::on_focused() @@ -1009,53 +754,25 @@ void scenes::lobby::on_focused() recenter_gui = true; auto views = system.view_configuration_views(viewconfig); + assert(views.size() == 2); // FIXME stream_view = override_view(views[0], guess_model()); - uint32_t width = views[0].recommendedImageRectWidth; - uint32_t height = views[0].recommendedImageRectHeight; + width = views[0].recommendedImageRectWidth; + height = views[0].recommendedImageRectHeight; - swapchains_lobby.reserve(views.size()); - swapchains_controllers.reserve(views.size()); + // assert(std::ranges::all_of(views, [width](const XrViewConfigurationView & view) { return view.recommendedImageRectWidth == width; })); + // assert(std::ranges::all_of(views, [height](const XrViewConfigurationView & view) { return view.recommendedImageRectHeight == height; })); - if (composition_layer_depth_test_supported) - swapchains_lobby_depth.reserve(views.size()); + renderer.emplace(device, physical_device, queue, commandpool); + loader.emplace(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material()); - for ([[maybe_unused]] auto view: views) - { - assert(view.recommendedImageRectWidth == width); - assert(view.recommendedImageRectHeight == height); + lobby_entity = load_gltf("ground.gltf", layer_lobby).first; - swapchains_lobby.emplace_back(session, device, swapchain_format, width, height); - swapchains_controllers.emplace_back(session, device, swapchain_format, width, height); - - if (composition_layer_depth_test_supported) - { - swapchains_lobby_depth.emplace_back(session, device, depth_format, width, height); - swapchains_controllers_depth.emplace_back(session, device, depth_format, width, height); - } - } - - spdlog::info("Created lobby swapchains: {}x{}", width, height); - - vk::Extent2D output_size{width, height}; - - renderer.emplace(device, physical_device, queue, commandpool, output_size, swapchain_format, depth_format, 2, composition_layer_depth_test_supported); - - scene_loader loader(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material()); - - lobby_scene.emplace(); - lobby_handle = lobby_scene->new_node(); - lobby_scene->import(loader("ground.gltf"), lobby_handle); - - controllers_scene.emplace(); - - scene_data & controllers_scene_data = composition_layer_depth_test_supported ? *lobby_scene : *controllers_scene; - - auto profile = controller_name(); - input = input_profile( + std::string profile = controller_name(); + input.emplace( + *this, "controllers/" + profile + "/profile.json", - loader, - controllers_scene_data, - *controllers_scene); + layer_controllers, + layer_rays); spdlog::info("Loaded input profile {}", input->id); @@ -1079,17 +796,14 @@ void scenes::lobby::on_focused() offset_orientation = glm::degrees(glm::eulerAngles(input->offset[xr::spaces::grip_left].second)); ray_offset = input->offset[xr::spaces::aim_left].first.z; - xyz_axes_left_controller = controllers_scene_data.new_node(); - controllers_scene_data.import(loader("xyz-arrows.glb"), xyz_axes_left_controller); - - xyz_axes_right_controller = controllers_scene_data.new_node(); - controllers_scene_data.import(loader("xyz-arrows.glb"), xyz_axes_right_controller); + xyz_axes_left_controller = load_gltf("xyz-arrows.glb", layer_controllers).first; + xyz_axes_right_controller = load_gltf("xyz-arrows.glb", layer_controllers).first; #endif if (application::get_hand_tracking_supported()) { - left_hand.emplace("left-hand.glb", loader, controllers_scene_data); - right_hand.emplace("right-hand.glb", loader, controllers_scene_data); + hand_model::add_hand(*this, XR_HAND_LEFT_EXT, "left-hand.glb", layer_controllers); + hand_model::add_hand(*this, XR_HAND_RIGHT_EXT, "right-hand.glb", layer_controllers); } recenter_left_action = get_action("recenter_left").first; @@ -1102,6 +816,7 @@ void scenes::lobby::on_focused() .trigger = get_action("left_trigger").first, .squeeze = get_action("left_squeeze").first, .scroll = get_action("left_scroll").first, + .haptic_output = get_action("left_haptic").first, }, imgui_context::controller{ .aim = get_action_space("right_aim"), @@ -1109,6 +824,7 @@ void scenes::lobby::on_focused() .trigger = get_action("right_trigger").first, .squeeze = get_action("right_squeeze").first, .scroll = get_action("right_scroll").first, + .haptic_output = get_action("right_haptic").first, }, }; if (auto & hand = application::get_left_hand()) @@ -1209,20 +925,15 @@ void scenes::lobby::on_unfocused() renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets - about_picture = nullptr; + about_picture = 0; imgui_ctx.reset(); - lobby_scene.reset(); // Must be reset before the renderer so that the descriptor sets are freed before their pools - controllers_scene.reset(); + world.clear(); // Must be cleared before the renderer so that the descriptor sets are freed before their pools input.reset(); - left_hand.reset(); - right_hand.reset(); + loader.reset(); renderer.reset(); - swapchains_lobby.clear(); - swapchains_controllers.clear(); - swapchains_lobby_depth.clear(); - swapchains_controllers_depth.clear(); + clear_swapchains(); swapchain_imgui = xr::swapchain(); multicast.reset(); } @@ -1267,7 +978,17 @@ scene::meta & scenes::lobby::get_meta_scene() }, .bindings = { suggested_binding{ - "/interaction_profiles/oculus/touch_controller", + { + "/interaction_profiles/oculus/touch_controller", + "/interaction_profiles/facebook/touch_controller_pro", + "/interaction_profiles/meta/touch_pro_controller", + "/interaction_profiles/meta/touch_controller_plus", + "/interaction_profiles/meta/touch_plus_controller", + "/interaction_profiles/bytedance/pico_neo3_controller", + "/interaction_profiles/bytedance/pico4_controller", + "/interaction_profiles/bytedance/pico4s_controller", + "/interaction_profiles/htc/vive_focus3_controller", + }, { {"left_aim", "/user/hand/left/input/aim/pose"}, {"left_trigger", "/user/hand/left/input/trigger/value"}, @@ -1280,84 +1001,14 @@ scene::meta & scenes::lobby::get_meta_scene() {"right_scroll", "/user/hand/right/input/thumbstick"}, {"right_haptic", "/user/hand/right/output/haptic"}, - {"recenter_left", "/user/hand/left/input/x/click"}, - {"recenter_right", "/user/hand/right/input/a/click"}, + {"recenter_left", "/user/hand/left/input/squeeze/value"}, + {"recenter_right", "/user/hand/right/input/squeeze/value"}, }, }, suggested_binding{ - "/interaction_profiles/bytedance/pico_neo3_controller", { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/trigger/value"}, - {"left_squeeze", "/user/hand/left/input/squeeze/value"}, - {"left_scroll", "/user/hand/left/input/thumbstick"}, - {"left_haptic", "/user/hand/left/output/haptic"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/trigger/value"}, - {"right_squeeze", "/user/hand/right/input/squeeze/value"}, - {"right_scroll", "/user/hand/right/input/thumbstick"}, - {"right_haptic", "/user/hand/right/output/haptic"}, - - {"recenter_left", "/user/hand/left/input/x/click"}, - {"recenter_right", "/user/hand/right/input/a/click"}, + "/interaction_profiles/khr/simple_controller", }, - }, - suggested_binding{ - "/interaction_profiles/bytedance/pico4_controller", - { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/trigger/value"}, - {"left_squeeze", "/user/hand/left/input/squeeze/value"}, - {"left_scroll", "/user/hand/left/input/thumbstick"}, - {"left_haptic", "/user/hand/left/output/haptic"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/trigger/value"}, - {"right_squeeze", "/user/hand/right/input/squeeze/value"}, - {"right_scroll", "/user/hand/right/input/thumbstick"}, - {"right_haptic", "/user/hand/right/output/haptic"}, - - {"recenter_left", "/user/hand/left/input/x/click"}, - {"recenter_right", "/user/hand/right/input/a/click"}, - }, - }, - suggested_binding{ - "/interaction_profiles/bytedance/pico4s_controller", - { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/trigger/value"}, - {"left_squeeze", "/user/hand/left/input/squeeze/value"}, - {"left_scroll", "/user/hand/left/input/thumbstick"}, - {"left_haptic", "/user/hand/left/output/haptic"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/trigger/value"}, - {"right_squeeze", "/user/hand/right/input/squeeze/value"}, - {"right_scroll", "/user/hand/right/input/thumbstick"}, - {"right_haptic", "/user/hand/right/output/haptic"}, - - {"recenter_left", "/user/hand/left/input/x/click"}, - {"recenter_right", "/user/hand/right/input/a/click"}, - }, - }, - suggested_binding{ - "/interaction_profiles/htc/vive_focus3_controller", - { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/trigger/value"}, - {"left_squeeze", "/user/hand/left/input/squeeze/value"}, - {"left_scroll", "/user/hand/left/input/thumbstick"}, - {"left_haptic", "/user/hand/left/output/haptic"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/trigger/value"}, - {"right_squeeze", "/user/hand/right/input/squeeze/value"}, - {"right_scroll", "/user/hand/right/input/thumbstick"}, - {"right_haptic", "/user/hand/right/output/haptic"}, - - {"recenter_left", "/user/hand/left/input/x/click"}, - {"recenter_right", "/user/hand/right/input/a/click"}, - }, - }, - suggested_binding{ - "/interaction_profiles/khr/simple_controller", { {"left_aim", "/user/hand/left/input/aim/pose"}, {"left_trigger", "/user/hand/left/input/select/click"}, diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index 284e0d55..86d8a77b 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -22,23 +22,19 @@ #include "asset.h" #include "configuration.h" #include "crypto.h" -#include "render/scene_data.h" #include "scene.h" -#include "scenes/hand_model.h" #include "scenes/lobby_keyboard.h" #include "utils/thread_safe.h" #include "wifi_lock.h" #include "wivrn_config.h" #include "wivrn_discover.h" +#include "wivrn_packets.h" #include -#include "xr/system.h" #include #include #include "input_profile.h" -#include "render/imgui_impl.h" -#include "render/scene_renderer.h" #include "utils/async.h" class wivrn_session; @@ -64,37 +60,27 @@ class lobby : public scene_impl std::string server_name; bool autoconnect_enabled = true; - std::optional renderer; - std::optional lobby_scene; - std::optional controllers_scene; std::optional input; - std::optional left_hand; - std::optional right_hand; - node_handle lobby_handle; - bool composition_layer_depth_test_supported; - bool composition_layer_color_scale_bias_supported; + entt::entity lobby_entity; std::optional imgui_ctx; - std::array haptic_output; std::string selected_item; std::unique_ptr license; - ImGuiID hovered_item; - std::vector swapchains_lobby; - std::vector swapchains_lobby_depth; - std::vector swapchains_controllers; - std::vector swapchains_controllers_depth; + static inline const uint32_t layer_lobby = 1 << 0; + static inline const uint32_t layer_controllers = 1 << 1; + static inline const uint32_t layer_rays = 1 << 2; + + uint32_t width; + uint32_t height; xr::swapchain swapchain_imgui; - vk::Format swapchain_format; - vk::Format depth_format; - xr::system::passthrough_type passthrough_supported; XrViewConfigurationView stream_view; #if WIVRN_CLIENT_DEBUG_MENU // GUI debug - node_handle xyz_axes_left_controller; - node_handle xyz_axes_right_controller; + entt::entity xyz_axes_left_controller; + entt::entity xyz_axes_right_controller; bool display_debug_axes = false; bool display_grip_instead_of_aim = false; glm::vec3 offset_position{}; @@ -112,10 +98,10 @@ class lobby : public scene_impl std::optional gui_recenter_distance; bool recenter_gui = true; void move_gui(glm::vec3 head_position, glm::vec3 new_gui_position); - void tooltip(std::string_view text); enum class tab { + first_run, server_list, settings, post_processing, @@ -124,11 +110,13 @@ class lobby : public scene_impl #endif about, licenses, - exit + exit, + connected, }; tab current_tab = tab::server_list; tab last_current_tab = tab::server_list; + int optional_feature_index = 0; // Which step of the first run screen are we in ImTextureID about_picture; virtual_keyboard keyboard; @@ -146,6 +134,7 @@ class lobby : public scene_impl void draw_features_status(XrTime predicted_display_time); void gui_connecting(locked_notifiable & request); void gui_enter_pin(locked_notifiable & request); + void gui_connected(); void gui_server_list(); void gui_new_server(); void gui_settings(); @@ -154,11 +143,10 @@ class lobby : public scene_impl void gui_about(); void gui_licenses(); void gui_keyboard(); + void gui_first_run(); void setup_passthrough(); - void vibrate_on_hover(); - void connect(const configuration::server_data & data); std::unique_ptr connect_to_session(wivrn_discover::service service, bool manual_connection); diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index 8eb550e9..878d52ab 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -28,14 +28,13 @@ #include "constants.h" #include "imgui.h" #include "imgui_internal.h" -#include "implot.h" #include "lobby.h" #include "stream.h" #include "utils/i18n.h" #include "utils/overloaded.h" #include "version.h" #include -#include +#include #include #include #include @@ -44,6 +43,31 @@ #include "IconsFontAwesome6.h" +static void ScrollWhenDraggingOnVoid() +{ + ImVec2 delta{0.0f, -ImGui::GetIO().MouseDelta.y}; + + // https://github.com/ocornut/imgui/issues/3379#issuecomment-1678718752 + ImGuiContext & g = *ImGui::GetCurrentContext(); + ImGuiWindow * window = g.CurrentWindow; + bool hovered = false; + bool held = false; + static bool held_prev = false; + + // Don't drag for the first frame because the current controller might have just changed and have a large delta + + ImGuiID id = window->GetID("##scrolldraggingoverlay"); + ImGui::KeepAliveID(id); + if (g.HoveredId == 0) // If nothing hovered so far in the frame (not same as IsAnyItemHovered()!) + ImGui::ButtonBehavior(window->Rect(), id, &hovered, &held, ImGuiButtonFlags_MouseButtonLeft); + if (held and held_prev and delta.x != 0.0f) + ImGui::SetScrollX(window, window->Scroll.x + delta.x); + if (held and held_prev and delta.y != 0.0f) + ImGui::SetScrollY(window, window->Scroll.y + delta.y); + + held_prev = held; +} + static void CenterTextH(const std::string & text) { float win_width = ImGui::GetWindowSize().x; @@ -95,7 +119,7 @@ static void InputText(const char * label, std::string & text, const ImVec2 & siz static void display_recentering_tip(imgui_context & ctx, const std::string & tip) { - ImGui::PushFont(ctx.large_font); + ImGui::PushFont(nullptr, constants::gui::font_size_large); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::window_padding); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 2); ImGui::SetNextWindowPos(ctx.layers()[3].vp_center(), ImGuiCond_Always, {0.5, 0.5}); @@ -138,59 +162,6 @@ std::string openxr_post_processing_flag_name(XrCompositionLayerSettingsFlagsFB f } } -void scenes::lobby::tooltip(std::string_view text) -{ - // FIXME: this is incorrect if we use the docking branch of imgui - ImGuiViewport * viewport = ImGui::GetMainViewport(); - auto & layer = imgui_ctx->layer(ImGui::GetMousePos()); - auto pos_backup = viewport->Pos; - auto size_backup = viewport->Size; - viewport->Pos = ImVec2(layer.vp_origin.x, layer.vp_origin.y); - viewport->Size = ImVec2(layer.vp_size.x, layer.vp_size.y); - - ImVec2 pos{ - (ImGui::GetItemRectMin().x + ImGui::GetItemRectMax().x) / 2, - ImGui::GetItemRectMin().y - constants::style::tooltip_distance, - }; - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::tooltip_padding); - ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::tooltip_rounding); - - // Clamp position to avoid overflowing on the right - auto & style = ImGui::GetStyle(); - const ImVec2 text_size = ImGui::CalcTextSize(text.data(), text.data() + text.size(), true); - const ImVec2 size = {text_size.x + style.WindowPadding.x * 2.0f, text_size.y + style.WindowPadding.y * 2.0f}; - pos.x = std::min(pos.x, viewport->Pos.x + viewport->Size.x - size.x / 2); - ImVec2 pivot = {0.5, 1}; - - // Move tooltip below the item if it overflows on the top - if (pos.y - size.y <= viewport->Pos.y) - { - pos.y = ImGui::GetItemRectMax().y + constants::style::tooltip_distance; - pivot.y = 0; - } - - ImGui::SetNextWindowPos(pos, ImGuiCond_Always, pivot); - if (ImGui::BeginTooltip()) - { - ImGui::PushStyleColor(ImGuiCol_Text, 0xffffffff); - ImGui::TextUnformatted(text.data(), text.data() + text.size()); - ImGui::PopStyleColor(); - ImGui::EndTooltip(); - } - - ImGui::PopStyleVar(2); - - viewport->Pos = pos_backup; - viewport->Size = size_backup; -} - -void scenes::lobby::vibrate_on_hover() -{ - if (ImGui::IsItemHovered()) - hovered_item = ImGui::GetItemID(); -} - void scenes::lobby::gui_connecting(locked_notifiable & pin_request) { using constants::style::button_size; @@ -200,12 +171,9 @@ void scenes::lobby::gui_connecting(locked_notifiable & pin_req std::string status; if (next_scene) { - if (next_scene->current_state() == scenes::stream::state::stalled) - status = _("Video stream interrupted"); - else if (server_name == "") - status = fmt::format(_F("Connection ready\nStart a VR application on your computer")); - else - status = fmt::format(_F("Connection ready\nStart a VR application on {}"), server_name); + current_tab = tab::connected; + ImGui::CloseCurrentPopup(); + return; } else if (async_session.valid()) status = async_session.get_progress(); @@ -222,7 +190,7 @@ void scenes::lobby::gui_connecting(locked_notifiable & pin_req ImGui::Dummy({1000, 1}); - ImGui::PushFont(imgui_ctx->large_font); + ImGui::PushFont(nullptr, constants::gui::font_size_large); if (server_name == "") CenterTextH(fmt::format(_F("Connection"))); else @@ -243,7 +211,7 @@ void scenes::lobby::gui_connecting(locked_notifiable & pin_req ImGui::CloseCurrentPopup(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } void scenes::lobby::gui_enter_pin(locked_notifiable & pin_request) @@ -251,7 +219,7 @@ void scenes::lobby::gui_enter_pin(locked_notifiable & pin_requ const int pin_size = 6; ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, constants::style::pin_entry_item_spacing); - ImGui::PushFont(imgui_ctx->large_font); + ImGui::PushFont(nullptr, constants::gui::font_size_large); const auto & style = ImGui::GetStyle(); const auto window = ImGui::GetCurrentWindow(); @@ -278,7 +246,7 @@ void scenes::lobby::gui_enter_pin(locked_notifiable & pin_requ ImGui::PopFont(); if (ImGui::IsItemHovered()) - tooltip(_("Input the PIN displayed on the dashboard")); + imgui_ctx->tooltip(_("Input the PIN displayed on the dashboard")); ImGui::BeginDisabled(pin_buffer.size() == pin_size); for (int i = 1; i <= 9;) @@ -288,7 +256,7 @@ void scenes::lobby::gui_enter_pin(locked_notifiable & pin_requ char button_text[] = {char('0' + i), 0}; if (ImGui::Button(button_text, constants::style::pin_entry_key_size)) pin_buffer += button_text; - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (j < 2) ImGui::SameLine(); @@ -307,20 +275,20 @@ void scenes::lobby::gui_enter_pin(locked_notifiable & pin_requ ImGui::CloseCurrentPopup(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::PopStyleColor(3); ImGui::SameLine(); if (ImGui::Button("0", constants::style::pin_entry_key_size)) pin_buffer += "0"; - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::EndDisabled(); ImGui::SameLine(); ImGui::BeginDisabled(pin_buffer.size() == 0); if (ImGui::Button(ICON_FA_DELETE_LEFT, constants::style::pin_entry_key_size)) pin_buffer.resize(pin_buffer.size() - 1); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::EndDisabled(); ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing @@ -331,7 +299,66 @@ void scenes::lobby::gui_enter_pin(locked_notifiable & pin_requ pin_request->pin_requested = false; pin_request.notify_one(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); +} + +void scenes::lobby::gui_connected() +{ + if (not next_scene) + { + current_tab = tab::server_list; + return; + } + + ImGui::PushFont(nullptr, constants::gui::font_size_large); + if (server_name.empty()) + CenterTextH(_("Connected to WiVRn server")); + else + CenterTextH(fmt::format(_F("Connected to {}"), server_name)); + ImGui::PopFont(); + + auto disconnect = _("Disconnect"); + auto disconnect_size = ImGui::CalcTextSize(disconnect.c_str()); + + auto apps = next_scene->get_applications(); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {20, 20}); + if (apps->applications.empty()) + { + CenterTextHV(_("Start an application on the server to start streaming.")); + } + else + { + ImGui::BeginChild("Main", ImGui::GetWindowSize() - ImGui::GetCursorPos() - ImVec2(0, disconnect_size.y + 80), 0); + if (server_name.empty()) + ImGui::Text("%s", _S("Start an application on your computer or select one to start streaming.")); + else + ImGui::Text("%s", fmt::format(_F("Start an application on {} or select one to start streaming."), server_name).c_str()); + for (const auto & app: apps->applications) + { + if (ImGui::Button(fmt::format(ICON_FA_PLAY "##{}", app.id).c_str())) + next_scene->start_application(app.id); + imgui_ctx->vibrate_on_hover(); + ImGui::SameLine(); + ImGui::Text("%s", app.name.c_str()); + } + ScrollWhenDraggingOnVoid(); + ImGui::EndChild(); + } + ImGui::PopStyleVar(); + + ImGui::SetCursorPosX(ImGui::GetWindowSize().x - disconnect_size.x - 50); + ImGui::SetCursorPosY(ImGui::GetWindowSize().y - disconnect_size.y - 50); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f)); + if (ImGui::Button(disconnect.c_str())) + { + next_scene.reset(); + current_tab = tab::server_list; + } + imgui_ctx->vibrate_on_hover(); + ImGui::PopStyleColor(3); } void scenes::lobby::gui_new_server() @@ -359,7 +386,7 @@ void scenes::lobby::gui_new_server() if (ImGui::IsWindowAppearing()) ImGui::SetKeyboardFocusHere(); InputText("##Name", add_server_window_prettyname, {ImGui::GetContentRegionAvail().x, 0}, 0); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::TableNextRow(); ImGui::TableNextColumn(); @@ -368,7 +395,7 @@ void scenes::lobby::gui_new_server() ImGui::TableNextColumn(); InputText("##Hostname", add_server_window_hostname, {ImGui::GetContentRegionAvail().x, 0}, 0); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::TableNextRow(); ImGui::TableNextColumn(); @@ -377,12 +404,12 @@ void scenes::lobby::gui_new_server() ImGui::TableNextColumn(); ImGui::InputInt("##Port", &add_server_window_port, 1, 1, ImGuiInputTextFlags_CharsDecimal); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::EndTable(); ImGui::Checkbox(_S("TCP only"), &add_server_tcp_only); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); auto top_left = ImGui::GetWindowContentRegionMin(); auto bottom_right = ImGui::GetWindowContentRegionMax(); @@ -398,7 +425,7 @@ void scenes::lobby::gui_new_server() add_server_cookie = ""; ImGui::CloseCurrentPopup(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SameLine(bottom_right.x - button_size.x); @@ -429,7 +456,7 @@ void scenes::lobby::gui_new_server() add_server_cookie = ""; ImGui::CloseCurrentPopup(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::PopStyleVar(4); // ImGuiStyleVar_FrameRounding, ImGuiStyleVar_ItemSpacing, ImGuiStyleVar_CellPadding, ImGuiStyleVar_FramePadding } @@ -453,7 +480,7 @@ void scenes::lobby::gui_server_list() std::string cookie_to_remove; if (sorted_cookies.empty()) { - ImGui::PushFont(imgui_ctx->large_font); + ImGui::PushFont(nullptr, constants::gui::font_size_large); ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 0.5)); CenterTextHV(_("Start a WiVRn server on your\nlocal network")); ImGui::PopStyleColor(); @@ -490,7 +517,7 @@ void scenes::lobby::gui_server_list() std::string label = _("Autoconnect") + "##" + cookie; if (ImGui::Checkbox(label.c_str(), &data.autoconnect)) config.save(); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } ImVec2 button_position(ImGui::GetWindowContentRegionMax().x, pos.y + (list_item_height - button_size.y) / 2); @@ -518,14 +545,14 @@ void scenes::lobby::gui_server_list() connect(data); ImGui::OpenPopup("connecting"); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { if (!data.compatible && !data.manual) - tooltip(_("Incompatible server version")); + imgui_ctx->tooltip(_("Incompatible server version")); else if (!data.visible && !data.manual) - tooltip(_("Server not available")); + imgui_ctx->tooltip(_("Server not available")); } ImGui::PopStyleColor(3); @@ -541,7 +568,7 @@ void scenes::lobby::gui_server_list() if (ImGui::Button((ICON_FA_TRASH_CAN "##remove-" + cookie).c_str(), icon_button_size)) cookie_to_remove = cookie; - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::PopStyleColor(3); button_position.x -= icon_button_size.x + style.WindowPadding.x + 10; @@ -555,7 +582,7 @@ void scenes::lobby::gui_server_list() add_server_tcp_only = data.service.tcp_only; ImGui::OpenPopup("add or edit server"); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } pos.y += 120; @@ -620,7 +647,7 @@ void scenes::lobby::gui_settings() config.save(); } if (ImGui::IsItemHovered()) - tooltip(_("Select refresh rate based on measured application performance.\nMay cause flicker when a change happens.")); + imgui_ctx->tooltip(_("Select refresh rate based on measured application performance.\nMay cause flicker when a change happens.")); for (float rate: refresh_rates) { if (ImGui::Selectable(fmt::format("{}", rate).c_str(), rate == config.preferred_refresh_rate, ImGuiSelectableFlags_SelectOnRelease)) @@ -632,7 +659,7 @@ void scenes::lobby::gui_settings() } ImGui::EndCombo(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (config.preferred_refresh_rate == 0 and refresh_rates.size() > 2) { @@ -649,7 +676,7 @@ void scenes::lobby::gui_settings() } ImGui::EndCombo(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } } } @@ -670,7 +697,7 @@ void scenes::lobby::gui_settings() config.resolution_scale = intScale * 0.01; config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (width * config.resolution_scale > stream_view.maxImageRectWidth or height * config.resolution_scale > stream_view.maxImageRectHeight) { ImGui::TextColored(ImColor(0xf9, 0x73, 0x06) /*orange*/, ICON_FA_TRIANGLE_EXCLAMATION); @@ -684,9 +711,8 @@ void scenes::lobby::gui_settings() if (ImGui::Checkbox(_S("Enable microphone"), &enabled)) { config.set_feature(feature::microphone, enabled); - config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } { ImGui::BeginDisabled(not config.check_feature(feature::microphone)); @@ -695,9 +721,9 @@ void scenes::lobby::gui_settings() { config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) - tooltip(_("Force disable audio filters, such as noise cancellation")); + imgui_ctx->tooltip(_("Force disable audio filters, such as noise cancellation")); ImGui::Unindent(); ImGui::EndDisabled(); } @@ -707,11 +733,10 @@ void scenes::lobby::gui_settings() if (ImGui::Checkbox(_S("Enable hand tracking"), &enabled)) { config.set_feature(feature::hand_tracking, enabled); - config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) and (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled)) - tooltip(_("This feature is not supported by your headset")); + imgui_ctx->tooltip(_("This feature is not supported by your headset")); ImGui::EndDisabled(); } { @@ -720,25 +745,23 @@ void scenes::lobby::gui_settings() if (ImGui::Checkbox(_S("Enable eye tracking"), &enabled)) { config.set_feature(feature::eye_gaze, enabled); - config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) and (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled)) - tooltip(_("This feature is not supported by your headset")); + imgui_ctx->tooltip(_("This feature is not supported by your headset")); ImGui::EndDisabled(); } { - ImGui::BeginDisabled(not(application::get_fb_face_tracking2_supported() or application::get_htc_face_tracking_eye_supported() or application::get_htc_face_tracking_lip_supported() or application::get_pico_face_tracking_supported())); + ImGui::BeginDisabled(not application::get_face_tracking_supported()); bool enabled = config.check_feature(feature::face_tracking); if (ImGui::Checkbox(_S("Enable face tracking"), &enabled)) { config.set_feature(feature::face_tracking, enabled); - config.save(); } ImGui::EndDisabled(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) and (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled)) - tooltip(_("This feature is not supported by your headset")); - vibrate_on_hover(); + imgui_ctx->tooltip(_("This feature is not supported by your headset")); + imgui_ctx->vibrate_on_hover(); } { @@ -747,28 +770,27 @@ void scenes::lobby::gui_settings() if (ImGui::Checkbox(_S("Enable body tracking"), &enabled)) { config.set_feature(feature::body_tracking, enabled); - config.save(); } ImGui::EndDisabled(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { if (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled) { - tooltip(_("This feature is not supported by your headset")); + imgui_ctx->tooltip(_("This feature is not supported by your headset")); } else { std::visit(utils::overloaded{ [](auto &) {}, [this](xr::fb_body_tracker &) { - tooltip(_("Requires 'Hand and body tracking' to be enabled in the Quest movement tracking settings,\notherwise body data will be guessed from controller and headset positions")); + imgui_ctx->tooltip(_("Requires 'Hand and body tracking' to be enabled in the Quest movement tracking settings,\notherwise body data will be guessed from controller and headset positions")); }, }, application::get_body_tracker()); } } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } if (std::holds_alternative(application::get_body_tracker())) { @@ -778,18 +800,18 @@ void scenes::lobby::gui_settings() { config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) - tooltip(_("Estimate lower body joint positions using Generative Legs\nRequires 'Hand and body tracking' to be enabled in the Quest movement tracking settings")); + imgui_ctx->tooltip(_("Estimate lower body joint positions using Generative Legs\nRequires 'Hand and body tracking' to be enabled in the Quest movement tracking settings")); ImGui::BeginDisabled(not config.fb_lower_body); if (ImGui::Checkbox(_S("Enable hip tracking"), &config.fb_hip)) { config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) - tooltip(_("Only takes affect with lower body tracking enabled\nMay be desired when using another source of hip tracking")); + imgui_ctx->tooltip(_("Only takes affect with lower body tracking enabled\nMay be desired when using another source of hip tracking")); ImGui::EndDisabled(); ImGui::Unindent(); @@ -802,72 +824,12 @@ void scenes::lobby::gui_settings() setup_passthrough(); config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) and (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled)) - tooltip(_("This feature is not supported by your headset")); + imgui_ctx->tooltip(_("This feature is not supported by your headset")); ImGui::EndDisabled(); - if (ImGui::Checkbox(_S("Show performance metrics"), &config.show_performance_metrics)) - config.save(); - vibrate_on_hover(); - if (ImGui::IsItemHovered()) - tooltip(_("Overlay can be toggled by pressing both thumbsticks")); - - ImGui::PopStyleVar(); - - if (config.show_performance_metrics) - { - float win_width = ImGui::GetWindowSize().x; - float win_height = ImGui::GetWindowSize().y; - - ImVec2 plot_size{ - win_width / 2 - style.ItemSpacing.x / 2, - win_height / 2}; - - static std::array cpu_time; - static std::array gpu_time; - static int offset = 0; - - float min_v = 0; - float max_v = 20; - - cpu_time[offset] = application::get_cpu_time().count() * 1.0e-6; - gpu_time[offset] = renderer->get_gpu_time() * 1'000; - offset = (offset + 1) % cpu_time.size(); - - ImPlot::PushStyleColor(ImPlotCol_PlotBg, IM_COL32(32, 32, 32, 64)); - ImPlot::PushStyleColor(ImPlotCol_FrameBg, IM_COL32(0, 0, 0, 0)); - ImPlot::PushStyleColor(ImPlotCol_AxisBg, IM_COL32(0, 0, 0, 0)); - ImPlot::PushStyleColor(ImPlotCol_AxisBgActive, IM_COL32(0, 0, 0, 0)); - ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, IM_COL32(0, 0, 0, 0)); - - if (ImPlot::BeginPlot(_S("CPU time"), plot_size, ImPlotFlags_CanvasOnly | ImPlotFlags_NoChild)) - { - auto col = ImPlot::GetColormapColor(0); - - ImPlot::SetupAxes(nullptr, _S("CPU time [ms]"), ImPlotAxisFlags_NoDecorations, 0); - ImPlot::SetupAxesLimits(0, cpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); - ImPlot::SetNextLineStyle(col); - ImPlot::SetNextFillStyle(col, 0.25); - ImPlot::PlotLine(_S("CPU time"), cpu_time.data(), cpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); - ImPlot::EndPlot(); - } - - ImGui::SameLine(); - - if (ImPlot::BeginPlot(_S("GPU time"), plot_size, ImPlotFlags_CanvasOnly | ImPlotFlags_NoChild)) - { - auto col = ImPlot::GetColormapColor(1); - - ImPlot::SetupAxes(nullptr, _S("GPU time [ms]"), ImPlotAxisFlags_NoDecorations, 0); - ImPlot::SetupAxesLimits(0, gpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); - ImPlot::SetNextLineStyle(col); - ImPlot::SetNextFillStyle(col, 0.25); - ImPlot::PlotLine(_S("GPU time"), gpu_time.data(), gpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); - ImPlot::EndPlot(); - } - ImPlot::PopStyleColor(5); - } + ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing } void scenes::lobby::gui_post_processing() @@ -895,14 +857,14 @@ void scenes::lobby::gui_post_processing() config.openxr_post_processing.super_sampling = option; config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } ImGui::EndCombo(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) { - tooltip(_("Reduce flicker for high contrast edges.\nUseful when the input resolution is high compared to the headset display")); + imgui_ctx->tooltip(_("Reduce flicker for high contrast edges.\nUseful when the input resolution is high compared to the headset display")); } } { @@ -920,14 +882,14 @@ void scenes::lobby::gui_post_processing() config.openxr_post_processing.sharpening = option; config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } ImGui::EndCombo(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) { - tooltip(_("Improve clarity of high contrast edges and counteract blur.\nUseful when the input resolution is low compared to the headset display")); + imgui_ctx->tooltip(_("Improve clarity of high contrast edges and counteract blur.\nUseful when the input resolution is low compared to the headset display")); } } ImGui::Unindent(); @@ -940,13 +902,13 @@ void scenes::lobby::gui_post_processing() { config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) { if (application::get_openxr_post_processing_supported()) - tooltip(_("On this headset, this setting has been fully superseded by the native Sharpening setting above.\nOnly enable if you know what you're doing.")); + imgui_ctx->tooltip(_("On this headset, this setting has been fully superseded by the native Sharpening setting above.\nOnly enable if you know what you're doing.")); else - tooltip(_("Client-side upscaling and sharpening, adds a performance cost on the headset")); + imgui_ctx->tooltip(_("Client-side upscaling and sharpening, adds a performance cost on the headset")); } if (application::get_openxr_post_processing_supported()) { @@ -974,7 +936,7 @@ void scenes::lobby::gui_post_processing() config.sgsr.upscaling_factor = intScale * 0.01; config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (width * current > stream_view.maxImageRectWidth or height * current > stream_view.maxImageRectHeight) { ImGui::TextColored(ImColor(0xf9, 0x73, 0x06) /*orange*/, ICON_FA_TRIANGLE_EXCLAMATION); @@ -987,9 +949,9 @@ void scenes::lobby::gui_post_processing() { config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) - tooltip(_("Adds an additional performance cost")); + imgui_ctx->tooltip(_("Adds an additional performance cost")); } { const float current = config.sgsr.edge_threshold; @@ -999,18 +961,18 @@ void scenes::lobby::gui_post_processing() config.sgsr.edge_threshold = float(intScale); config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) - tooltip(fmt::format(_F("Recommended: {:.1f}"), 4.0)); + imgui_ctx->tooltip(fmt::format(_F("Recommended: {:.1f}"), 4.0)); } { if (ImGui::SliderFloat(_S("Edge sharpness"), &config.sgsr.edge_sharpness, 1.0, 2.0, "%.2f")) { config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) - tooltip(fmt::format(_F("Recommended: {:.1f}"), 2.0)); + imgui_ctx->tooltip(fmt::format(_F("Recommended: {:.1f}"), 2.0)); } ImGui::Unindent(); ImGui::EndDisabled(); @@ -1027,55 +989,111 @@ void scenes::lobby::gui_debug() ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(20, 20)); ImGui::Checkbox("Display debug axes", &display_debug_axes); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (display_debug_axes) { ImGui::Checkbox("Display grip instead of aim", &display_grip_instead_of_aim); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); } ImGui::SetNextItemWidth(140); ImGui::DragFloat("##offset x", &offset_position.x, 0.0001); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SameLine(); ImGui::SetNextItemWidth(140); ImGui::DragFloat("##offset y", &offset_position.y, 0.0001); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SameLine(); ImGui::SetNextItemWidth(140); ImGui::DragFloat("Position", &offset_position.z, 0.0001); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SameLine(); if (ImGui::Button("Reset##position")) offset_position = {0, 0, 0}; - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SetNextItemWidth(140); ImGui::DragFloat("##offset roll", &offset_orientation.x, 0.01); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SameLine(); ImGui::SetNextItemWidth(140); ImGui::DragFloat("##offset pitch", &offset_orientation.y, 0.01); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SameLine(); ImGui::SetNextItemWidth(140); ImGui::DragFloat("Rotation", &offset_orientation.z, 0.01); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SameLine(); if (ImGui::Button("Reset##orientation")) offset_orientation = {0, 0, 0}; - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SetNextItemWidth(140); ImGui::DragFloat("Ray offset", &ray_offset, 0.0001); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); + + if (ImGui::Button("Delete configuration file")) + std::filesystem::remove(application::get_config_path() / "client.json"); + imgui_ctx->vibrate_on_hover(); + + float win_width = ImGui::GetWindowSize().x; + float win_height = ImGui::GetWindowSize().y; + + ImGuiStyle & style = ImGui::GetStyle(); + ImVec2 plot_size{ + win_width / 2 - style.ItemSpacing.x / 2, + win_height / 2}; + + static std::array cpu_time; + static std::array gpu_time; + static int offset = 0; + + float min_v = 0; + float max_v = 20; + + cpu_time[offset] = application::get_cpu_time().count() * 1.0e-6; + gpu_time[offset] = renderer->get_gpu_time() * 1'000; + offset = (offset + 1) % cpu_time.size(); + + ImPlot::PushStyleColor(ImPlotCol_PlotBg, IM_COL32(32, 32, 32, 64)); + ImPlot::PushStyleColor(ImPlotCol_FrameBg, IM_COL32(0, 0, 0, 0)); + ImPlot::PushStyleColor(ImPlotCol_AxisBg, IM_COL32(0, 0, 0, 0)); + ImPlot::PushStyleColor(ImPlotCol_AxisBgActive, IM_COL32(0, 0, 0, 0)); + ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, IM_COL32(0, 0, 0, 0)); + + if (ImPlot::BeginPlot(_S("CPU time"), plot_size, ImPlotFlags_CanvasOnly)) + { + auto col = ImPlot::GetColormapColor(0); + + ImPlot::SetupAxes(nullptr, _S("CPU time [ms]"), ImPlotAxisFlags_NoDecorations, 0); + ImPlot::SetupAxesLimits(0, cpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); + ImPlot::SetNextLineStyle(col); + ImPlot::SetNextFillStyle(col, 0.25); + ImPlot::PlotLine(_S("CPU time"), cpu_time.data(), cpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); + ImPlot::EndPlot(); + } + + ImGui::SameLine(); + + if (ImPlot::BeginPlot(_S("GPU time"), plot_size, ImPlotFlags_CanvasOnly)) + { + auto col = ImPlot::GetColormapColor(1); + + ImPlot::SetupAxes(nullptr, _S("GPU time [ms]"), ImPlotAxisFlags_NoDecorations, 0); + ImPlot::SetupAxesLimits(0, gpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); + ImPlot::SetNextLineStyle(col); + ImPlot::SetNextFillStyle(col, 0.25); + ImPlot::PlotLine(_S("GPU time"), gpu_time.data(), gpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); + ImPlot::EndPlot(); + } + ImPlot::PopStyleColor(5); ImGui::PopStyleVar(); } @@ -1083,7 +1101,7 @@ void scenes::lobby::gui_debug() void scenes::lobby::gui_about() { - ImGui::PushFont(imgui_ctx->large_font); + ImGui::PushFont(nullptr, constants::gui::font_size_large); CenterTextH(std::string("WiVRn ") + wivrn::git_version); ImGui::PopFont(); @@ -1098,9 +1116,95 @@ void scenes::lobby::gui_about() ImGui::PopFont(); } +void scenes::lobby::gui_first_run() +{ + float win_width = ImGui::GetWindowSize().x; + auto & config = application::get_config(); + const ImGuiStyle & style = ImGui::GetStyle(); + + struct item + { + feature f; + std::string text; + bool supported; + }; + + std::array optional_features{ + item{ + .f = feature::microphone, + .text = _S("Enable the microphone?"), + .supported = true, + }, + item{ + .f = feature::eye_gaze, + .text = _S("Enable eye tracking?"), + .supported = application::get_eye_gaze_supported(), + }, + item{ + .f = feature::face_tracking, + .text = _S("Enable face tracking?"), + .supported = application::get_face_tracking_supported(), + }, + item{ + .f = feature::body_tracking, + .text = _S("Enable body tracking?"), + .supported = application::get_body_tracking_supported(), + }, + }; + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {20, 40}); + + ImGui::PushFont(nullptr, constants::gui::font_size_large); + CenterTextH(_("Welcome to WiVRn")); + ImGui::PopFont(); + + while (optional_feature_index < optional_features.size() and + (not optional_features[optional_feature_index].supported or + config.check_feature(optional_features[optional_feature_index].f))) + + optional_feature_index++; + + if (optional_feature_index == optional_features.size()) + { + current_tab = tab::server_list; + config.first_run = false; + config.save(); + } + + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10); + + CenterTextH(optional_features[optional_feature_index].text); + + float button_width = constants::style::button_size.x; + float buttons_width = 2 * button_width + style.ItemSpacing.x; + ImGui::SetCursorPosX((win_width - buttons_width) / 2); + + if (ImGui::Button(_S("Yes"), constants::style::button_size)) + { + config.set_feature(optional_features[optional_feature_index].f, true); + } + imgui_ctx->vibrate_on_hover(); + + ImGui::SameLine(); + if (ImGui::Button(_S("No"), constants::style::button_size)) + { + config.set_feature(optional_features[optional_feature_index].f, false); + optional_feature_index++; + } + imgui_ctx->vibrate_on_hover(); + ImGui::PopStyleVar(2); // ImGuiStyleVar_ItemSpacing + + if (optional_feature_index == optional_features.size()) + { + current_tab = tab::server_list; + config.first_run = false; + config.save(); + } +} + void scenes::lobby::gui_licenses() { - ImGui::PushFont(imgui_ctx->large_font); + ImGui::PushFont(nullptr, constants::gui::font_size_large); ImGui::Text("%s", _("Licenses").c_str()); ImGui::PopFont(); @@ -1137,7 +1241,7 @@ void scenes::lobby::gui_licenses() } ImGui::EndCombo(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (license) ImGui::TextUnformatted((const char *)license->data(), (const char *)license->data() + license->size()); } @@ -1192,31 +1296,6 @@ static bool RadioButtonWithoutCheckBox(const std::string & label, T * v, T v_but return pressed; } -static void ScrollWhenDraggingOnVoid() -{ - ImVec2 delta{0.0f, -ImGui::GetIO().MouseDelta.y}; - - // https://github.com/ocornut/imgui/issues/3379#issuecomment-1678718752 - ImGuiContext & g = *ImGui::GetCurrentContext(); - ImGuiWindow * window = g.CurrentWindow; - bool hovered = false; - bool held = false; - static bool held_prev = false; - - // Don't drag for the first frame because the current controller might have just changed and have a large delta - - ImGuiID id = window->GetID("##scrolldraggingoverlay"); - ImGui::KeepAliveID(id); - if (g.HoveredId == 0) // If nothing hovered so far in the frame (not same as IsAnyItemHovered()!) - ImGui::ButtonBehavior(window->Rect(), id, &hovered, &held, ImGuiButtonFlags_MouseButtonLeft); - if (held and held_prev and delta.x != 0.0f) - ImGui::SetScrollX(window, window->Scroll.x + delta.x); - if (held and held_prev and delta.y != 0.0f) - ImGui::SetScrollY(window, window->Scroll.y + delta.y); - - held_prev = held; -} - static auto face_weights() { using weights = decltype(wivrn::from_headset::tracking::fb_face2{}.weights); @@ -1403,7 +1482,7 @@ static const char * get_face_icon(XrTime predicted_display_time) { static const auto w = face_weights(); wivrn::from_headset::tracking::fb_face2 expression; - application::get_fb_face_tracker2().get_weights(predicted_display_time, expression); + std::get(application::get_face_tracker()).get_weights(predicted_display_time, expression); if (not expression.is_valid) return ICON_FA_FACE_MEH; @@ -1467,24 +1546,16 @@ void scenes::lobby::draw_features_status(XrTime predicted_display_time) }); } - if (application::get_fb_face_tracking2_supported()) + if (application::get_face_tracking_supported()) { + const char * icon_enabled = std::holds_alternative(application::get_face_tracker()) + ? get_face_icon(predicted_display_time) + : ICON_FA_FACE_KISS_WINK_HEART; items.push_back({ .f = feature::face_tracking, .tooltip_enabled = _("Face tracking is enabled"), .tooltip_disabled = _("Face tracking is disabled"), - .icon_enabled = get_face_icon(predicted_display_time), - .icon_disabled = ICON_FA_FACE_MEH_BLANK, - }); - } - - if (application::get_htc_face_tracking_eye_supported() or application::get_htc_face_tracking_lip_supported() or application::get_pico_face_tracking_supported()) - { - items.push_back({ - .f = feature::face_tracking, - .tooltip_enabled = _("Face tracking is enabled"), - .tooltip_disabled = _("Face tracking is disabled"), - .icon_enabled = ICON_FA_FACE_KISS_WINK_HEART, + .icon_enabled = icon_enabled, .icon_disabled = ICON_FA_FACE_MEH_BLANK, }); } @@ -1512,7 +1583,7 @@ void scenes::lobby::draw_features_status(XrTime predicted_display_time) // New server button if (ImGui::Button(_S("Add server")) && !ImGui::IsPopupOpen("add or edit server")) ImGui::OpenPopup("add or edit server"); - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); ImGui::SameLine(); // Enabled features @@ -1529,12 +1600,11 @@ void scenes::lobby::draw_features_status(XrTime predicted_display_time) { // button doesn't alter the bool config.set_feature(i.f, not i.enabled); - config.save(); } - vibrate_on_hover(); + imgui_ctx->vibrate_on_hover(); if (ImGui::IsItemHovered()) - tooltip(i.enabled ? i.tooltip_enabled : i.tooltip_disabled); + imgui_ctx->tooltip(i.enabled ? i.tooltip_enabled : i.tooltip_disabled); if (i.icon_disabled == std::string_view(ICON_FA_SLASH) and not i.enabled) { @@ -1609,7 +1679,7 @@ void scenes::lobby::draw_features_status(XrTime predicted_display_time) void scenes::lobby::gui_keyboard() { - keyboard.display(hovered_item); + keyboard.display(*imgui_ctx); auto & config = application::get_config(); @@ -1647,44 +1717,62 @@ static bool is_gui_visible(imgui_context & ctx, XrTime predicted_display_time) std::vector> scenes::lobby::draw_gui(XrTime predicted_display_time) { - for (const auto & [key, server]: application::get_config().servers) - { - imgui_ctx->add_chars(server.service.name); - } - imgui_ctx->new_frame(predicted_display_time); ImGuiStyle & style = ImGui::GetStyle(); const float TabWidth = 300; - auto last_hovered = hovered_item; - hovered_item = 0; - if (ImGui::GetIO().WantTextInput) { ImGui::SetNextWindowPos(imgui_ctx->layers()[2].vp_center(), ImGuiCond_Always, {0.5, 0.5}); gui_keyboard(); } - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0, 0}); ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 30); ImGui::PushStyleColor(ImGuiCol_WindowBg, IM_COL32(8, 8, 8, 224)); ImGui::SetNextWindowPos(imgui_ctx->layers()[0].vp_center(), ImGuiCond_Always, {0.5, 0.5}); - ImGui::SetNextWindowSize({1400, 900}); - - ImGui::Begin("WiVRn", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); - - ImGui::SetCursorPos({TabWidth + 20, 0}); + if (current_tab == tab::first_run) { ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::window_padding * 2); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::window_rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, constants::style::window_border_size); + ImGui::Begin("WiVRn", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize); + gui_first_run(); + ImGui::End(); + ImGui::PopStyleVar(4); // ImGuiStyleVar_FrameRounding, ImGuiStyleVar_WindowPadding, ImGuiStyleVar_WindowRounding, ImGuiStyleVar_WindowBorderSize + } + else if (current_tab == tab::connected) + { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {20, 20}); - ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0)); + ImGui::SetNextWindowSize({1400, 900}); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 10}); + ImGui::Begin("WiVRn", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); + gui_connected(); + ImGui::End(); + ImGui::PopStyleVar(3); // ImGuiStyleVar_WindowPadding + } + else + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0, 0}); + ImGui::SetNextWindowSize({1400, 900}); + ImGui::Begin("WiVRn", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); + ImGui::SetCursorPos({TabWidth + 20, 0}); + + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {20, 20}); + ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0), 0); ImGui::SetCursorPosY(20); switch (current_tab) { + case tab::first_run: + case tab::connected: + __builtin_unreachable(); + case tab::server_list: ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 10}); draw_features_status(predicted_display_time); @@ -1731,59 +1819,54 @@ std::vector> scenes::lobby::draw_gui(XrTi ScrollWhenDraggingOnVoid(); ImGui::EndChild(); ImGui::PopStyleVar(2); // ImGuiStyleVar_FrameRounding, ImGuiStyleVar_WindowPadding - } - ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 255)); - ImGui::SetCursorPos(style.WindowPadding); - { - ImGui::BeginChild("Tabs", {TabWidth, ImGui::GetContentRegionMax().y - ImGui::GetWindowContentRegionMin().y}); + ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 255)); + ImGui::SetCursorPos(style.WindowPadding); + { + ImGui::BeginChild("Tabs", {TabWidth, ImGui::GetContentRegionMax().y - ImGui::GetWindowContentRegionMin().y}); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 10)); - RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " " + _("Server list"), ¤t_tab, tab::server_list, {TabWidth, 0}); - vibrate_on_hover(); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 10)); + RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " " + _("Server list"), ¤t_tab, tab::server_list, {TabWidth, 0}); + imgui_ctx->vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_GEARS " " + _("Settings"), ¤t_tab, tab::settings, {TabWidth, 0}); - vibrate_on_hover(); + RadioButtonWithoutCheckBox(ICON_FA_GEARS " " + _("Settings"), ¤t_tab, tab::settings, {TabWidth, 0}); + imgui_ctx->vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_WAND_MAGIC_SPARKLES " " + _("Post-processing"), ¤t_tab, tab::post_processing, {TabWidth, 0}); - vibrate_on_hover(); + RadioButtonWithoutCheckBox(ICON_FA_WAND_MAGIC_SPARKLES " " + _("Post-processing"), ¤t_tab, tab::post_processing, {TabWidth, 0}); + imgui_ctx->vibrate_on_hover(); #if WIVRN_CLIENT_DEBUG_MENU - RadioButtonWithoutCheckBox(ICON_FA_BUG_SLASH " " + _("Debug"), ¤t_tab, tab::debug, {TabWidth, 0}); - vibrate_on_hover(); + RadioButtonWithoutCheckBox(ICON_FA_BUG_SLASH " " + _("Debug"), ¤t_tab, tab::debug, {TabWidth, 0}); + imgui_ctx->vibrate_on_hover(); #endif - ImGui::SetCursorPosY(ImGui::GetContentRegionMax().y - 3 * ImGui::GetCurrentContext()->FontSize - 6 * style.FramePadding.y - 2 * style.ItemSpacing.y - style.WindowPadding.y); - RadioButtonWithoutCheckBox(ICON_FA_CIRCLE_INFO " " + _("About"), ¤t_tab, tab::about, {TabWidth, 0}); - vibrate_on_hover(); + ImGui::SetCursorPosY(ImGui::GetContentRegionMax().y - 3 * ImGui::GetCurrentContext()->FontSize - 6 * style.FramePadding.y - 2 * style.ItemSpacing.y - style.WindowPadding.y); + RadioButtonWithoutCheckBox(ICON_FA_CIRCLE_INFO " " + _("About"), ¤t_tab, tab::about, {TabWidth, 0}); + imgui_ctx->vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_SCALE_BALANCED " " + _("Licenses"), ¤t_tab, tab::licenses, {TabWidth, 0}); - vibrate_on_hover(); + RadioButtonWithoutCheckBox(ICON_FA_SCALE_BALANCED " " + _("Licenses"), ¤t_tab, tab::licenses, {TabWidth, 0}); + imgui_ctx->vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " " + _("Exit"), ¤t_tab, tab::exit, {TabWidth, 0}); - vibrate_on_hover(); + RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " " + _("Exit"), ¤t_tab, tab::exit, {TabWidth, 0}); + imgui_ctx->vibrate_on_hover(); - ImGui::PopStyleVar(); // ImGuiStyleVar_FramePadding - ImGui::EndChild(); + ImGui::PopStyleVar(); // ImGuiStyleVar_FramePadding + ImGui::EndChild(); + } + ImGui::PopStyleColor(); // ImGuiCol_ChildBg + ImGui::End(); + ImGui::PopStyleVar(); // ImGuiStyleVar_WindowPadding } - ImGui::PopStyleColor(); // ImGuiCol_ChildBg - ImGui::End(); + ImGui::PopStyleColor(); // ImGuiCol_WindowBg - ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_ScrollbarSize + ImGui::PopStyleVar(); // ImGuiStyleVar_ScrollbarSize if (not is_gui_visible(*imgui_ctx, predicted_display_time)) { if (application::get_hand_tracking_supported()) - display_recentering_tip(*imgui_ctx, _("Press A or X or put your palm up\nto move the main window")); + display_recentering_tip(*imgui_ctx, _("Press the grip button or put your palm up\nto move the main window")); else - display_recentering_tip(*imgui_ctx, _("Press A or X to move the main window")); - } - - if (hovered_item != last_hovered && hovered_item != 0) - { - size_t controller = imgui_ctx->get_focused_controller(); - if (controller < haptic_output.size()) - application::haptic_start(haptic_output[controller], XR_NULL_PATH, 10'000'000, 1000, 1); + display_recentering_tip(*imgui_ctx, _("Press the grip button to move the main window")); } #if WIVRN_CLIENT_DEBUG_MENU diff --git a/client/scenes/lobby_keyboard.cpp b/client/scenes/lobby_keyboard.cpp index 23f11433..6f1ca954 100644 --- a/client/scenes/lobby_keyboard.cpp +++ b/client/scenes/lobby_keyboard.cpp @@ -319,14 +319,14 @@ virtual_keyboard::key_status virtual_keyboard::button_behavior(const ImRect & bb float prev_held_duration = held_duration; held_duration += g.IO.DeltaTime; - if ((flags & ImGuiButtonFlags_Repeat) and held_duration > g.IO.KeyRepeatDelay) - { - int n1 = (prev_held_duration - g.IO.KeyRepeatDelay) / g.IO.KeyRepeatRate; - int n2 = (held_duration - g.IO.KeyRepeatDelay) / g.IO.KeyRepeatRate; - - if (n2 != n1) - pressed = true; - } + // if ((flags & ImGuiButtonFlags_Repeat) and held_duration > g.IO.KeyRepeatDelay) + // { + // int n1 = (prev_held_duration - g.IO.KeyRepeatDelay) / g.IO.KeyRepeatRate; + // int n2 = (held_duration - g.IO.KeyRepeatDelay) / g.IO.KeyRepeatRate; + // + // if (n2 != n1) + // pressed = true; + // } } else { @@ -381,8 +381,8 @@ virtual_keyboard::key_status virtual_keyboard::draw_single_key(const key & k, in ImGuiButtonFlags flags = ImGuiButtonFlags_None; - if (k.flag & key_flag_repeat) - flags |= ImGuiButtonFlags_Repeat; + // if (k.flag & key_flag_repeat) + // flags |= ImGuiButtonFlags_Repeat; auto status = button_behavior(bb, id, window_hovered, flags); @@ -462,7 +462,7 @@ void virtual_keyboard::press_single_key(const key & k) } } -void virtual_keyboard::display(ImGuiID & hovered_id) +void virtual_keyboard::display(imgui_context & ctx) { ImGuiStyle & style = ImGui::GetStyle(); @@ -534,7 +534,7 @@ void virtual_keyboard::display(ImGuiID & hovered_id) auto status = draw_single_key(key, id++, ImVec2{base_key_width * key.width - style.ItemSpacing.x, key_height}, window_hovered); if (status.hovered) - hovered_id = ImGui::GetItemID(); + ctx.set_hovered_item(); } key_position.x += base_key_width * key.width; diff --git a/client/scenes/lobby_keyboard.h b/client/scenes/lobby_keyboard.h index 0a91c9cd..28c96955 100644 --- a/client/scenes/lobby_keyboard.h +++ b/client/scenes/lobby_keyboard.h @@ -20,6 +20,7 @@ #pragma once #include "imgui.h" +#include "render/imgui_impl.h" #include #include @@ -80,7 +81,7 @@ private: bool symbols_shown = false; public: - void display(ImGuiID & hovered); + void display(imgui_context & ctx); const std::string_view get_layout() const; void set_layout(std::string_view layout_name); }; diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index e74954d3..ca66f181 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -16,10 +16,17 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +#include "constants.h" #include "utils/overloaded.h" #include "xr/fb_body_tracker.h" +#include "xr/fb_face_tracker2.h" #include "xr/htc_body_tracker.h" #include "xr/pico_body_tracker.h" +#include "xr/space.h" +#include +#include +#include +#include #define GLM_FORCE_RADIANS #include "stream.h" @@ -115,14 +122,39 @@ static const std::unordered_map device_ids = { {"/user/hand/right/input/trackpad/force", device_id::RIGHT_TRACKPAD_FORCE}, {"/user/hand/right/input/stylus/force", device_id::RIGHT_STYLUS_FORCE}, {"/user/hand/right/input/stylus_fb/force", device_id::RIGHT_STYLUS_FORCE}, + + // XR_EXT_hand_interaction + {"/user/hand/left/input/pinch_ext/value", device_id::LEFT_PINCH_VALUE}, + {"/user/hand/left/input/pinch_ext/ready_ext", device_id::LEFT_PINCH_READY}, + {"/user/hand/left/input/aim_activate_ext/value",device_id::LEFT_AIM_ACTIVATE_VALUE}, + {"/user/hand/left/input/aim_activate_ext/ready_ext",device_id::LEFT_AIM_ACTIVATE_READY}, + {"/user/hand/left/input/grasp_ext/value", device_id::LEFT_GRASP_VALUE}, + {"/user/hand/left/input/grasp_ext/ready_ext", device_id::LEFT_GRASP_READY}, + + {"/user/hand/right/input/pinch_ext/value", device_id::RIGHT_PINCH_VALUE}, + {"/user/hand/right/input/pinch_ext/ready_ext", device_id::RIGHT_PINCH_READY}, + {"/user/hand/right/input/aim_activate_ext/value",device_id::RIGHT_AIM_ACTIVATE_VALUE}, + {"/user/hand/right/input/aim_activate_ext/ready_ext",device_id::RIGHT_AIM_ACTIVATE_READY}, + {"/user/hand/right/input/grasp_ext/value", device_id::RIGHT_GRASP_VALUE}, + {"/user/hand/right/input/grasp_ext/ready_ext", device_id::RIGHT_GRASP_READY}, }; // clang-format on -static const std::array supported_formats = { +static const std::array supported_color_formats = { vk::Format::eR8G8B8A8Srgb, vk::Format::eB8G8R8A8Srgb, }; +static const std::array supported_depth_formats{ + vk::Format::eD32Sfloat, + vk::Format::eX8D24UnormPack32, +}; + +scenes::stream::stream() : + scene_impl(supported_color_formats, supported_depth_formats) +{ +} + static from_headset::visibility_mask_changed::masks get_visibility_mask(xr::instance & inst, xr::session & session, int view) { assert(inst.has_extension(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME)); @@ -219,12 +251,21 @@ std::shared_ptr scenes::stream::create(std::unique_ptr scenes::stream::create(std::unique_ptrnetwork_session->send_control(from_headset::visibility_mask_changed{ - .data = get_visibility_mask(self->instance, self->session, view), - .view_index = view}); + try + { + self->network_session->send_control(from_headset::visibility_mask_changed{ + .data = get_visibility_mask(self->instance, self->session, view), + .view_index = view}); + } + catch (std::exception & e) + { + spdlog::warn("Failed to get visibility mask: ", e.what()); + } } } + { + const auto & info = application::get_messages_info(); + self->network_session->send_control(from_headset::get_application_list{ + .language = info.language, + .country = info.country, + .variant = info.variant, + }); + } + + { + const auto & config = application::get_config(); + self->override_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({ @@ -308,25 +379,6 @@ std::shared_ptr scenes::stream::create(std::unique_ptrinput_actions.emplace_back(it->second, action, action_type); } - self->swapchain_format = vk::Format::eUndefined; - spdlog::info("Supported swapchain formats:"); - - for (auto format: self->session.get_swapchain_formats()) - { - spdlog::info(" {}", vk::to_string(format)); - } - for (auto format: self->session.get_swapchain_formats()) - { - if (std::find(supported_formats.begin(), supported_formats.end(), format) != supported_formats.end()) - { - self->swapchain_format = format; - break; - } - } - - if (self->swapchain_format == vk::Format::eUndefined) - throw std::runtime_error("No supported swapchain format"); - spdlog::info("Using format {}", vk::to_string(self->swapchain_format)); self->query_pool = vk::raii::QueryPool( @@ -342,42 +394,107 @@ std::shared_ptr scenes::stream::create(std::unique_ptrget_default_material()); + + std::string profile = controller_name(); + input.emplace( + *this, + "controllers/" + profile + "/profile.json", + layer_controllers, + layer_rays); + + spdlog::info("Loaded input profile {}", input->id); + + for (auto i: {xr::spaces::aim_left, xr::spaces::aim_right, xr::spaces::grip_left, xr::spaces::grip_right}) { - swapchain_imgui = xr::swapchain( - session, - device, - swapchain_format, - 1500, - 1000); + auto [p, q] = input->offset[i] = controller_offset(controller_name(), i); - imgui_context::viewport vp{ - .space = xr::spaces::view, - .position = {0, 0, -1}, - .orientation = {1, 0, 0, 0}, - .size = {1.0, 0.6666}, - .vp_origin = {0, 0}, - .vp_size = {1500, 1000}, - }; - - imgui_ctx.emplace(physical_device, - device, - queue_family_index, - queue, - std::span{}, - swapchain_imgui, - std::vector{vp}); - - plots_toggle_1 = get_action("plots_toggle_1").first; - plots_toggle_2 = get_action("plots_toggle_2").first; + auto rot = glm::degrees(glm::eulerAngles(q)); + spdlog::info("Initializing offset of space {} to ({}, {}, {}) mm, ({}, {}, {})°", + magic_enum::enum_name(i), + 1000 * p.x, + 1000 * p.y, + 1000 * p.z, + rot.x, + rot.y, + rot.z); } + std::array imgui_inputs{ + imgui_context::controller{ + .aim = get_action_space("left_aim"), + .offset = input->offset[xr::spaces::aim_left], + .trigger = get_action("left_trigger").first, + .squeeze = get_action("left_squeeze").first, + .scroll = get_action("left_scroll").first, + .haptic_output = get_action("left_haptic").first, + }, + imgui_context::controller{ + .aim = get_action_space("right_aim"), + .offset = input->offset[xr::spaces::aim_right], + .trigger = get_action("right_trigger").first, + .squeeze = get_action("right_squeeze").first, + .scroll = get_action("right_scroll").first, + .haptic_output = get_action("right_haptic").first, + }, + }; + + swapchain_imgui = xr::swapchain( + session, + device, + swapchain_format, + 1800, + 1000); + + imgui_context::viewport vp{ + .space = xr::spaces::world, + // Position and orientation are set at each frame + .size = {1.2, 0.6666}, + .vp_origin = {0, 0}, + .vp_size = {1800, 1000}, + }; + + imgui_ctx.emplace(physical_device, + device, + queue_family_index, + queue, + imgui_inputs, + swapchain_imgui, + std::vector{vp}); + + plots_toggle_1 = get_action("plots_toggle_1").first; + plots_toggle_2 = get_action("plots_toggle_2").first; + recenter_left = get_action("recenter_left").first; + recenter_right = get_action("recenter_right").first; + foveation_pitch = get_action("foveation_pitch").first; + foveation_distance = get_action("foveation_distance").first; + foveation_ok = get_action("foveation_ok").first; + foveation_cancel = get_action("foveation_cancel").first; + assert(video_stream_description); - setup_reprojection_swapchain(); + std::unique_lock lock(decoder_mutex); + setup_reprojection_swapchain( + video_stream_description->defoveated_width / view_count, + video_stream_description->defoveated_height); } void scenes::stream::on_unfocused() { + renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets + world.clear(); // Must be cleared before the renderer so that the descriptor sets are freed before their pools + input.reset(); + loader.reset(); + renderer.reset(); + clear_swapchains(); + imgui_ctx.reset(); swapchain_imgui = xr::swapchain(); } @@ -549,6 +666,78 @@ std::shared_ptr scenes::stream::accumulator_imag return nullptr; } +void scenes::stream::update_gui_position(xr::spaces controller) +{ + auto aim = application::locate_controller( + application::space(controller), + application::space(xr::spaces::view), + predicted_display_time); + + if (not aim) + return; + + auto [offset_position, offset_orientation] = input->offset[controller]; + + auto head_controller_position = aim->first + glm::mat3_cast(aim->second * offset_orientation) * offset_position; + auto head_controller_orientation = aim->second * offset_orientation; + auto head_controller_direction = -glm::column(glm::mat3_cast(head_controller_orientation), 2); + + if (not recentering_context) + { + // First frame of recentering: get the GUI position relative to the controller + + // Compute the intersection of the ray with the GUI + auto gui_controller_direction = glm::conjugate(head_gui_orientation) * head_controller_direction; + auto gui_controller_position = glm::conjugate(head_gui_orientation) * (head_controller_position - head_gui_position); + + float lambda = -gui_controller_position.z / gui_controller_direction.z; + auto gui_intersection = gui_controller_position + lambda * gui_controller_direction; + + auto viewport_size = imgui_ctx->layers()[0].size; + if (std::isnan(lambda) or lambda < 0 or + std::abs(gui_intersection.x) > viewport_size.x / 2 or + std::abs(gui_intersection.y) > viewport_size.y / 2) + { + // Reset the relative GUI position if the ray does not intersect + recentering_context.emplace(controller, glm::vec3{0, 0, -1}, glm::quat{1, 0, 0, 0}); + } + else + { + glm::vec3 controller_gui_position = glm::conjugate(head_controller_orientation) * (head_gui_position - head_controller_position); + glm::quat controller_gui_orientation = glm::conjugate(head_controller_orientation) * head_gui_orientation; + + recentering_context.emplace(controller, controller_gui_position, controller_gui_orientation); + } + } + else + { + // Subsequent frames of recentering: keep the GUI locked to the controller + auto [_, controller_gui_position, controller_gui_orientation] = *recentering_context; + + head_gui_position = head_controller_position + head_controller_orientation * controller_gui_position; + head_gui_orientation = head_controller_orientation * controller_gui_orientation; + } +} + +bool scenes::stream::is_gui_interactable() const +{ + switch (gui_status) + { + case gui_status::stats: + case gui_status::settings: + case gui_status::foveation_settings: + return true; + + case gui_status::hidden: + case gui_status::overlay_only: + case gui_status::compact: + return false; + } + + assert(false); + __builtin_unreachable(); +} + void scenes::stream::render(const XrFrameState & frame_state) { if (exiting) @@ -737,8 +926,6 @@ void scenes::stream::render(const XrFrameState & frame_state) session.begin_frame(); - int image_index = swapchain.acquire(); - swapchain.wait(); std::array image_indices; command_buffer.reset(); @@ -878,15 +1065,43 @@ void scenes::stream::render(const XrFrameState & frame_state) command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1); - // defoveate the image - auto extents = reprojector->reproject(command_buffer, foveation, image_index); - for (size_t i = 0; i < view_count; ++i) + XrExtent2Di extents[view_count]; { - extents[i] = { - .width = std::min(extents[i].width, swapchain.width()), - .height = std::min(extents[i].height, swapchain.height()), - }; + int32_t max_width = 0; + int32_t max_height = 0; + for (size_t i = 0; i < view_count; ++i) + { + extents[i] = reprojector->defoveated_size(foveation[i]); + max_width = std::max(max_width, extents[i].width); + max_height = std::max(max_height, extents[i].height); + } + // If the defoveated image is larger than the swapchain, try to reallocate one + if (swapchain.width() < max_width or swapchain.height() < max_height) + { + 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()); + } + } + } } + // defoveate the image + int image_index = swapchain.acquire(); + swapchain.wait(); + reprojector->reproject(command_buffer, foveation, image_index); command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 2); @@ -894,31 +1109,18 @@ void scenes::stream::render(const XrFrameState & frame_state) vk::SubmitInfo submit_info; submit_info.setCommandBuffers(*command_buffer); queue.submit(submit_info, *fence); + swapchain.release(); - XrEnvironmentBlendMode blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; - std::vector layers_base; std::vector layer_view(view_count); if (use_alpha) - { session.enable_passthrough(system); - std::visit( - utils::overloaded{ - [&](std::monostate &) { - assert(false); - }, - [&](xr::passthrough_alpha_blend & p) { - blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND; - }, - [&](auto & p) { - layers_base.push_back(p.layer()); - }}, - session.get_passthrough()); - } else session.disable_passthrough(); - swapchain.release(); + render_start(use_alpha, frame_state.predictedDisplayTime); + + // Add the layer with the streamed content for (uint32_t view = 0; view < view_count; view++) { layer_view[view] = @@ -937,45 +1139,47 @@ void scenes::stream::render(const XrFrameState & frame_state) }, }; } + add_projection_layer( + XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + application::space(xr::spaces::world), + std::move(layer_view)); - XrCompositionLayerProjection layer{ - .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION, - .layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, - .space = application::space(xr::spaces::world), - .viewCount = (uint32_t)layer_view.size(), - .views = layer_view.data(), - }; - - XrCompositionLayerSettingsFB settings; - const configuration::openxr_post_processing_settings openxr_post_processing = application::get_config().openxr_post_processing; - if ((openxr_post_processing.sharpening | openxr_post_processing.super_sampling) > 0) + if (composition_layer_color_scale_bias_supported) { - settings = { - .type = XR_TYPE_COMPOSITION_LAYER_SETTINGS_FB, - .layerFlags = openxr_post_processing.sharpening | openxr_post_processing.super_sampling, - }; - layer.next = &settings; + switch (gui_status) + { + case gui_status::hidden: + case gui_status::foveation_settings: + case gui_status::compact: + case gui_status::overlay_only: + dimming = dimming - frame_state.predictedDisplayPeriod / (1e9 * constants::stream::fade_duration); + break; + case gui_status::stats: + case gui_status::settings: + dimming = dimming + frame_state.predictedDisplayPeriod / (1e9 * constants::stream::fade_duration); + break; + } + + dimming = std::clamp(dimming, 0, 1); + float x = dimming * dimming * (3 - 2 * dimming); // Easing function + + float scale = std::lerp(1, constants::stream::dimming_scale, x); + float bias = std::lerp(0, constants::stream::dimming_bias, x); + + set_color_scale_bias({scale, scale, scale, 1}, {bias, bias, bias, 0}); } - std::vector imgui_layers; - if (imgui_ctx) - { - accumulate_metrics(frame_state.predictedDisplayTime, current_blit_handles, timestamps); - if (plots_visible) - imgui_layers = plot_performance_metrics(frame_state.predictedDisplayTime); - } + if (const configuration::openxr_post_processing_settings openxr_post_processing = application::get_config().openxr_post_processing; + (openxr_post_processing.sharpening | openxr_post_processing.super_sampling) > 0) + set_layer_settings(openxr_post_processing.sharpening | openxr_post_processing.super_sampling); - layers_base.push_back(reinterpret_cast(&layer)); + accumulate_metrics(frame_state.predictedDisplayTime, current_blit_handles, timestamps); - if (imgui_ctx and plots_visible) - { - for (auto & layer: imgui_layers) - layers_base.push_back(reinterpret_cast(&layer)); - } + draw_gui(frame_state.predictedDisplayTime, frame_state.predictedDisplayPeriod); try { - session.end_frame(frame_state.predictedDisplayTime, layers_base, blend_mode); + render_end(); } catch (std::system_error & e) { @@ -1031,7 +1235,22 @@ void scenes::stream::render(const XrFrameState & frame_state) CHECK_XR(xrGetActionStateBoolean(session, &get_info, &state_2)); if (state_1.currentState and state_2.currentState and (state_1.changedSinceLastSync or state_2.changedSinceLastSync)) - plots_visible = not plots_visible; + { + switch (gui_status) + { + case gui_status::hidden: + case gui_status::compact: + case gui_status::overlay_only: + gui_status = gui_status::stats; + break; + + case gui_status::stats: + case gui_status::settings: + case gui_status::foveation_settings: + gui_status = gui_status::hidden; + break; + } + } } query_pool_filled = true; @@ -1173,16 +1392,13 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript } } -void scenes::stream::setup_reprojection_swapchain() +void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint32_t swapchain_height) { - std::unique_lock lock(decoder_mutex); device.waitIdle(); session.set_refresh_rate(video_stream_description->fps); const uint32_t video_width = video_stream_description->width / view_count; const uint32_t video_height = video_stream_description->height; - uint32_t swapchain_width = video_stream_description->defoveated_width / view_count; - uint32_t swapchain_height = video_stream_description->defoveated_height; const configuration::sgsr_settings sgsr = application::get_config().sgsr; if (sgsr.enabled) @@ -1225,40 +1441,68 @@ scene::meta & scenes::stream::get_meta_scene() static meta m{ .name = "Stream", .actions = { + {"left_aim", XR_ACTION_TYPE_POSE_INPUT}, + {"left_trigger", XR_ACTION_TYPE_FLOAT_INPUT}, + {"left_squeeze", XR_ACTION_TYPE_FLOAT_INPUT}, + {"left_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT}, + {"left_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, + {"right_aim", XR_ACTION_TYPE_POSE_INPUT}, + {"right_trigger", XR_ACTION_TYPE_FLOAT_INPUT}, + {"right_squeeze", XR_ACTION_TYPE_FLOAT_INPUT}, + {"right_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT}, + {"right_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, + {"plots_toggle_1", XR_ACTION_TYPE_BOOLEAN_INPUT}, {"plots_toggle_2", XR_ACTION_TYPE_BOOLEAN_INPUT}, + + {"recenter_left", XR_ACTION_TYPE_BOOLEAN_INPUT}, + {"recenter_right", XR_ACTION_TYPE_BOOLEAN_INPUT}, + + {"foveation_pitch", XR_ACTION_TYPE_FLOAT_INPUT}, + {"foveation_distance", XR_ACTION_TYPE_FLOAT_INPUT}, + {"foveation_ok", XR_ACTION_TYPE_BOOLEAN_INPUT}, + {"foveation_cancel", XR_ACTION_TYPE_BOOLEAN_INPUT}, }, .bindings = { suggested_binding{ - "/interaction_profiles/oculus/touch_controller", { + "/interaction_profiles/oculus/touch_controller", + "/interaction_profiles/facebook/touch_controller_pro", + "/interaction_profiles/meta/touch_pro_controller", + "/interaction_profiles/meta/touch_controller_plus", + "/interaction_profiles/meta/touch_plus_controller", + "/interaction_profiles/bytedance/pico_neo3_controller", + "/interaction_profiles/bytedance/pico4_controller", + "/interaction_profiles/bytedance/pico4s_controller", + "/interaction_profiles/htc/vive_focus3_controller", + }, + { + {"left_aim", "/user/hand/left/input/aim/pose"}, + {"left_trigger", "/user/hand/left/input/trigger/value"}, + {"left_squeeze", "/user/hand/left/input/squeeze/value"}, + {"left_scroll", "/user/hand/left/input/thumbstick"}, + {"left_haptic", "/user/hand/left/output/haptic"}, + {"right_aim", "/user/hand/right/input/aim/pose"}, + {"right_trigger", "/user/hand/right/input/trigger/value"}, + {"right_squeeze", "/user/hand/right/input/squeeze/value"}, + {"right_scroll", "/user/hand/right/input/thumbstick"}, + {"right_haptic", "/user/hand/right/output/haptic"}, + + {"recenter_left", "/user/hand/left/input/squeeze/value"}, + {"recenter_right", "/user/hand/right/input/squeeze/value"}, + {"foveation_pitch", "/user/hand/right/input/thumbstick/y"}, + {"foveation_distance", "/user/hand/left/input/thumbstick/y"}, + {"foveation_ok", "/user/hand/right/input/a/click"}, + {"foveation_cancel", "/user/hand/right/input/b/click"}, + {"plots_toggle_1", "/user/hand/left/input/thumbstick/click"}, {"plots_toggle_2", "/user/hand/right/input/thumbstick/click"}, }, }, suggested_binding{ - "/interaction_profiles/bytedance/pico_neo3_controller", { - {"plots_toggle_1", "/user/hand/left/input/thumbstick/click"}, - {"plots_toggle_2", "/user/hand/right/input/thumbstick/click"}, + "/interaction_profiles/khr/simple_controller", }, - }, - suggested_binding{ - "/interaction_profiles/bytedance/pico4_controller", - { - {"plots_toggle_1", "/user/hand/left/input/thumbstick/click"}, - {"plots_toggle_2", "/user/hand/right/input/thumbstick/click"}, - }, - }, - suggested_binding{ - "/interaction_profiles/htc/vive_focus3_controller", - { - {"plots_toggle_1", "/user/hand/left/input/thumbstick/click"}, - {"plots_toggle_2", "/user/hand/right/input/thumbstick/click"}, - }, - }, - suggested_binding{ - "/interaction_profiles/khr/simple_controller", {}, }, }, @@ -1287,6 +1531,22 @@ void scenes::stream::on_xr_event(const xr::event & event) .view_index = uint8_t(event.visibility_mask_changed.viewIndex), }); break; + case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: + // Override session state if the GUI is interactable + if (event.state_changed.state == XR_SESSION_STATE_FOCUSED and is_gui_interactable()) + network_session->send_control(from_headset::session_state_changed{ + .state = XR_SESSION_STATE_VISIBLE, + }); + else + network_session->send_control(from_headset::session_state_changed{ + .state = event.state_changed.state, + }); + break; + case XR_TYPE_EVENT_DATA_USER_PRESENCE_CHANGED_EXT: + network_session->send_control(from_headset::user_presence_changed{ + .present = (bool)event.user_presence_changed.isUserPresent, + }); + break; case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: on_interaction_profile_changed(event.interaction_profile_changed); break; diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 2f3bc860..6f506ab7 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -23,11 +23,13 @@ #include "decoder/shard_accumulator.h" #include "render/imgui_impl.h" #include "scene.h" +#include "scenes/input_profile.h" #include "stream_reprojection.h" +#include "utils/thread_safe.h" #include "wifi_lock.h" #include "wivrn_client.h" #include "wivrn_packets.h" -#include "xr/passthrough.h" +#include "xr/space.h" #include #include #include @@ -104,8 +106,6 @@ private: std::optional reprojector; - std::optional passthrough; - vk::raii::Fence fence = nullptr; vk::raii::CommandBuffer command_buffer = nullptr; @@ -122,19 +122,63 @@ private: xr::swapchain swapchain; xr::swapchain swapchain_imgui; - vk::Format swapchain_format; std::optional