diff --git a/CMakeLists.txt b/CMakeLists.txt index d021b179..2f7c4411 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -126,6 +126,7 @@ FetchContent_Declare(openxr_loader URL https://github.com/KhronosGroup/OpenXR-SD FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/refs/tags/v1.11.0.tar.gz) FetchContent_Declare(stb URL https://github.com/nothings/stb/archive/refs/heads/master.zip) FetchContent_Declare(libktx URL https://github.com/KhronosGroup/KTX-Software/archive/refs/tags/v4.3.0.tar.gz) +FetchContent_Declare(implot URL https://github.com/epezent/implot/archive/refs/tags/v0.16.tar.gz) # Server dependencies FetchContent_Declare(monado diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 3e68b137..a67ef0f4 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -5,7 +5,7 @@ set(KTX_FEATURE_VK_UPLOAD ON) set(KTX_FEATURE_GL_UPLOAD OFF) set(KTX_FEATURE_LOADTEST_APPS OFF) -FetchContent_MakeAvailable(spdlog glm fastgltf imgui stb libktx) +FetchContent_MakeAvailable(spdlog glm fastgltf imgui stb libktx implot) include(FreetypeHarfbuzz) include(CompileGLSL) @@ -85,13 +85,16 @@ target_sources(wivrn PRIVATE ${imgui_SOURCE_DIR}/imgui_demo.cpp ${imgui_SOURCE_DIR}/misc/freetype/imgui_freetype.cpp ${imgui_SOURCE_DIR}/backends/imgui_impl_vulkan.cpp + ${implot_SOURCE_DIR}/implot.cpp + ${implot_SOURCE_DIR}/implot_items.cpp ) target_include_directories(wivrn PRIVATE ${imgui_SOURCE_DIR}) +target_include_directories(wivrn PRIVATE ${implot_SOURCE_DIR}) # target_compile_definitions(wivrn PRIVATE "IMGUI_USER_CONFIG=\"render/imgui_config.h\"") target_compile_definitions(wivrn PRIVATE IMGUI_USE_WCHAR32) target_compile_definitions(wivrn PRIVATE IMGUI_ENABLE_FREETYPE) -target_compile_definitions(wivrn PRIVATE IMGUI_DISABLE_OBSOLETE_FUNCTIONS) +# target_compile_definitions(wivrn PRIVATE IMGUI_DISABLE_OBSOLETE_FUNCTIONS) # incompatible with implot # target_compile_definitions(wivrn PRIVATE IMGUI_ENABLE_FREETYPE_LUNASVG) target_compile_definitions(wivrn PRIVATE IMGUI_DEFINE_MATH_OPERATORS) diff --git a/client/application.cpp b/client/application.cpp index 86810fa6..f76df4cf 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -501,6 +501,7 @@ void application::initialize_vulkan() #endif vk_physical_device = xr_system_id.physical_device(vk_instance); + physical_device_properties = vk_physical_device.getProperties(); spdlog::info("Available Vulkan device extensions:"); for(vk::ExtensionProperties & i: vk_physical_device.enumerateDeviceExtensionProperties()) @@ -826,6 +827,21 @@ void application::initialize() vk_cmdpool = vk::raii::CommandPool{vk_device, cmdpool_create_info}; + // Create timestamp queries + query_pool = vk::raii::QueryPool(vk_device, vk::QueryPoolCreateInfo{.queryType = vk::QueryType::eTimestamp, .queryCount = 6}); + query_command_buffers = vk_device.allocateCommandBuffers(vk::CommandBufferAllocateInfo{.commandPool = *vk_cmdpool, .commandBufferCount = 6}); + for(int i = 0; i < 6; i+=2) + { + query_command_buffers[i].begin({}); + query_command_buffers[i].resetQueryPool(*query_pool, i, 2); + query_command_buffers[i].writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, *query_pool, i); + query_command_buffers[i].end(); + + query_command_buffers[i+1].begin({}); + query_command_buffers[i+1].writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, i+1); + query_command_buffers[i+1].end(); + } + initialize_actions(); interaction_profile_changed(); @@ -1026,7 +1042,6 @@ void application::loop() } else { - auto scene = current_scene(); if (scene) { @@ -1041,7 +1056,31 @@ void application::loop() last_scene = scene; } - scene->render(); + XrFrameState framestate = xr_session.wait_frame(); + + auto t1 = std::chrono::steady_clock::now(); + + vk_queue.submit(vk::SubmitInfo{ + .commandBufferCount = 1, + .pCommandBuffers = &*query_command_buffers[(current_query%3) * 2], + }, nullptr); + + scene->render(framestate.predictedDisplayTime, framestate.shouldRender); + + last_scene_cpu_time = std::chrono::steady_clock::now() - t1; + + vk_queue.submit(vk::SubmitInfo{ + .commandBufferCount = 1, + .pCommandBuffers = &*query_command_buffers[(current_query%3) * 2 + 1], + }, nullptr); + + current_query = current_query + 1; + if (current_query > 3) + { + auto [res, timestamps] = query_pool.getResults((current_query%3)*2, 2, 2 * sizeof(uint64_t), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); + if (res == vk::Result::eSuccess) + last_scene_gpu_time = std::chrono::nanoseconds((int)((timestamps[1] - timestamps[0]) * physical_device_properties.limits.timestampPeriod)); + } } else { diff --git a/client/application.h b/client/application.h index 6e9d59eb..20be2d2b 100644 --- a/client/application.h +++ b/client/application.h @@ -19,6 +19,7 @@ #pragma once +#include #ifdef __ANDROID__ #include #endif @@ -89,10 +90,16 @@ class application : public singleton vk::raii::Queue vk_queue = nullptr; vk::raii::CommandPool vk_cmdpool = nullptr; vk::raii::PipelineCache pipeline_cache = nullptr; + vk::PhysicalDeviceProperties physical_device_properties; // Vulkan memory allocator stuff std::optional allocator; + // Timestamp queries + vk::raii::QueryPool query_pool = nullptr; + std::vector query_command_buffers; + int current_query = 0; + // OpenXR stuff void initialize_actions(); @@ -124,6 +131,8 @@ class application : public singleton std::mutex scene_stack_lock; std::vector> scene_stack; std::weak_ptr last_scene; + std::chrono::nanoseconds last_scene_cpu_time; + std::chrono::nanoseconds last_scene_gpu_time; void loop(); @@ -355,9 +364,18 @@ public: return instance().config_path; } - static const std::filesystem::path& get_cache_path() { return instance().cache_path; } + + static std::chrono::nanoseconds get_cpu_time() + { + return instance().last_scene_cpu_time; + } + + static std::chrono::nanoseconds get_gpu_time() + { + return instance().last_scene_gpu_time; + } }; diff --git a/client/main.cpp b/client/main.cpp index a90b9ce8..926b6687 100644 --- a/client/main.cpp +++ b/client/main.cpp @@ -103,7 +103,7 @@ void real_main() freeaddrinfo(addresses); if (not session) throw std::runtime_error("Unable to connect to " + server_address + ":" + std::to_string(port)); - app.push_scene(scenes::stream::create(std::move(session))); + app.push_scene(scenes::stream::create(std::move(session), false)); } app.run(); diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index 56418cbb..1b4db955 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -18,6 +18,7 @@ #include "imgui_impl.h" +#include "implot.h" #include "application.h" #include "asset.h" @@ -224,6 +225,7 @@ imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii: scale_(size.x, size.y), swapchain(swapchain), context(ImGui::CreateContext()), + plot_context(ImPlot::CreateContext()), io((ImGui::SetCurrentContext(context), ImGui::GetIO())), world(world) { @@ -260,6 +262,7 @@ imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii: }; ImGui::SetCurrentContext(context); + ImPlot::SetCurrentContext(plot_context); ImGui_ImplVulkan_Init(&init_info, *renderpass); // Load Fonts @@ -299,6 +302,7 @@ imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii: void imgui_context::new_frame(XrTime display_time) { ImGui::SetCurrentContext(context); + ImPlot::SetCurrentContext(plot_context); if (last_display_time) io.DeltaTime = std::min((display_time - last_display_time) * 1e-9f, 0.1f); @@ -447,18 +451,20 @@ void imgui_context::new_frame(XrTime display_time) draw_list->AddCircleFilled(*position, radius, button_pressed ? color_pressed : color_unpressed); draw_list->AddCircle(*position, radius*1.2, ImGui::GetColorU32(ImVec4(0, 0, 0, alpha)), 0, radius * 0.4); } + + image_index = swapchain.acquire(); + swapchain.wait(); } -void imgui_context::render(vk::Image destination) +XrCompositionLayerQuad imgui_context::end_frame() { + vk::Image destination = swapchain.images()[image_index].image; + swapchain.release(); + ImGui::SetCurrentContext(context); + ImPlot::SetCurrentContext(plot_context); ImGui::Render(); - ImDrawData* draw_data = ImGui::GetDrawData(); - const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); - - if (is_minimized) - return; current_command_buffer = (current_command_buffer + 1) % command_buffers.size(); @@ -483,7 +489,7 @@ void imgui_context::render(vk::Image destination) .pClearValues = &clear }, vk::SubpassContents::eInline); - ImGui_ImplVulkan_RenderDrawData(draw_data, *cb); + ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), *cb); cb.endRenderPass(); @@ -494,13 +500,26 @@ void imgui_context::render(vk::Image destination) .pCommandBuffers = &*cb, }, *fence); - // Use the aliasing constructor - // return std::shared_ptr{viewport, &vp.frames[vp.frameindex].image_view_texture}; + return XrCompositionLayerQuad{ + .type = XR_TYPE_COMPOSITION_LAYER_QUAD, + .layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + .space = world, + .eyeVisibility = XrEyeVisibility::XR_EYE_VISIBILITY_BOTH, + .subImage = { + .swapchain = swapchain, + .imageRect = { + .offset = {0, 0}, + .extent = {(int32_t)size.width, (int32_t)size.height}}, + }, + .pose = pose(), + .size = scale(), + }; } imgui_context::~imgui_context() { ImGui::SetCurrentContext(context); + ImPlot::SetCurrentContext(plot_context); std::vector fences; @@ -515,6 +534,7 @@ imgui_context::~imgui_context() device.waitForFences(fences, true, 1'000'000'000); ImGui_ImplVulkan_Shutdown(); + ImPlot::DestroyContext(); ImGui::DestroyContext(context); } @@ -546,12 +566,13 @@ ImTextureID imgui_context::load_texture(const std::string& filename, vk::raii::S device.updateDescriptorSets(ds_write, nullptr); - ImTextureID id = ds.release(); + ImTextureID id = *ds; textures.emplace(id, texture_data{ .sampler = std::move(sampler), .image = std::move(loader.image), - .image_view = std::move(loader.image_view) + .image_view = std::move(loader.image_view), + .descriptor_set = std::move(ds), }); return id; @@ -570,5 +591,10 @@ ImTextureID imgui_context::load_texture(const std::string& filename) void imgui_context::free_texture(ImTextureID texture) { textures.erase(texture); - // TODO free descriptor set +} + +void imgui_context::set_current() +{ + ImGui::SetCurrentContext(context); + ImPlot::SetCurrentContext(plot_context); } diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h index 9aea7769..fd22b0fc 100644 --- a/client/render/imgui_impl.h +++ b/client/render/imgui_impl.h @@ -20,6 +20,7 @@ #include "xr/swapchain.h" #include +#include #include #include #include @@ -43,6 +44,7 @@ class imgui_context vk::raii::Sampler sampler; std::shared_ptr image; vk::raii::ImageView image_view; + vk::raii::DescriptorSet descriptor_set; }; public: @@ -111,8 +113,10 @@ private: glm::vec2 scale_; xr::swapchain& swapchain; + int image_index; ImGuiContext * context; + ImPlotContext * plot_context; ImGuiIO& io; std::vector> controllers; @@ -134,24 +138,6 @@ public: orientation_ = orientation; } - XrCompositionLayerQuad composition_layer(XrSwapchain swapchain) const - { - return XrCompositionLayerQuad{ - .type = XR_TYPE_COMPOSITION_LAYER_QUAD, - .layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, - .space = world, - .eyeVisibility = XrEyeVisibility::XR_EYE_VISIBILITY_BOTH, - .subImage = { - .swapchain = swapchain, - .imageRect = { - .offset = {0, 0}, - .extent = {(int32_t)size.width, (int32_t)size.height}}, - }, - .pose = pose(), - .size = scale(), - }; - } - XrPosef pose() const { return XrPosef{ @@ -195,8 +181,7 @@ public: } void new_frame(XrTime display_time); - - void render(vk::Image destination); + XrCompositionLayerQuad end_frame(); ImFont * large_font; size_t get_focused_controller() const @@ -207,4 +192,5 @@ public: ImTextureID load_texture(const std::string& filename, vk::raii::Sampler&& sampler); ImTextureID load_texture(const std::string& filename); void free_texture(ImTextureID); + void set_current(); }; diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index e09ec39a..06c72d7e 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -171,11 +171,6 @@ scene_renderer::scene_renderer(vk::raii::Device & device, vk::raii::PhysicalDevi { res.fence = device.createFence({.flags = vk::FenceCreateFlagBits::eSignaled}); res.cb = std::move(cb); - - res.query_pool = vk::raii::QueryPool(device, vk::QueryPoolCreateInfo{ - .queryType = vk::QueryType::eTimestamp, - .queryCount = 2, - }); } renderpass = create_renderpass(); @@ -544,17 +539,12 @@ void scene_renderer::start_frame() current_frame_index = (current_frame_index + 1) % frame_resources.size(); auto& f = current_frame(); - f.cpu_time_start = std::chrono::steady_clock::now(); - device.waitForFences(*f.fence, true, 1'000'000'000); device.resetFences(*f.fence); f.resources.clear(); f.cb.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); - f.cb.resetQueryPool(*f.query_pool, 0, 2); - f.cb.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, *f.query_pool, 0); - // TODO: replace with vector and write to GPU in end_frame() f.staging_buffer_offset = 0; if (!f.staging_buffer) @@ -574,20 +564,12 @@ void scene_renderer::end_frame() { auto& f = current_frame(); - f.cb.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *f.query_pool, 1); f.cb.end(); queue.submit(vk::SubmitInfo{ .commandBufferCount = 1, .pCommandBuffers = &*f.cb, }, *f.fence); - - auto cpu_time_stop = std::chrono::steady_clock::now(); - spdlog::info("scene_renderer::render: CPU time: {} us", std::chrono::duration_cast(cpu_time_stop - f.cpu_time_start).count()); - - auto [res, timestamps] = f.query_pool.getResults(0, 2, 2 * sizeof(uint64_t), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); - if (res == vk::Result::eSuccess) - spdlog::info("scene_renderer::render: GPU time: {} us", (int)((timestamps[1] - timestamps[0]) * physical_device_properties.limits.timestampPeriod * 1.0e-3)); } scene_renderer::per_frame_resources & scene_renderer::current_frame() diff --git a/client/render/scene_renderer.h b/client/render/scene_renderer.h index 2050ea7f..7877b89f 100644 --- a/client/render/scene_renderer.h +++ b/client/render/scene_renderer.h @@ -151,7 +151,6 @@ public: { vk::raii::Fence fence = nullptr; vk::raii::CommandBuffer cb = nullptr; - vk::raii::QueryPool query_pool = nullptr; std::vector> resources; // Uniform buffer for per-view and per-instance data @@ -161,8 +160,6 @@ public: // device local // buffer_allocation uniform_buffer; - - std::chrono::steady_clock::time_point cpu_time_start; }; std::vector frame_resources; diff --git a/client/scene.cpp b/client/scene.cpp index 1c11d8e5..fa7bc34f 100644 --- a/client/scene.cpp +++ b/client/scene.cpp @@ -32,6 +32,7 @@ scene::scene(key, const meta& current_meta) : system(application::instance().xr_system_id), session(application::instance().xr_session), world_space(application::instance().world_space), + view_space(application::instance().view_space), viewconfig(application::instance().app_info.viewconfig), vk_instance(application::instance().vk_instance), diff --git a/client/scene.h b/client/scene.h index 8e1eb4ab..5db4c449 100644 --- a/client/scene.h +++ b/client/scene.h @@ -73,6 +73,7 @@ protected: xr::system & system; xr::session & session; xr::space & world_space; + xr::space & view_space; XrViewConfigurationType viewconfig; vk::raii::Instance& vk_instance; @@ -99,7 +100,7 @@ public: virtual ~scene(); - virtual void render() = 0; + virtual void render(XrTime predicted_display_time, bool should_render) = 0; virtual void on_unfocused(); virtual void on_focused(); virtual void on_interaction_profile_changed(); diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index 7b16b715..80e5a293 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -207,11 +207,16 @@ scenes::lobby::lobby() }; servers.emplace(data.service.txt["cookie"], data); } + + auto json_show_plots = root["show_performance_metrics"]; + if (json_show_plots.is_bool()) + show_performance_metrics = json_show_plots.get_bool(); } catch(std::exception& e) { spdlog::warn("Cannot read configuration: {}", e.what()); servers.clear(); + show_performance_metrics = false; } spdlog::info("{} known server(s):", servers.size()); @@ -270,7 +275,9 @@ void scenes::lobby::save_config() std::ofstream json(application::get_config_path() / "client.json"); - json << "{\"servers\":[" << servers_str << "]}"; + json << "{\"servers\":[" << servers_str << "]," + << "\"show_performance_metrics\":" << std::boolalpha << show_performance_metrics + << "}"; } static std::string ip_address_to_string(const in_addr& addr) @@ -478,7 +485,7 @@ static std::vector render_layer(std::vectorset_current(); if (!async_session.valid() && !next_scene && !ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopup)) { for(auto&& [cookie, data]: servers) @@ -519,24 +527,21 @@ void scenes::lobby::render() } } - XrFrameState framestate = session.wait_frame(); - - if (!framestate.shouldRender) + if (!should_render) { - spdlog::debug("framestate.shouldRender is false"); session.begin_frame(); - session.end_frame(framestate.predictedDisplayTime, {}); + session.end_frame(predicted_display_time, {}); return; } session.begin_frame(); - auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space); + auto [flags, views] = session.locate_views(viewconfig, predicted_display_time, world_space); assert(views.size() == swapchains_lobby.size()); - input->apply(world_space, framestate.predictedDisplayTime); + input->apply(world_space, predicted_display_time); - XrCompositionLayerQuad imgui_layer = draw_gui(framestate.predictedDisplayTime); + XrCompositionLayerQuad imgui_layer = draw_gui(predicted_display_time); assert(renderer); renderer->start_frame(); @@ -572,7 +577,7 @@ void scenes::lobby::render() layers_base.push_back(reinterpret_cast(&imgui_layer)); layers_base.push_back(reinterpret_cast(&controllers_layer)); - session.end_frame(framestate.predictedDisplayTime, layers_base); + session.end_frame(predicted_display_time, layers_base); } void scenes::lobby::on_focused() diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index 3237031f..98381279 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -81,7 +81,7 @@ class lobby : public scene_impl std::array haptic_output; std::string selected_item; - std::string hovered_item; + ImGuiID hovered_item; std::vector swapchains_lobby; std::vector swapchains_controllers; @@ -110,6 +110,8 @@ class lobby : public scene_impl tab last_current_tab = tab::server_list; ImTextureID about_picture; + bool show_performance_metrics = false; + void gui_connecting(); void gui_server_list(); void gui_add_server(); @@ -117,13 +119,15 @@ class lobby : public scene_impl void gui_about(); void gui_keyboard(ImVec2 size); + void vibrate_on_hover(); + void connect(server_data& data); public: virtual ~lobby(); lobby(); - void render() override; + void render(XrTime predicted_display_time, bool should_render) override; void render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index); void on_unfocused() override; diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index 6271a1e0..a6aae762 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -19,13 +19,14 @@ #include "application.h" #include "imgui.h" +#include "implot.h" #include "imgui_internal.h" #include "lobby.h" #include "version.h" #include #include -#include "../external/IconsFontAwesome6.h" +#include "IconsFontAwesome6.h" static void CenterTextH(const std::string& text) { @@ -58,6 +59,12 @@ static void CenterTextHV(const std::string& text) ImGui::PopStyleVar(); } +void scenes::lobby::vibrate_on_hover() +{ + if (ImGui::IsItemHovered()) + hovered_item = ImGui::GetItemID(); +} + void scenes::lobby::gui_connecting() { const ImVec2 button_size(220, 80); @@ -97,13 +104,11 @@ void scenes::lobby::gui_connecting() ImGui::CloseCurrentPopup(); } - if (ImGui::IsItemHovered()) - hovered_item = "close"; + vibrate_on_hover(); } void scenes::lobby::gui_add_server() { - const ImVec2 button_size(220, 80); // TODO column widths @@ -116,8 +121,7 @@ void scenes::lobby::gui_add_server() static char buf[100]; ImGui::TableNextColumn(); ImGui::InputText("##Name", buf, sizeof(buf)); - if (ImGui::IsItemHovered()) - hovered_item = "name"; + vibrate_on_hover(); ImGui::TableNextRow(); ImGui::TableNextColumn(); @@ -126,8 +130,7 @@ void scenes::lobby::gui_add_server() static char buf2[100]; ImGui::TableNextColumn(); ImGui::InputText("##Hostname", buf2, sizeof(buf2)); - if (ImGui::IsItemHovered()) - hovered_item = "hostname"; + vibrate_on_hover(); ImGui::TableNextRow(); ImGui::TableNextColumn(); @@ -136,8 +139,7 @@ void scenes::lobby::gui_add_server() static int port; ImGui::TableNextColumn(); ImGui::InputInt("##Port", &port); - if (ImGui::IsItemHovered()) - hovered_item = "port"; + vibrate_on_hover(); ImGui::EndTable(); @@ -154,8 +156,7 @@ void scenes::lobby::gui_add_server() ImGui::SetCursorPosX(top_left.x); if (ImGui::Button("Cancel", button_size)) current_tab = tab::server_list; - if (ImGui::IsItemHovered()) - hovered_item = "cancel"; + vibrate_on_hover(); ImGui::SameLine(bottom_right.x - button_size.x); @@ -176,8 +177,7 @@ void scenes::lobby::gui_add_server() save_config(); } - if (ImGui::IsItemHovered()) - hovered_item = "save"; + vibrate_on_hover(); } void scenes::lobby::gui_server_list() @@ -230,8 +230,7 @@ void scenes::lobby::gui_server_list() ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0,1,0,1)); if (ImGui::Checkbox(("Autoconnect##" + cookie).c_str(), &data.autoconnect)) save_config(); - if (ImGui::IsItemHovered()) - hovered_item = "autoconnect " + cookie; + vibrate_on_hover(); ImGui::PopStyleColor(); } @@ -265,9 +264,7 @@ void scenes::lobby::gui_server_list() connect(data); ImGui::OpenPopup("connecting"); } - - if (ImGui::IsItemHovered()) - hovered_item = "connect " + cookie; + vibrate_on_hover(); ImGui::PopStyleColor(3); ImGui::EndDisabled(); @@ -282,9 +279,7 @@ void scenes::lobby::gui_server_list() if (ImGui::Button(("Remove##" + cookie).c_str(), button_size)) cookie_to_remove = cookie; - - if (ImGui::IsItemHovered()) - hovered_item = "remove " + cookie; + vibrate_on_hover(); ImGui::PopStyleColor(3); } @@ -317,6 +312,72 @@ void scenes::lobby::gui_server_list() ImGui::PopStyleVar(3); } +void scenes::lobby::gui_settings() +{ + ImGuiStyle & style = ImGui::GetStyle(); + + if (ImGui::Checkbox("Show performance metrics", &show_performance_metrics)) + save_config(); + vibrate_on_hover(); + + if (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] = application::get_gpu_time().count() * 1.0e-6; + 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("CPU time", plot_size, ImPlotFlags_CanvasOnly|ImPlotFlags_NoChild)) + { + auto col = ImPlot::GetColormapColor(0); + + ImPlot::SetupAxes(nullptr, "CPU time", 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("CPU time", cpu_time.data(), cpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); + ImPlot::EndPlot(); + } + + ImGui::SameLine(); + + if (ImPlot::BeginPlot("GPU time", plot_size, ImPlotFlags_CanvasOnly|ImPlotFlags_NoChild)) + { + auto col = ImPlot::GetColormapColor(1); + + ImPlot::SetupAxes(nullptr,"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("GPU time", gpu_time.data(), gpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); + ImPlot::EndPlot(); + } + ImPlot::PopStyleColor(5); + } +} + void scenes::lobby::gui_about() { ImGui::PushFont(imgui_ctx->large_font); @@ -408,9 +469,6 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) const float MinTabWidth = 300; const float MaxTabWidth = 300; - int image_index = swapchain_imgui.acquire(); - swapchain_imgui.wait(); - std::optional> head_position = application::locate_controller(application::view(), world_space, predicted_display_time); if (head_position) @@ -419,7 +477,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) } auto last_hovered = hovered_item; - hovered_item = ""; + hovered_item = 0; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0, 0}); ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 30); @@ -452,6 +510,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) break; case tab::settings: + gui_settings(); break; case tab::about: @@ -486,16 +545,18 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10,10)); RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " Server list", ¤t_tab, tab::server_list, {TabWidth, 0}); - if (ImGui::IsItemHovered()) - hovered_item = "Server list"; + vibrate_on_hover(); + + RadioButtonWithoutCheckBox(ICON_FA_GEARS " Settings", ¤t_tab, tab::settings, {TabWidth, 0}); + vibrate_on_hover(); ImGui::SetCursorPosY(ImGui::GetContentRegionMax().y - 2*ImGui::GetCurrentContext()->FontSize - 4*style.FramePadding.y - style.ItemSpacing.y - style.WindowPadding.y); RadioButtonWithoutCheckBox(ICON_FA_CIRCLE_INFO " About", ¤t_tab, tab::about, {TabWidth, 0}); - if (ImGui::IsItemHovered()) - hovered_item = "about"; + vibrate_on_hover(); + RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " Exit", ¤t_tab, tab::exit, {TabWidth, 0}); - if (ImGui::IsItemHovered()) - hovered_item = "exit"; + vibrate_on_hover(); + if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) { @@ -513,16 +574,12 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) ImGui::PopStyleColor(); // ImGuiCol_WindowBg ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_ScrollbarSize - if (hovered_item != last_hovered && hovered_item != "") + 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); } - - imgui_ctx->render(swapchain_imgui.images()[image_index].image); - swapchain_imgui.release(); - - return imgui_ctx->composition_layer(swapchain_imgui); + return imgui_ctx->end_frame(); } diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 2a0fb156..ac43baa3 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -17,8 +17,6 @@ * along with this program. If not, see . */ -#include -#include #include #define GLM_FORCE_RADIANS @@ -38,6 +36,7 @@ #include #include "audio/audio.h" #include "hardware.h" +#include "implot.h" using namespace xrt::drivers::wivrn; @@ -70,13 +69,19 @@ static const std::unordered_map device_ids = { }; // clang-format on -std::shared_ptr scenes::stream::create(std::unique_ptr network_session) +static const std::array supported_formats = +{ + vk::Format::eR8G8B8A8Srgb, + vk::Format::eB8G8R8A8Srgb +}; + +std::shared_ptr scenes::stream::create(std::unique_ptr network_session, bool show_performance_metrics) { std::shared_ptr self{new stream}; spdlog::info("decoder_mutex.native_handle() = {}", (void*)self->decoder_mutex.native_handle()); - self->network_session = std::move(network_session); + self->show_performance_metrics = show_performance_metrics; from_headset::headset_info_packet info{}; @@ -137,9 +142,59 @@ 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)); + return self; } +void scenes::stream::on_focused() +{ + if (show_performance_metrics) + { + swapchain_imgui = xr::swapchain( + session, + device, + swapchain_format, + 1500, 1000); + + imgui_ctx.emplace(physical_device, + device, + queue_family_index, + queue, + view_space, + std::span{}, + swapchain_imgui, + glm::vec2{1.0, 0.6666}); + + imgui_ctx->set_position({0,0,-1}, {1,0,0,0}); + } +} + +void scenes::stream::on_unfocused() +{ + imgui_ctx.reset(); + swapchain_imgui.reset(); +} + scenes::stream::~stream() { exit(); @@ -234,21 +289,169 @@ std::shared_ptr scenes::stream::accumulator_imag return nullptr; } -void scenes::stream::render() +scenes::stream::metric scenes::stream::get_metrics(XrTime predicted_display_time) +{ + uint64_t rx = network_session->bytes_received(); + uint64_t tx = network_session->bytes_sent(); + + float dt = (predicted_display_time - last_metric_time) * 1e-9f; + float bandwidth_rx = float(rx - bytes_received) / dt; + float bandwidth_tx = float(tx - bytes_sent ) /dt; + last_metric_time = predicted_display_time; + bytes_received = rx; + bytes_sent = tx; + + return metric{ + .cpu_time = application::get_cpu_time().count() * 1e-9f, + .gpu_time = application::get_gpu_time().count() * 1e-9f, + .bandwidth_rx = bandwidth_rx * 8, + .bandwidth_tx = bandwidth_tx * 8, + }; +} + +static float compute_plot_max_value(float * data, int count, ptrdiff_t stride) +{ + float max = 0; + uintptr_t ptr = (uintptr_t)data; + for(int i = 0; i < count; i++) + { + max = std::max(max, *(float*)(ptr + i * stride)); + } + + // First power of 10 less than the max + float x = pow(10, floor(log10(max))); + return ceil(max / x) * x; +} + +static std::pair compute_plot_unit(float max_value) +{ + if (max_value > 1e9) + return { 1e-9, "G" }; + if (max_value > 1e6) + return { 1e-6, "M" }; + if (max_value > 1e3) + return { 1e-3, "k" }; + if (max_value > 1) + return { 1, "" }; + if (max_value > 1e-3) + return { 1e3, "m" }; + if (max_value > 1e-6) + return { 1e6, "u" }; + return { 1e9, "n" }; +} + +struct getter_data +{ + uintptr_t data; + int stride; + int offset; + int count; + float multiplier; +}; + +static ImPlotPoint getter(int index, void * data_) +{ + getter_data& data = *(getter_data*)data_; + + int offset_index = (index + data.offset) % data.count; + + return ImPlotPoint(index, *(float*)(data.data + offset_index * data.stride) * data.multiplier); +} + +XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted_display_time) +{ + imgui_ctx->new_frame(predicted_display_time); + const ImGuiStyle & style = ImGui::GetStyle(); + + ImGui::SetNextWindowPos({0, 0}); + ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size); + ImGui::Begin("Performance metrics", nullptr, + ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove); + + ImVec2 window_size = ImGui::GetWindowSize() - ImVec2(2,2) * style.WindowPadding; + + metrics[metrics_offset] = get_metrics(predicted_display_time); + metrics_offset = (metrics_offset + 1) % metrics.size(); + + static const std::array plots = { + std::make_tuple(ImPlot::GetColormapColor(0), "CPU time", "s", &metric::cpu_time), + std::make_tuple(ImPlot::GetColormapColor(1), "GPU time", "s", &metric::gpu_time), + std::make_tuple(ImPlot::GetColormapColor(2), "Download", "bit/s", &metric::bandwidth_rx), + std::make_tuple(ImPlot::GetColormapColor(3), "Upload", "bit/s", &metric::bandwidth_tx), + }; + + axis_scale.resize(plots.size()); + + int n_cols = 2; + int n_rows = ceil((float)plots.size() / n_cols); + + ImVec2 plot_size = ImVec2( + window_size.x / n_cols - style.ItemSpacing.x * (n_cols-1) / n_cols, + window_size.y / n_rows - style.ItemSpacing.y * (n_rows-1) / n_rows); + + 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)); + + int n = 0; + for(auto [color, title, unit, data]: plots) + { + if (ImPlot::BeginPlot(title, plot_size, ImPlotFlags_CanvasOnly|ImPlotFlags_NoChild)) + { + float min_v = 0; + float max_v = compute_plot_max_value(&(metrics.data()->*data), metrics.size(), sizeof(metric)); + auto [ multiplier, prefix ] = compute_plot_unit(max_v); + + if (axis_scale[n] == 0) + axis_scale[n] = max_v; + else + axis_scale[n] = 0.99 * axis_scale[n] + 0.01 * max_v; + + getter_data gdata{ + .data = (uintptr_t)&(metrics.data()->*data), + .stride = sizeof(metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = multiplier + }; + + std::string title_with_units = std::string(title) + " [" + prefix + unit + "]"; + ImPlot::SetupAxes(nullptr, title_with_units.c_str(), ImPlotAxisFlags_NoDecorations, 0); + ImPlot::SetupAxesLimits(0, metrics.size() - 1, min_v * multiplier, axis_scale[n] * multiplier, ImGuiCond_Always); + ImPlot::SetNextLineStyle(color); + ImPlot::SetNextFillStyle(color, 0.25); + ImPlot::PlotLineG(title, getter, &gdata, metrics.size(), ImPlotLineFlags_Shaded); + // ImPlot::PlotLine(title, &(metrics.data()->*data), metrics.size(), 1, 0, ImPlotLineFlags_Shaded, metrics_offset, sizeof(metric)); + ImPlot::EndPlot(); + } + + if (++n % 2 != 0) + ImGui::SameLine(); + } + + ImPlot::PopStyleColor(5); + ImGui::End(); + + return imgui_ctx->end_frame(); +} + +void scenes::stream::render(XrTime predicted_display_time, bool should_render) { if (exiting) application::pop_scene(); - XrFrameState framestate = session.wait_frame(); - if (decoders.empty()) - framestate.shouldRender = false; + should_render = false; - if (!framestate.shouldRender) + if (!should_render) { // TODO: stop/restart video stream session.begin_frame(); - session.end_frame(framestate.predictedDisplayTime, {}); + session.end_frame(predicted_display_time, {}); std::unique_lock lock(decoder_mutex); for (auto & i: decoders) @@ -262,7 +465,7 @@ void scenes::stream::render() session.begin_frame(); - auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space); + auto [flags, views] = session.locate_views(viewconfig, predicted_display_time, world_space); assert(views.size() == swapchains.size()); std::array image_indices; @@ -326,7 +529,7 @@ void scenes::stream::render() current_blit_handles.push_back(blit_handle); blit_handle->feedback.blitted = application::now(); - blit_handle->feedback.displayed = framestate.predictedDisplayTime; + blit_handle->feedback.displayed = predicted_display_time; blit_handle->feedback.real_pose[0] = views[0].pose; blit_handle->feedback.real_pose[1] = views[1].pose; @@ -392,7 +595,7 @@ void scenes::stream::render() layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height(); } - float brightness = std::clamp(dbrightness * (framestate.predictedDisplayTime - first_frame_time) / 1.e9, 0, 1); + float brightness = std::clamp(dbrightness * (predicted_display_time - first_frame_time) / 1.e9, 0, 1); XrCompositionLayerColorScaleBiasKHR color_scale_bias{ .type = XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR, @@ -410,8 +613,16 @@ void scenes::stream::render() if (instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME)) layer.next = &color_scale_bias; + XrCompositionLayerQuad imgui_layer; + if (imgui_ctx) + imgui_layer = plot_performance_metrics(predicted_display_time); + layers_base.push_back(reinterpret_cast(&layer)); - session.end_frame(/*timestamp*/ framestate.predictedDisplayTime, layers_base); + + if (imgui_ctx) + layers_base.push_back(reinterpret_cast(&imgui_layer)); + + session.end_frame(/*timestamp*/ predicted_display_time, layers_base); // Network operations may be blocking, do them once everything was submitted for (const auto& handle: current_blit_handles) @@ -433,12 +644,6 @@ void scenes::stream::exit() shard_queue.close(); } -static const std::array supported_formats = -{ - vk::Format::eR8G8B8A8Srgb, - vk::Format::eB8G8R8A8Srgb -}; - void scenes::stream::setup(const to_headset::video_stream_description & description) { std::unique_lock lock(decoder_mutex); @@ -459,27 +664,6 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript const uint32_t swapchain_width = video_width / description.foveation[0].x.scale; const uint32_t swapchain_height = video_height / description.foveation[0].y.scale; - 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_formats.begin(), supported_formats.end(), format) != supported_formats.end()) - { - swapchain_format = format; - break; - } - } - - if (swapchain_format == vk::Format::eUndefined) - throw std::runtime_error("No supported swapchain format"); - - spdlog::info("Using format {}", vk::to_string(swapchain_format)); - auto views = system.view_configuration_views(viewconfig); swapchains.reserve(views.size()); diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 4232ab64..fca48e33 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -29,6 +29,7 @@ #include #include #include "audio/audio.h" +#include "render/imgui_impl.h" namespace scenes { @@ -82,20 +83,26 @@ class stream : public scene_impl, public std::enable_shared_from_this swapchains; + xr::swapchain swapchain_imgui; vk::Format swapchain_format; std::optional