From b27145f4682eb5fa2362f0cd8a703dafd3d54d35 Mon Sep 17 00:00:00 2001 From: Guillaume Meunier Date: Wed, 31 Jan 2024 21:07:18 +0100 Subject: [PATCH] Put the GUI and the controllers in other composition layers --- assets/imgui.gltf | 155 --------- client/render/imgui_impl.cpp | 294 +++++------------ client/render/imgui_impl.h | 103 +++--- client/render/scene_renderer.cpp | 153 +++++---- client/render/scene_renderer.h | 13 +- client/scenes/lobby.cpp | 538 ++++++------------------------- client/scenes/lobby.h | 9 +- client/scenes/lobby_gui.cpp | 407 +++++++++++++++++++++++ client/utils/handle.h | 5 + 9 files changed, 761 insertions(+), 916 deletions(-) delete mode 100644 assets/imgui.gltf create mode 100644 client/scenes/lobby_gui.cpp diff --git a/assets/imgui.gltf b/assets/imgui.gltf deleted file mode 100644 index 07db31d5..00000000 --- a/assets/imgui.gltf +++ /dev/null @@ -1,155 +0,0 @@ -{ - "accessors": [ - { - "bufferView": 0, - "byteOffset": 0, - "componentType": 5123, - "count": 6, - "type": "SCALAR", - "max": [ - 5 - ], - "min": [ - 0 - ] - }, - { - "bufferView": 1, - "byteOffset": 0, - "componentType": 5126, - "count": 6, - "type": "VEC3", - "max": [ - 0.5, - 0.5, - 0 - ], - "min": [ - -0.5, - -0.5, - 0 - ], - "name": "POSITION" - }, - { - "bufferView": 1, - "byteOffset": 12, - "componentType": 5126, - "count": 6, - "type": "VEC2", - "max": [ - 1, - 1 - ], - "min": [ - 0, - 0 - ], - "name": "TEXCOORD_0" - }, - { - "bufferView": 1, - "byteOffset": 20, - "componentType": 5126, - "count": 6, - "type": "VEC3", - "max": [ - 0, - 0, - 1.0000044107437134 - ], - "min": [ - 0, - 0, - 1.0000044107437134 - ], - "name": "NORMAL" - } - ], - "asset": { - "generator": "Aspose.3D 23.12.0", - "version": "2.0" - }, - "buffers": [ - { - "uri": "data:application/octet-stream;base64,AAABAAIAAwAEAAUAAAAAAAAAAL8AAAC/AAAAAAAAAAAAAIA/AAAAAAAAAAAlAIA/AAAAPwAAAL8AAAAAAACAPwAAgD8AAAAAAAAAACUAgD8AAAC/AAAAPwAAAAAAAAAAAAAAAAAAAAAAAAAAJQCAPwAAAD8AAAA/AAAAAAAAgD8AAAAAAAAAAAAAAAAlAIA/AAAAvwAAAD8AAAAAAAAAAAAAAAAAAAAAAAAAACUAgD8AAAA/AAAAvwAAAAAAAIA/AACAPwAAAAAAAAAAJQCAPwAAAAA=", - "byteLength": 212 - } - ], - "images" : [ - { - "uri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQAAAAA3bvkkAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAACYktHRAAB3YoTpAAAAAd0SU1FB+gBExMyDyqgtkcAAAAKSURBVAjXY2gAAACCAIHdQ2r0AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDI0LTAxLTE5VDE5OjUwOjE1KzAwOjAwKF3Y0gAAACV0RVh0ZGF0ZTptb2RpZnkAMjAyNC0wMS0xOVQxOTo1MDoxNSswMDowMFkAYG4AAAAodEVYdGRhdGU6dGltZXN0YW1wADIwMjQtMDEtMTlUMTk6NTA6MTUrMDA6MDAOFUGxAAAAAElFTkSuQmCC" - } - ], - "bufferViews": [ - { - "buffer": 0, - "byteOffset": 0, - "byteLength": 12, - "target": 34963 - }, - { - "buffer": 0, - "byteOffset": 16, - "byteLength": 192, - "byteStride": 32, - "target": 34962 - } - ], - "meshes": [ - { - "primitives": [ - { - "attributes": { - "POSITION": 1, - "TEXCOORD_0": 2, - "NORMAL": 3 - }, - "indices": 0, - "mode": 4, - "material": 0 - } - ], - "name": "" - } - ], - "samplers" : [ - { - "wrapS": 33071, - "wrapT": 33071, - "minFilter": 9987 - } - ], - "textures" : [ - { - "sampler" : 0, - "source" : 0 - } - ], - "materials" : [ - { - "name": "imgui", - "pbrMetallicRoughness": { - "baseColorTexture": { - "index": 0 - } - } - } - ], - "nodes": [ - { - "mesh": 0, - "name": "imgui", - "translation": [0, 1.5, -1.5], - "scale": [1.5, 1, 1] - } - ], - "scene": 0, - "scenes": [ - { - "nodes": [ - 0 - ] - } - ] -} diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index 29829b5e..6368c83a 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -27,8 +27,8 @@ #include "vulkan/vulkan_handles.hpp" #include "vulkan/vulkan_to_string.hpp" #include -#include "vk/allocation.h" #include +#include #include #include @@ -54,7 +54,7 @@ static vk::raii::RenderPass create_renderpass(vk::raii::Device& device, vk::Form .stencilLoadOp = vk::AttachmentLoadOp::eDontCare, .stencilStoreOp = vk::AttachmentStoreOp::eDontCare, .initialLayout = vk::ImageLayout::eUndefined, - .finalLayout = vk::ImageLayout::eTransferSrcOptimal, + .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, }; vk::AttachmentReference color_attachment{ @@ -96,17 +96,17 @@ static void check_vk_result(VkResult result) } } -static std::optional ray_plane_intersection(const imgui_context::imgui_viewport& vp, const imgui_context::controller_state& in) +std::optional imgui_context::ray_plane_intersection(const imgui_context::controller_state& in) { if (!in.active) return {}; - auto M = glm::transpose(glm::mat3_cast(vp.orientation)); // world-to-plane transform + auto M = glm::transpose(glm::mat3_cast(orientation_)); // world-to-plane transform glm::vec3 controller_direction = glm::column(glm::mat3_cast(in.aim_orientation), 2); // Compute all vectors in the reference frame of the GUI plane - glm::vec3 ray_start = M * (in.aim_position - vp.position); + glm::vec3 ray_start = M * (in.aim_position - position_); glm::vec3 ray_dir = M * controller_direction; if (ray_dir.z > 0.0001f) @@ -123,93 +123,72 @@ static std::optional ray_plane_intersection(const imgui_context::imgui_v coord.y = ray_start.y + lambda * ray_dir.y; // Convert from mesh coordinates to imgui coordinates - coord = coord / vp.scale; + coord = coord / scale; if (fabs(coord.x) <= 0.5 && fabs(coord.y) <= 0.5) return ImVec2( - (0.5 + coord.x) * vp.size.width, - (0.5 - coord.y) * vp.size.height); + (0.5 + coord.x) * size.width, + (0.5 - coord.y) * size.height); } } return {}; } -imgui_context::imgui_viewport::imgui_viewport(vk::raii::Device& device, vk::raii::CommandPool& command_pool, vk::RenderPass renderpass, vk::Extent2D size, vk::Format format) : - device(device), - size(size) +imgui_context::imgui_frame& imgui_context::get_frame(vk::Image destination) { - num_mipmaps = std::floor(std::log2(std::max(size.width, size.height))) + 1; - - for(auto& frame:frames) + for(auto& i: frames) { - frame.image = image_allocation( - vk::ImageCreateInfo{ - .imageType = vk::ImageType::e2D, - .format = format, - .extent = { - size.width, - size.height, - 1 - }, - .mipLevels = num_mipmaps, - .arrayLayers = 1, - .samples = vk::SampleCountFlagBits::e1, - .tiling = vk::ImageTiling::eOptimal, - .usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst, - .initialLayout = vk::ImageLayout::eUndefined, - }, - VmaAllocationCreateInfo{ - .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE - } - ); - - // Only 1 mipmap level for the framebuffer view - frame.image_view_framebuffer = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ - .image = (vk::Image)frame.image, - .viewType = vk::ImageViewType::e2D, - .format = format, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - } - }); - - frame.image_view_texture = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ - .image = (vk::Image)frame.image, - .viewType = vk::ImageViewType::e2D, - .format = format, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = num_mipmaps, - .baseArrayLayer = 0, - .layerCount = 1, - } - }); - - frame.framebuffer = vk::raii::Framebuffer(device, vk::FramebufferCreateInfo{ - .renderPass = renderpass, - .attachmentCount = 1, - .pAttachments = &*frame.image_view_framebuffer, - .width = size.width, - .height = size.height, - .layers = 1, - }); - - frame.command_buffer = std::move(device.allocateCommandBuffers({ - .commandPool = *command_pool, - .commandBufferCount = 1, - })[0]); - - frame.fence = device.createFence(vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}); + if (i.destination == destination) + return i; } + + auto& frame = frames.emplace_back(); + + frame.destination = destination; + + // Only 1 mipmap level for the framebuffer view + frame.image_view_framebuffer = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ + .image = destination, + .viewType = vk::ImageViewType::e2D, + .format = format, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + } + }); + + frame.framebuffer = vk::raii::Framebuffer(device, vk::FramebufferCreateInfo{ + .renderPass = *renderpass, + .attachmentCount = 1, + .pAttachments = &*frame.image_view_framebuffer, + .width = size.width, + .height = size.height, + .layers = 1, + }); + + frame.command_buffer = std::move(device.allocateCommandBuffers({ + .commandPool = *command_pool, + .commandBufferCount = 1, + })[0]); + + frame.fence = device.createFence(vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}); + + return frame; } -imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_index, vk::raii::Queue& queue, XrSpace world, std::span controllers_, float resolution, glm::vec2 scale) : +static const std::array pool_sizes = +{ + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + } +}; + +imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_index, vk::raii::Queue& queue, XrSpace world, std::span controllers_, vk::Extent2D size, float resolution, vk::Format format) : device(device), queue_family_index(queue_family_index), queue(queue), @@ -220,11 +199,14 @@ imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_ind .poolSizeCount = pool_sizes.size(), .pPoolSizes = pool_sizes.data(), }), - renderpass(create_renderpass(device, vk::Format::eR8G8B8A8Unorm, true)), + renderpass(create_renderpass(device, format, true)), command_pool(device, vk::CommandPoolCreateInfo{ .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient, .queueFamilyIndex = queue_family_index, }), + size(size), + format(format), + scale(size.width / resolution, size.height / resolution), context(ImGui::CreateContext()), io(ImGui::GetIO()), world(world) @@ -233,14 +215,6 @@ imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_ind for(const auto& i:controllers_) controllers.emplace_back(i, controller_state{}); - vk::Extent2D extent{ - (uint32_t)(resolution * scale.x), - (uint32_t)(resolution * scale.y) - }; - - viewport = std::make_shared(device, command_pool, *renderpass, extent, vk::Format::eR8G8B8A8Unorm); - viewport->scale = scale; - io.IniFilename = nullptr; ImGui_ImplVulkan_InitInfo init_info = { @@ -252,8 +226,9 @@ imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_ind .PipelineCache = *application::get_pipeline_cache(), .DescriptorPool = *descriptor_pool, .Subpass = 0, - .MinImageCount = imgui_viewport::frames_in_flight, - .ImageCount = imgui_viewport::frames_in_flight, + // image count is not actually used because we don't use a WSI swapchain + .MinImageCount = 2, // imgui_viewport::frames_in_flight, + .ImageCount = 2, //imgui_viewport::frames_in_flight, .MSAASamples = VK_SAMPLE_COUNT_1_BIT, .Allocator = nullptr, .CheckVkResultFn = check_vk_result, @@ -272,7 +247,7 @@ imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_ind // Setup Dear ImGui style ImGui::StyleColorsDark(); - //ImGui::StyleColorsClassic(); + // ImGui::StyleColorsClassic(); //ImGui::StyleColorsLight(); ImGuiStyle& style = ImGui::GetStyle(); @@ -289,15 +264,8 @@ imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_ind style.Colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0,0,0,0.8); - // TODO: scroll to drag https://github.com/ocornut/imgui/issues/3379 } -void imgui_context::set_position(glm::vec3 position, glm::quat orientation) -{ - auto& vp = *viewport; - vp.position = position; - vp.orientation = orientation; -} void imgui_context::new_frame(XrTime display_time) { @@ -382,7 +350,7 @@ void imgui_context::new_frame(XrTime display_time) if (new_focused_controller != (size_t)-1) { - position = ray_plane_intersection(*viewport, new_states[new_focused_controller]); + position = ray_plane_intersection(new_states[new_focused_controller]); trigger = new_states[new_focused_controller].trigger_value; auto scroll = new_states[new_focused_controller].scroll_value; @@ -423,9 +391,10 @@ void imgui_context::new_frame(XrTime display_time) } // Start the Dear ImGui frame + ImGui::SetCurrentContext(context); ImGui_ImplVulkan_NewFrame(); - io.DisplaySize = ImVec2(viewport->size.width, viewport->size.height); + io.DisplaySize = ImVec2(size.width, size.height); io.DisplayFramebufferScale = ImVec2(1, 1); // See ImGui_ImplSDL2_ProcessEvent @@ -444,18 +413,16 @@ void imgui_context::new_frame(XrTime display_time) } } -std::shared_ptr imgui_context::render() +void imgui_context::render(vk::Image destination) { 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 {}; + return; - auto &vp = *viewport; - vp.frameindex = (vp.frameindex + 1) % imgui_viewport::frames_in_flight; - auto& f = vp.frames[vp.frameindex]; + auto& f = get_frame(destination); auto& cb = f.command_buffer; device.waitForFences(*f.fence, true, 1'000'000'000); // TODO check timeout @@ -469,7 +436,7 @@ std::shared_ptr imgui_context::render() .renderPass = *renderpass, .framebuffer = *f.framebuffer, .renderArea = { - .extent = vp.size, + .extent = size, }, .clearValueCount = 1, .pClearValues = &clear @@ -479,113 +446,6 @@ std::shared_ptr imgui_context::render() cb.endRenderPass(); - // TODO: create mipmaps - // Create mipmaps - int width = vp.size.width; - int height = vp.size.height; - vk::ImageLayout prev_layout = vk::ImageLayout::eTransferSrcOptimal; - for(uint32_t level = 1; level < vp.num_mipmaps; level++) - { - int next_width = width > 1 ? width / 2 : 1; - int next_height = height > 1 ? height / 2 : 1; - - // Transition source image layout to eTransferSrcOptimal and destination image layout to eTransferDstOptimal - cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, - { - vk::ImageMemoryBarrier{ - .srcAccessMask = vk::AccessFlagBits::eTransferWrite, - .dstAccessMask = vk::AccessFlagBits::eShaderRead, - .oldLayout = prev_layout, - .newLayout = vk::ImageLayout::eTransferSrcOptimal, - .image = f.image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = level - 1, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }, - vk::ImageMemoryBarrier{ - .srcAccessMask = vk::AccessFlagBits::eTransferWrite, // TODO - .dstAccessMask = vk::AccessFlagBits::eShaderRead, // TODO - .oldLayout = vk::ImageLayout::eUndefined, - .newLayout = vk::ImageLayout::eTransferDstOptimal, - .image = f.image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = level, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }, - - }); - prev_layout = vk::ImageLayout::eTransferDstOptimal; - - // Blit level n-1 to level n - cb.blitImage(f.image, vk::ImageLayout::eTransferSrcOptimal, f.image, vk::ImageLayout::eTransferDstOptimal, - vk::ImageBlit{ - .srcSubresource = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .mipLevel = level - 1, - .baseArrayLayer = 0, - .layerCount = 1}, - .srcOffsets = std::array{ - vk::Offset3D{0, 0, 0}, - vk::Offset3D{width, height, 1}, - }, - .dstSubresource = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .mipLevel = level, - .baseArrayLayer = 0, - .layerCount = 1 - }, - .dstOffsets = std::array{ - vk::Offset3D{0, 0, 0}, - vk::Offset3D{next_width, next_height, 1}, - }, - }, - vk::Filter::eLinear); - - - // Transition source image layout to eShaderReadOnlyOptimal - cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{ - .srcAccessMask = vk::AccessFlagBits::eTransferRead, - .dstAccessMask = vk::AccessFlagBits::eShaderRead, - .oldLayout = vk::ImageLayout::eTransferSrcOptimal, - .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, - .image = f.image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = level - 1, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }); - - width = next_width; - height = next_height; - } - - // Transition the last level to eShaderReadOnlyOptimal - cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{ - .srcAccessMask = vk::AccessFlagBits::eTransferWrite, - .dstAccessMask = vk::AccessFlagBits::eShaderRead, - .oldLayout = prev_layout, - .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, - .image = f.image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = vp.num_mipmaps - 1, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }); - cb.end(); queue.submit(vk::SubmitInfo{ @@ -594,19 +454,19 @@ std::shared_ptr imgui_context::render() }, *f.fence); // Use the aliasing constructor - return std::shared_ptr{viewport, &vp.frames[vp.frameindex].image_view_texture}; + // return std::shared_ptr{viewport, &vp.frames[vp.frameindex].image_view_texture}; } imgui_context::~imgui_context() { // Release the command buffers, they will be destroyed with the command pool - for(auto& f: viewport->frames) + for(auto& f: frames) f.command_buffer.release(); // Wait for fences here and not in imgui_viewport::~imgui_viewport so that the command buffers have finished when ImGui_ImplVulkan_Shutdown is called - std::array fences; - for(auto&& [i, f]: utils::enumerate(viewport->frames)) - fences[i] = *f.fence; + std::vector fences; + for(auto& f: frames) + fences.push_back(*f.fence); device.waitForFences(fences, true, 1'000'000'000); diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h index 6111e24d..ad6593a9 100644 --- a/client/render/imgui_impl.h +++ b/client/render/imgui_impl.h @@ -18,48 +18,27 @@ #pragma once -#include "render/scene_data.h" #include #include #include #include #include -#include "vk/allocation.h" +#include +#include +#include class imgui_context { public: struct imgui_frame { - image_allocation image; + vk::Image destination; vk::raii::ImageView image_view_framebuffer = nullptr; - vk::raii::ImageView image_view_texture = nullptr; vk::raii::Framebuffer framebuffer = nullptr; vk::raii::CommandBuffer command_buffer = nullptr; vk::raii::Fence fence = nullptr; }; - struct imgui_viewport - { - static constexpr int frames_in_flight = 2; - uint32_t num_mipmaps; - - std::array frames; - int frameindex = 0; - - vk::raii::Device& device; - - vk::Extent2D size; - vk::ClearValue clear_value = {vk::ClearColorValue{0,0,0,0}}; - - // TODO: sync with 3d scene - glm::vec3 position = {0, 1, -1.5}; - glm::quat orientation = {1, 0, 0, 0}; - glm::vec2 scale = {1, 1}; - - imgui_viewport(vk::raii::Device& device, vk::raii::CommandPool& command_pool, vk::RenderPass renderpass, vk::Extent2D size, vk::Format format); - }; - struct controller { XrSpace aim; @@ -86,14 +65,6 @@ public: }; private: - static inline const std::array pool_sizes = - { - vk::DescriptorPoolSize{ - .type = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - } - }; - vk::raii::Device& device; uint32_t queue_family_index; vk::raii::Queue& queue; @@ -103,14 +74,20 @@ private: vk::raii::RenderPass renderpass; vk::raii::CommandPool command_pool; - // shared_ptr because it needs to be kept alive until the output textures are not used anymore - std::shared_ptr viewport; + std::vector frames; + imgui_frame& get_frame(vk::Image destination); + + vk::Extent2D size; + vk::Format format; + vk::ClearValue clear_value = {vk::ClearColorValue{0,0,0,0}}; + + glm::vec3 position_ = {0, 1, -1.5}; + glm::quat orientation_ = {1, 0, 0, 0}; + glm::vec2 scale = {1, 1}; ImGuiContext * context; ImGuiIO& io; - // std::string ini_filename; - std::vector> controllers; XrSpace world; size_t focused_controller = (size_t)-1; @@ -118,14 +95,58 @@ private: bool button_pressed = false; + std::optional ray_plane_intersection(const imgui_context::controller_state& in); + public: - imgui_context(vk::raii::Device& device, uint32_t queue_family_index, - vk::raii::Queue& queue, XrSpace world, std::span controllers, float resolution, glm::vec2 scale); + imgui_context(vk::raii::Device& device, uint32_t queue_family_index, vk::raii::Queue& queue, XrSpace world, std::span controllers, vk::Extent2D size, float resolution, vk::Format format); ~imgui_context(); - void set_position(glm::vec3 position, glm::quat orientation); + void set_position(glm::vec3 position, glm::quat orientation) + { + position_ = position; + orientation_ = orientation; + } + + XrPosef pose() + { + return XrPosef{ + .orientation = { + .x = orientation_.x, + .y = orientation_.y, + .z = orientation_.z, + .w = orientation_.w, + }, + .position = { + .x = position_.x, + .y = position_.y, + .z = position_.z, + } + }; + } + + glm::vec3& position() + { + return position_; + } + + glm::quat& orientation() + { + return orientation_; + } + + glm::vec3 position() const + { + return position_; + } + + glm::quat orientation() const + { + return orientation_; + } + void new_frame(XrTime display_time); - std::shared_ptr render(); + + void render(vk::Image destination); ImFont * large_font; size_t get_focused_controller() const diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index 19c6d91e..1b3db22d 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -28,6 +28,7 @@ #include "vk/pipeline.h" #include "vk/shader.h" #include +#include #include #include #include @@ -191,6 +192,11 @@ 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(); @@ -245,6 +251,13 @@ void scene_renderer::wait_idle() device.waitForFences(fences, true, 1'000'000'000); // TODO check for timeout } +// #define MSAA_4x + +#ifdef MSAA_4x +#define MSAA_SAMPLES vk::SampleCountFlagBits::e4 +#else +#define MSAA_SAMPLES vk::SampleCountFlagBits::e1 +#endif vk::raii::RenderPass scene_renderer::create_renderpass() { @@ -253,7 +266,7 @@ vk::raii::RenderPass scene_renderer::create_renderpass() std::array attachments = { vk::AttachmentDescription{ .format = output_format, - .samples = vk::SampleCountFlagBits::e4, + .samples = MSAA_SAMPLES, .loadOp = vk::AttachmentLoadOp::eClear, .storeOp = vk::AttachmentStoreOp::eStore, .initialLayout = vk::ImageLayout::eUndefined, @@ -261,7 +274,7 @@ vk::raii::RenderPass scene_renderer::create_renderpass() }, vk::AttachmentDescription{ .format = depth_format, - .samples = vk::SampleCountFlagBits::e4, + .samples = MSAA_SAMPLES, .loadOp = vk::AttachmentLoadOp::eClear, .storeOp = vk::AttachmentStoreOp::eDontCare, .stencilLoadOp = vk::AttachmentLoadOp::eClear, @@ -270,6 +283,7 @@ vk::raii::RenderPass scene_renderer::create_renderpass() .finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal, }, +#ifdef MSAA_4x vk::AttachmentDescription{ .format = output_format, .samples = vk::SampleCountFlagBits::e1, @@ -280,7 +294,9 @@ vk::raii::RenderPass scene_renderer::create_renderpass() .initialLayout = vk::ImageLayout::eUndefined, .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, - }}; + } +#endif + }; info.setAttachments(attachments); vk::AttachmentReference color_attachment{ @@ -293,16 +309,20 @@ vk::raii::RenderPass scene_renderer::create_renderpass() .layout = vk::ImageLayout::eDepthStencilAttachmentOptimal, }; +#ifdef MSAA_4x 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, }; info.setSubpasses(subpasses); @@ -361,7 +381,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image }, .mipLevels = 1, .arrayLayers = 1, - .samples = vk::SampleCountFlagBits::e4, + .samples = MSAA_SAMPLES, .tiling = vk::ImageTiling::eOptimal, .usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment @@ -380,6 +400,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eDepth, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, }); +#ifdef MSAA_4x out.multisample_image = image_allocation{vk::ImageCreateInfo{ .imageType = vk::ImageType::e2D, .format = output_format, @@ -390,7 +411,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image }, .mipLevels = 1, .arrayLayers = 1, - .samples = vk::SampleCountFlagBits::e4, + .samples = MSAA_SAMPLES, .tiling = vk::ImageTiling::eOptimal, .usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment @@ -408,6 +429,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image .components{}, .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, }); +#endif vk::FramebufferCreateInfo fb_info{ .renderPass = *renderpass, @@ -416,11 +438,18 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image .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); @@ -483,7 +512,7 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) .lineWidth = 1.0, }}, .MultisampleState = {vk::PipelineMultisampleStateCreateInfo{ - .rasterizationSamples = vk::SampleCountFlagBits::e4, + .rasterizationSamples = MSAA_SAMPLES, }}, .DepthStencilState = {vk::PipelineDepthStencilStateCreateInfo{ .depthTestEnable = true, @@ -502,7 +531,7 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) .srcAlphaBlendFactor = vk::BlendFactor::eSrcAlpha, .dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, .alphaBlendOp = vk::BlendOp::eAdd, - .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB}}, + .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA}}, .DynamicState = {}, .layout = *pipeline_layout, .renderPass = *renderpass, @@ -530,17 +559,60 @@ vk::Sampler scene_renderer::get_sampler(const sampler_info & info) return **out; } -scene_renderer::per_frame_resources & scene_renderer::start_frame() +void scene_renderer::start_frame() { - current_frame = (current_frame + 1) % frame_resources.size(); + current_frame_index = (current_frame_index + 1) % frame_resources.size(); - device.waitForFences(*frame_resources[current_frame].fence, true, 1'000'000'000); - device.resetFences(*frame_resources[current_frame].fence); + auto& f = current_frame(); + f.cpu_time_start = std::chrono::steady_clock::now(); - frame_resources[current_frame].resources.clear(); - frame_resources[current_frame].cb.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); + device.waitForFences(*f.fence, true, 1'000'000'000); + device.resetFences(*f.fence); - return frame_resources[current_frame]; + 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) + { + f.staging_buffer = buffer_allocation{vk::BufferCreateInfo{ + .size = 1048576, + .usage = vk::BufferUsageFlagBits::eUniformBuffer}, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, + .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}, + "scene_renderer::render (UBO staging)" + }; + } +} + +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() +{ + return frame_resources[current_frame_index]; } void scene_renderer::update_material_descriptor_set(scene_data::material& material) @@ -609,8 +681,10 @@ static void print_scene_hierarchy(const scene_data& scene, std::span } } -void scene_renderer::render(scene_data & scene, std::span frames) +void scene_renderer::render(scene_data & scene, const std::array& clear_color, std::span frames) { + per_frame_resources & resources = current_frame(); + size_t ubo_alignment = physical_device_properties.limits.minUniformBufferOffsetAlignment; size_t ubo_frame_size = utils::align_up(ubo_alignment, sizeof(frame_gpu_data)); @@ -623,59 +697,36 @@ void scene_renderer::render(scene_data & scene, std::span frames) }); // Enough room for one frame_gpu_data per view and one instance_gpu_data per instance and per view - size_t ubo_size = nb_frames * (ubo_frame_size + nb_objects * ubo_instance_size); + // size_t ubo_size = nb_frames * (ubo_frame_size + nb_objects * ubo_instance_size); // Compute the position of each ubo, taking in account the minimum alignment - ptrdiff_t offset = 0; - std::vector ubo_frame_offset(nb_frames); + std::vector ubo_frame_offset(nb_frames); for(size_t i = 0; i < nb_frames; i++) { - ubo_frame_offset[i] = offset; - offset += ubo_frame_size; + ubo_frame_offset[i] = resources.staging_buffer_offset; + resources.staging_buffer_offset += ubo_frame_size; } - std::vector ubo_object_offset(nb_frames * nb_objects); + std::vector ubo_object_offset(nb_frames * nb_objects); for(size_t i = 0; i < nb_frames; i++) { for(size_t j = 0; j < nb_objects; j++) { - ubo_object_offset[i * nb_objects + j] = offset; - offset += ubo_frame_size; + ubo_object_offset[i * nb_objects + j] = resources.staging_buffer_offset; + resources.staging_buffer_offset += ubo_instance_size; } } + assert(resources.staging_buffer_offset <= resources.staging_buffer.info().size); auto current_ubo_frame_offset = ubo_frame_offset.begin(); auto current_ubo_object_offset = ubo_object_offset.begin(); - per_frame_resources & resources = start_frame(); vk::raii::CommandBuffer & cb = resources.cb; - if (!resources.staging_buffer || resources.staging_buffer.info().size < ubo_size) - { - resources.staging_buffer = buffer_allocation{vk::BufferCreateInfo{ - .size = ubo_size, - .usage = vk::BufferUsageFlagBits::eUniformBuffer}, - VmaAllocationCreateInfo{ - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, - .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}, - "scene_renderer::render (UBO staging)" - }; - } - - // if (!resources.uniform_buffer || resources.uniform_buffer.info().size < ubo_size) - // { - // resources.staging_buffer = buffer_allocation{vk::BufferCreateInfo{ - // .size = ubo_size, - // .usage = vk::BufferUsageFlagBits::eUniformBuffer}, - // VmaAllocationCreateInfo{ - // .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, - // .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}}; - // } - uintptr_t ubo = reinterpret_cast(resources.staging_buffer.map()); std::array clear_values{ - vk::ClearColorValue(0.0f, 0.0f, 0.0f, 0.0f), + vk::ClearColorValue{clear_color}, vk::ClearDepthStencilValue{1.0, 0}, }; @@ -844,12 +895,4 @@ void scene_renderer::render(scene_data & scene, std::span frames) current_ubo_frame_offset++; } - - cb.end(); - - queue.submit(vk::SubmitInfo{ - .commandBufferCount = 1, - .pCommandBuffers = &*cb, - }, *frame_resources[current_frame].fence); - } diff --git a/client/render/scene_renderer.h b/client/render/scene_renderer.h index 973be0f5..7d2b970e 100644 --- a/client/render/scene_renderer.h +++ b/client/render/scene_renderer.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -150,20 +151,24 @@ 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 // host visible, host coherent + size_t staging_buffer_offset; buffer_allocation staging_buffer; // device local // buffer_allocation uniform_buffer; + + std::chrono::steady_clock::time_point cpu_time_start; }; std::vector frame_resources; - int current_frame; + int current_frame_index; - per_frame_resources& start_frame(); + per_frame_resources& current_frame(); void update_material_descriptor_set(scene_data::material& material); @@ -179,7 +184,9 @@ public: glm::mat4 view; }; - void render(scene_data & scene, std::span info); + void start_frame(); + void render(scene_data & scene, const std::array& clear_color, std::span info); + void end_frame(); std::shared_ptr get_default_material() { diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index 73a5fed3..18710f4a 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -25,6 +25,7 @@ #include "input_profile.h" #include "openxr/openxr.h" #include "render/scene_data.h" +#include "render/scene_renderer.h" #include "stream.h" #include "hardware.h" #include "wivrn_client.h" @@ -33,18 +34,14 @@ #include #include "wivrn_discover.h" -#include "wivrn_packets.h" #include #include #include -#include #include #include #include #include #include -#include -#include #include #include #include @@ -157,7 +154,7 @@ void scenes::lobby::move_gui(glm::vec3 position, glm::quat orientation, XrTime p { const float gui_target_distance = 1.5; - glm::vec3 gui_direction = glm::column(glm::mat3_cast(imgui_node->rotation), 2); + glm::vec3 gui_direction = glm::column(glm::mat3_cast(imgui_ctx->orientation()), 2); float gui_yaw = atan2(gui_direction.x, gui_direction.z); glm::vec3 head_direction = -glm::column(glm::mat3_cast(orientation), 2); @@ -169,20 +166,16 @@ void scenes::lobby::move_gui(glm::vec3 position, glm::quat orientation, XrTime p glm::vec3 gui_target_position = position + gui_target_distance * head_direction; - glm::vec3 gui_position_error = gui_target_position - imgui_node->translation; + glm::vec3 gui_position_error = gui_target_position - imgui_ctx->position(); float gui_yaw_error = remainderf(head_yaw - gui_yaw, 2 * M_PI); if (move_gui_first_time) { move_gui_first_time = false; gui_yaw += gui_yaw_error; - imgui_node->translation += gui_position_error; - imgui_node->rotation = glm::quat{ cos(gui_yaw/2), 0, sin(gui_yaw/2), 0 }; - } - else - { - // gui_yaw += gui_yaw_error * std::min(1.0f, dt / tau); - // imgui_node->translation += gui_position_error * std::min(1.0f, dt / tau); + + imgui_ctx->position() += gui_position_error; + imgui_ctx->orientation() = glm::quat{ cos(gui_yaw/2), 0, sin(gui_yaw/2), 0 }; } } @@ -392,37 +385,6 @@ static glm::mat4 view_matrix(XrPosef pose) return glm::inverse(inv_view_matrix); } -static void CenterTextH(const std::string& text) -{ - float win_width = ImGui::GetWindowSize().x; - float text_width = ImGui::CalcTextSize(text.c_str()).x; - ImGui::SetCursorPosX((win_width - text_width) / 2); - - ImGui::Text("%s", text.c_str()); -} - -static void CenterTextHV(const std::string& text) -{ - ImVec2 size = ImGui::GetWindowSize(); - - std::vector lines = utils::split(text); - - float text_height = 0; - for(const auto& i: lines) - text_height += ImGui::CalcTextSize(i.c_str()).y; - - ImGui::SetCursorPosY((size.y - text_height) / 2); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); - for(const auto& i: lines) - { - float text_width = ImGui::CalcTextSize(i.c_str()).x; - ImGui::SetCursorPosX((size.x - text_width) / 2); - ImGui::Text("%s", i.c_str()); - } - ImGui::PopStyleVar(); -} - void scenes::lobby::update_server_list() { std::vector discovered_services = discover->get_services(); @@ -472,352 +434,38 @@ void scenes::lobby::connect(server_data& data) }, data.service, data.manual); } -void scenes::lobby::gui_connecting() +static std::vector render_layer(std::vector& views, std::vector& swapchains, scene_renderer& renderer, scene_data& data, const std::array& clear_color) { - const ImVec2 button_size(220, 80); + std::vector frames; + frames.reserve(views.size()); - std::string status; - if (next_scene) - status = "Waiting for video stream"; - else if (async_session.valid()) - status = async_session.get_progress(); - else if (async_error) - status = *async_error; + std::vector layer_views; + layer_views.reserve(views.size()); - std::string button_label; - - if (async_error) - button_label = "Close"; - else - button_label = "Cancel"; - - ImGui::Dummy({1000, 1}); - - - ImGui::PushFont(imgui_ctx->large_font); - CenterTextH(fmt::format("Connection to {}", server_name)); - ImGui::PopFont(); - - // ImGui::TextWrapped("%s", status.first.c_str()); - ImGui::Text("%s", status.c_str()); - - ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - button_size.x - ImGui::GetStyle().WindowPadding.x); - - if (ImGui::Button(button_label.c_str(), button_size)) + for (auto && [view, swapchain]: utils::zip(views, swapchains)) { - async_session.cancel(); + int image_index = swapchain.acquire(); + swapchain.wait(); - next_scene.reset(); + frames.push_back({.destination = swapchain.images()[image_index].image, + .projection = projection_matrix(view.fov), + .view = view_matrix(view.pose)}); - ImGui::CloseCurrentPopup(); - } - if (ImGui::IsItemHovered()) - hovered_item = "close"; -} - -void scenes::lobby::gui_add_server() -{ - const ImVec2 button_size(220, 80); - - // CenterNextWindow({1200, 900}); - - ImGui::PushFont(imgui_ctx->large_font); - CenterTextH("Add server"); - ImGui::PopFont(); - - // TODO column widths - ImGui::BeginTable("table", 2); - - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - ImGui::Text("Displayed name"); - - static char buf[100]; - ImGui::TableNextColumn(); - ImGui::InputText("##Name", buf, sizeof(buf)); - if (ImGui::IsItemHovered()) - hovered_item = "name"; - - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - ImGui::Text("Host name"); - - static char buf2[100]; - ImGui::TableNextColumn(); - ImGui::InputText("##Hostname", buf2, sizeof(buf2)); - if (ImGui::IsItemHovered()) - hovered_item = "hostname"; - - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - ImGui::Text("Port"); - - static int port; - ImGui::TableNextColumn(); - ImGui::InputInt("##Port", &port); - if (ImGui::IsItemHovered()) - hovered_item = "port"; - - ImGui::EndTable(); - - // TODO virtual keyboard - // See https://github.com/qt/qtvirtualkeyboard/tree/dev/src/layouts/fallback - // https://github.com/qt/qtvirtualkeyboard/blob/dev/src/layouts/fr_FR/main.qml - // https://doc.qt.io/qt-6/qtvirtualkeyboard-layouts.html - - gui_keyboard(ImVec2(1000, 280)); - - auto top_left = ImGui::GetWindowContentRegionMin(); - auto bottom_right = ImGui::GetWindowContentRegionMax(); - - ImGui::SetCursorPosX(top_left.x); - if (ImGui::Button("Cancel", button_size)) - ImGui::CloseCurrentPopup(); - if (ImGui::IsItemHovered()) - hovered_item = "cancel"; - - ImGui::SameLine(bottom_right.x - button_size.x); - - if (ImGui::Button("Save", button_size)) - { - ImGui::CloseCurrentPopup(); - - server_data data - { - .manual = true, - .service = { - .name = add_server_window_prettyname, - .hostname = add_server_window_hostname, - .port = add_server_window_port, - }, - }; - - servers.emplace("manual-" + data.service.name, data); - save_config(); - - } - if (ImGui::IsItemHovered()) - hovered_item = "save"; -} - -void scenes::lobby::gui_server_list() -{ - // Build an index of the cookies sorted by server name - std::multimap sorted_cookies; - for(auto&& [cookie, data]: servers) - { - sorted_cookies.emplace(data.service.name, cookie); + layer_views.push_back({ + .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, + .pose = view.pose, + .fov = view.fov, + .subImage = { + .swapchain = swapchain, + .imageRect = { + .offset = {0, 0}, + .extent = swapchain.extent()}}, + }); } - const ImVec2 button_size(220, 80); - const float list_item_height = 100; - auto& style = ImGui::GetStyle(); + renderer.render(data, clear_color, frames); - ImGui::SetNextWindowPos({0, 0}); - ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size); - ImGui::Begin("WiVRn", nullptr, - ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove); - - ImGui::PushFont(imgui_ctx->large_font); - CenterTextH(std::string("WiVRn ") + xrt::drivers::wivrn::git_version); - ImGui::PopFont(); - - std::string cookie_to_remove; - - float list_box_height = ImGui::GetWindowContentRegionMax().y - button_size.y - style.WindowPadding.y - ImGui::GetCursorPosY(); - - if (ImGui::BeginListBox("##detected servers", ImVec2(-FLT_MIN, list_box_height))) - { - if (sorted_cookies.empty()) - { - ImGui::PushFont(imgui_ctx->large_font); - ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 0.5)); - CenterTextHV("Start a WiVRn server on your\nlocal network"); - ImGui::PopStyleColor(); - ImGui::PopFont(); - } - - auto pos = ImGui::GetCursorPos(); - - ImGui::PushStyleColor(ImGuiCol_Header, 0); - ImGui::PushStyleColor(ImGuiCol_HeaderHovered, 0); - ImGui::PushStyleColor(ImGuiCol_HeaderActive, 0); - for(const auto& [name, cookie]: sorted_cookies) - { - server_data& data = servers.at(cookie); - bool is_selected = (cookie == selected_item); - - ImGui::SetCursorPos(pos); - - ImGui::SetNextItemAllowOverlap(); - - // TODO custom widget - if (ImGui::Selectable(("##" + cookie).c_str(), is_selected, ImGuiSelectableFlags_None, ImVec2(0, list_item_height))) - selected_item = cookie; - - ImGui::SetCursorPos(ImVec2(pos.x, pos.y)); - ImGui::Text("%s", name.c_str()); - - if (!data.manual) - { - ImGui::SetCursorPos(ImVec2(pos.x, pos.y + 50)); - 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; - ImGui::PopStyleColor(); - } - - // TODO - // if (ImGui::IsItemHovered()) - // { - // ImGui::SetTooltip("Tooltip"); - // } - - ImVec2 button_position(ImGui::GetWindowContentRegionMax().x + style.FramePadding.x, pos.y + (list_item_height - button_size.y) / 2); - - button_position.x -= button_size.x + style.WindowPadding.x; - ImGui::SetCursorPos(button_position); - - bool enable_connect_button = data.visible || data.manual; - ImGui::BeginDisabled(!enable_connect_button); - if (enable_connect_button) - { - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.8f, 0.3f, 0.40f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.8f, 0.3f, 1.00f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 1.0f, 0.2f, 1.00f)); - } - else - { - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.4f, 0.3f, 0.40f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.4f, 0.3f, 1.00f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.5f, 0.2f, 1.00f)); - } - if (ImGui::Button(("Connect##" + cookie).c_str(), button_size)) - { - connect(data); - ImGui::OpenPopup("connecting"); - } - - if (ImGui::IsItemHovered()) - hovered_item = "connect " + cookie; - - ImGui::PopStyleColor(3); - ImGui::EndDisabled(); - - button_position.x -= button_size.x + style.WindowPadding.x; - if (data.manual) - { - ImGui::SetCursorPos(button_position); - 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(("Remove##" + cookie).c_str(), button_size)) - cookie_to_remove = cookie; - - if (ImGui::IsItemHovered()) - hovered_item = "remove " + cookie; - - ImGui::PopStyleColor(3); - } - - pos.y += 120; - } - ImGui::PopStyleColor(3); - - if (cookie_to_remove != "") - { - servers.erase(cookie_to_remove); - save_config(); - } - - ImGui::EndListBox(); - } - - auto top_left = ImGui::GetWindowContentRegionMin(); - auto bottom_right = ImGui::GetWindowContentRegionMax(); - -#ifndef NDEBUG - ImGui::SetCursorPos(ImVec2(top_left.x, bottom_right.y - button_size.y)); - if (ImGui::Button("Add server", button_size)) - { - ImGui::OpenPopup("add_server"); - strcpy(add_server_window_prettyname, ""); - strcpy(add_server_window_hostname, ""); - add_server_window_port = xrt::drivers::wivrn::default_port; - } - - if (ImGui::IsItemHovered()) - { - hovered_item = "add"; - ImGui::SetTooltip("TODO"); - } -#endif - - ImGui::SetCursorPos(ImVec2(bottom_right.x - button_size.x, bottom_right.y - button_size.y)); - if (ImGui::Button("Exit", button_size)) - application::pop_scene(); - - if (ImGui::IsItemHovered()) - hovered_item = "exit"; - - if (ImGui::BeginPopupModal("add_server", nullptr, - ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove)) - { - gui_add_server(); - ImGui::EndPopup(); - } - - // Check if an automatic connection has started - if ((async_session.valid() || next_scene) && !ImGui::IsPopupOpen("connecting")) - ImGui::OpenPopup("connecting"); - - if (ImGui::BeginPopupModal("connecting", nullptr, - ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove)) - { - gui_connecting(); - ImGui::EndPopup(); - } - - ImGui::End(); -} - -void scenes::lobby::draw_gui(XrTime predicted_display_time) -{ - std::optional> head_position = application::locate_controller(application::view(), world_space, predicted_display_time); - - if (head_position) - { - move_gui(head_position->first, head_position->second, predicted_display_time); - } - - imgui_ctx->set_position(imgui_node->translation, imgui_node->rotation); - imgui_ctx->new_frame(predicted_display_time); - // ImGui::ShowDemoWindow(); - - auto last_hovered = hovered_item; - hovered_item = ""; - - gui_server_list(); - - if (hovered_item != last_hovered && hovered_item != "") - { - 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); - } - - // Render the GUI to the imgui material - imgui_material->base_color_texture->image_view = imgui_ctx->render(); - imgui_material->ds_dirty = true; + return layer_views; } void scenes::lobby::render() @@ -840,7 +488,6 @@ void scenes::lobby::render() } } - if (next_scene) { if (!next_scene->alive()) @@ -866,7 +513,7 @@ void scenes::lobby::render() if (!framestate.shouldRender) { - spdlog::info("framestate.shouldRender is false"); + spdlog::debug("framestate.shouldRender is false"); session.begin_frame(); session.end_frame(framestate.predictedDisplayTime, {}); return; @@ -875,55 +522,64 @@ void scenes::lobby::render() session.begin_frame(); auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space); - assert(views.size() == swapchains.size()); + assert(views.size() == swapchains_lobby.size()); input->apply(world_space, framestate.predictedDisplayTime); draw_gui(framestate.predictedDisplayTime); - std::vector layer_view; - std::vector frames; - - layer_view.reserve(views.size()); - frames.reserve(views.size()); - - for (auto && [view, swapchain]: utils::zip(views, swapchains)) - { - int image_index = swapchain.acquire(); - swapchain.wait(); - - frames.push_back({.destination = swapchain.images()[image_index].image, - .projection = projection_matrix(view.fov), - .view = view_matrix(view.pose)}); - - layer_view.push_back({ - .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, - .pose = view.pose, - .fov = view.fov, - .subImage = { - .swapchain = swapchain, - .imageRect = { - .offset = {0, 0}, - .extent = swapchain.extent()}}, - }); - } assert(renderer); - renderer->render(*teapot, frames); + renderer->start_frame(); + auto lobby_layer_views = render_layer(views, swapchains_lobby, *renderer, *lobby_scene, {0, 0.25, 0.5, 1}); + auto controllers_layer_views = render_layer(views, swapchains_controllers, *renderer, *controllers_scene, {0, 0, 0, 0}); + renderer->end_frame(); - for (auto & swapchain: swapchains) + + + for (auto & swapchain: swapchains_lobby) swapchain.release(); - XrCompositionLayerProjection layer{ + for (auto & swapchain: swapchains_controllers) + swapchain.release(); + + swapchain_imgui.release(); + + XrCompositionLayerProjection lobby_layer{ .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION, .layerFlags = 0, .space = world_space, - .viewCount = (uint32_t)layer_view.size(), - .views = layer_view.data(), + .viewCount = (uint32_t)lobby_layer_views.size(), + .views = lobby_layer_views.data(), + }; + + XrCompositionLayerQuad imgui_layer{ + .type = XR_TYPE_COMPOSITION_LAYER_QUAD, + .layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + .space = world_space, + .eyeVisibility = XrEyeVisibility::XR_EYE_VISIBILITY_BOTH, + .subImage = { + .swapchain = swapchain_imgui, + .imageRect = { + .offset = {0, 0}, + .extent = swapchain_imgui.extent()}, + }, + .pose = imgui_ctx->pose(), + .size = {1.5, 1}, // TODO + }; + + 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(), }; std::vector layers_base; - layers_base.push_back(reinterpret_cast(&layer)); + layers_base.push_back(reinterpret_cast(&lobby_layer)); + layers_base.push_back(reinterpret_cast(&imgui_layer)); + layers_base.push_back(reinterpret_cast(&controllers_layer)); session.end_frame(framestate.predictedDisplayTime, layers_base); } @@ -934,17 +590,22 @@ void scenes::lobby::on_focused() move_gui_first_time = true; auto views = system.view_configuration_views(viewconfig); + uint32_t width = views[0].recommendedImageRectWidth; + uint32_t height = views[0].recommendedImageRectHeight; - swapchains.reserve(views.size()); - for (auto view: views) + swapchains_lobby.reserve(views.size()); + swapchains_controllers.reserve(views.size()); + for ([[maybe_unused]] auto view: views) { - swapchains.emplace_back(session, device, swapchain_format, view.recommendedImageRectWidth, view.recommendedImageRectHeight); + assert(view.recommendedImageRectWidth == width); + assert(view.recommendedImageRectHeight == height); - spdlog::info("Created lobby swapchain {}: {}x{}", swapchains.size(), swapchains.back().width(), swapchains.back().height()); + swapchains_lobby.emplace_back(session, device, swapchain_format, width, height); + swapchains_controllers.emplace_back(session, device, swapchain_format, width, height); } - uint32_t width = swapchains[0].width(); - uint32_t height = swapchains[0].height(); + spdlog::info("Created lobby swapchains: {}x{}", width, height); + vk::Extent2D output_size{width, height}; std::array depth_formats{ @@ -953,26 +614,17 @@ void scenes::lobby::on_focused() vk::Format::eD32Sfloat, }; - renderer.emplace(device, physical_device, queue, commandpool, output_size, swapchains[0].format(), depth_formats); + renderer.emplace(device, physical_device, queue, commandpool, output_size, swapchain_format, depth_formats); scene_loader loader(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material()); - teapot.emplace(); - teapot->import(loader("ground.gltf")); + lobby_scene.emplace(); + lobby_scene->import(loader("ground.gltf")); - input = input_profile("controllers/" + choose_webxr_profile() + "/profile.json", loader, *teapot); + controllers_scene.emplace(); + input = input_profile("controllers/" + choose_webxr_profile() + "/profile.json", loader, *controllers_scene); spdlog::info("Loaded input profile {}", input->id); - // Put the imgui node last so that alpha blending works correctly - teapot->import(loader("imgui.gltf")); - imgui_material = teapot->find_material("imgui"); - assert(imgui_material); - imgui_material->shader_name = "unlit"; - imgui_material->blend_enable = true; - - imgui_node = teapot->find_node("imgui"); - assert(imgui_node); - std::array imgui_inputs{ imgui_context::controller{ .aim = get_action_space("left_aim"), @@ -987,8 +639,10 @@ void scenes::lobby::on_focused() .scroll = get_action("right_scroll").first, }, }; - imgui_ctx.emplace(device, queue_family_index, queue, world_space, imgui_inputs, 1000, imgui_node->scale); - imgui_ctx->set_position(imgui_node->translation, imgui_node->rotation); + + vk::Extent2D gui_size(1500, 1000); + swapchain_imgui = xr::swapchain(session, device, swapchain_format, gui_size.width, gui_size.height); + imgui_ctx.emplace(device, queue_family_index, queue, world_space, imgui_inputs, gui_size, 1000, swapchain_format); } void scenes::lobby::on_unfocused() @@ -998,10 +652,12 @@ void scenes::lobby::on_unfocused() renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets imgui_ctx.reset(); - imgui_material.reset(); - teapot.reset(); // Must be reset before the renderer so that the descriptor sets are freed before their pools + lobby_scene.reset(); // Must be reset before the renderer so that the descriptor sets are freed before their pools + controllers_scene.reset(); renderer.reset(); - swapchains.clear(); + swapchains_lobby.clear(); + swapchains_controllers.clear(); + swapchain_imgui.reset(); } scene::meta& scenes::lobby::get_meta_scene() diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index ce1112a0..170942c0 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -73,18 +73,19 @@ class lobby : public scene_impl std::optional renderer; - std::optional teapot; + std::optional lobby_scene; + std::optional controllers_scene; std::optional input; std::optional imgui_ctx; - std::shared_ptr imgui_material; - scene_object_handle imgui_node; std::array haptic_output; std::string selected_item; std::string hovered_item; - std::vector swapchains; + std::vector swapchains_lobby; + std::vector swapchains_controllers; + xr::swapchain swapchain_imgui; vk::Format swapchain_format; void save_config(); diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp new file mode 100644 index 00000000..6b8b5e10 --- /dev/null +++ b/client/scenes/lobby_gui.cpp @@ -0,0 +1,407 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 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 "lobby.h" +#include "wivrn_packets.h" +#include "../common/version.h" +#include + + +static void CenterTextH(const std::string& text) +{ + float win_width = ImGui::GetWindowSize().x; + float text_width = ImGui::CalcTextSize(text.c_str()).x; + ImGui::SetCursorPosX((win_width - text_width) / 2); + + ImGui::Text("%s", text.c_str()); +} + +static void CenterTextHV(const std::string& text) +{ + ImVec2 size = ImGui::GetWindowSize(); + + std::vector lines = utils::split(text); + + float text_height = 0; + for(const auto& i: lines) + text_height += ImGui::CalcTextSize(i.c_str()).y; + + ImGui::SetCursorPosY((size.y - text_height) / 2); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); + for(const auto& i: lines) + { + float text_width = ImGui::CalcTextSize(i.c_str()).x; + ImGui::SetCursorPosX((size.x - text_width) / 2); + ImGui::Text("%s", i.c_str()); + } + ImGui::PopStyleVar(); +} + +void scenes::lobby::gui_connecting() +{ + const ImVec2 button_size(220, 80); + + std::string status; + if (next_scene) + status = "Waiting for video stream"; + else if (async_session.valid()) + status = async_session.get_progress(); + else if (async_error) + status = *async_error; + + std::string button_label; + + if (async_error) + button_label = "Close"; + else + button_label = "Cancel"; + + ImGui::Dummy({1000, 1}); + + + ImGui::PushFont(imgui_ctx->large_font); + CenterTextH(fmt::format("Connection to {}", server_name)); + ImGui::PopFont(); + + // ImGui::TextWrapped("%s", status.first.c_str()); + ImGui::Text("%s", status.c_str()); + + ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - button_size.x - ImGui::GetStyle().WindowPadding.x); + + if (ImGui::Button(button_label.c_str(), button_size)) + { + async_session.cancel(); + + next_scene.reset(); + + ImGui::CloseCurrentPopup(); + } + if (ImGui::IsItemHovered()) + hovered_item = "close"; +} + +void scenes::lobby::gui_add_server() +{ + const ImVec2 button_size(220, 80); + + // CenterNextWindow({1200, 900}); + + ImGui::PushFont(imgui_ctx->large_font); + CenterTextH("Add server"); + ImGui::PopFont(); + + // TODO column widths + ImGui::BeginTable("table", 2); + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("Displayed name"); + + static char buf[100]; + ImGui::TableNextColumn(); + ImGui::InputText("##Name", buf, sizeof(buf)); + if (ImGui::IsItemHovered()) + hovered_item = "name"; + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("Host name"); + + static char buf2[100]; + ImGui::TableNextColumn(); + ImGui::InputText("##Hostname", buf2, sizeof(buf2)); + if (ImGui::IsItemHovered()) + hovered_item = "hostname"; + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::Text("Port"); + + static int port; + ImGui::TableNextColumn(); + ImGui::InputInt("##Port", &port); + if (ImGui::IsItemHovered()) + hovered_item = "port"; + + ImGui::EndTable(); + + // TODO virtual keyboard + // See https://github.com/qt/qtvirtualkeyboard/tree/dev/src/layouts/fallback + // https://github.com/qt/qtvirtualkeyboard/blob/dev/src/layouts/fr_FR/main.qml + // https://doc.qt.io/qt-6/qtvirtualkeyboard-layouts.html + + gui_keyboard(ImVec2(1000, 280)); + + auto top_left = ImGui::GetWindowContentRegionMin(); + auto bottom_right = ImGui::GetWindowContentRegionMax(); + + ImGui::SetCursorPosX(top_left.x); + if (ImGui::Button("Cancel", button_size)) + ImGui::CloseCurrentPopup(); + if (ImGui::IsItemHovered()) + hovered_item = "cancel"; + + ImGui::SameLine(bottom_right.x - button_size.x); + + if (ImGui::Button("Save", button_size)) + { + ImGui::CloseCurrentPopup(); + + server_data data + { + .manual = true, + .service = { + .name = add_server_window_prettyname, + .hostname = add_server_window_hostname, + .port = add_server_window_port, + }, + }; + + servers.emplace("manual-" + data.service.name, data); + save_config(); + + } + if (ImGui::IsItemHovered()) + hovered_item = "save"; +} + +void scenes::lobby::gui_server_list() +{ + // Build an index of the cookies sorted by server name + std::multimap sorted_cookies; + for(auto&& [cookie, data]: servers) + { + sorted_cookies.emplace(data.service.name, cookie); + } + + const ImVec2 button_size(220, 80); + const float list_item_height = 100; + auto& style = ImGui::GetStyle(); + + ImGui::SetNextWindowPos({0, 0}); + ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size); + ImGui::Begin("WiVRn", nullptr, + ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove); + + ImGui::PushFont(imgui_ctx->large_font); + CenterTextH(std::string("WiVRn ") + xrt::drivers::wivrn::git_version); + ImGui::PopFont(); + + std::string cookie_to_remove; + + float list_box_height = ImGui::GetWindowContentRegionMax().y - button_size.y - style.WindowPadding.y - ImGui::GetCursorPosY(); + + if (ImGui::BeginListBox("##detected servers", ImVec2(-FLT_MIN, list_box_height))) + { + if (sorted_cookies.empty()) + { + ImGui::PushFont(imgui_ctx->large_font); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 0.5)); + CenterTextHV("Start a WiVRn server on your\nlocal network"); + ImGui::PopStyleColor(); + ImGui::PopFont(); + } + + auto pos = ImGui::GetCursorPos(); + + ImGui::PushStyleColor(ImGuiCol_Header, 0); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, 0); + ImGui::PushStyleColor(ImGuiCol_HeaderActive, 0); + for(const auto& [name, cookie]: sorted_cookies) + { + server_data& data = servers.at(cookie); + bool is_selected = (cookie == selected_item); + + ImGui::SetCursorPos(pos); + + ImGui::SetNextItemAllowOverlap(); + + // TODO custom widget + if (ImGui::Selectable(("##" + cookie).c_str(), is_selected, ImGuiSelectableFlags_None, ImVec2(0, list_item_height))) + selected_item = cookie; + + ImGui::SetCursorPos(ImVec2(pos.x, pos.y)); + ImGui::Text("%s", name.c_str()); + + if (!data.manual) + { + ImGui::SetCursorPos(ImVec2(pos.x, pos.y + 50)); + 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; + ImGui::PopStyleColor(); + } + + // TODO + // if (ImGui::IsItemHovered()) + // { + // ImGui::SetTooltip("Tooltip"); + // } + + ImVec2 button_position(ImGui::GetWindowContentRegionMax().x + style.FramePadding.x, pos.y + (list_item_height - button_size.y) / 2); + + button_position.x -= button_size.x + style.WindowPadding.x; + ImGui::SetCursorPos(button_position); + + bool enable_connect_button = data.visible || data.manual; + ImGui::BeginDisabled(!enable_connect_button); + if (enable_connect_button) + { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.8f, 0.3f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.8f, 0.3f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 1.0f, 0.2f, 1.00f)); + } + else + { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.4f, 0.3f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.4f, 0.3f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.5f, 0.2f, 1.00f)); + } + if (ImGui::Button(("Connect##" + cookie).c_str(), button_size)) + { + connect(data); + ImGui::OpenPopup("connecting"); + } + + if (ImGui::IsItemHovered()) + hovered_item = "connect " + cookie; + + ImGui::PopStyleColor(3); + ImGui::EndDisabled(); + + button_position.x -= button_size.x + style.WindowPadding.x; + if (data.manual) + { + ImGui::SetCursorPos(button_position); + 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(("Remove##" + cookie).c_str(), button_size)) + cookie_to_remove = cookie; + + if (ImGui::IsItemHovered()) + hovered_item = "remove " + cookie; + + ImGui::PopStyleColor(3); + } + + pos.y += 120; + } + ImGui::PopStyleColor(3); + + if (cookie_to_remove != "") + { + servers.erase(cookie_to_remove); + save_config(); + } + + ImGui::EndListBox(); + } + + auto top_left = ImGui::GetWindowContentRegionMin(); + auto bottom_right = ImGui::GetWindowContentRegionMax(); + +#ifndef NDEBUG + ImGui::SetCursorPos(ImVec2(top_left.x, bottom_right.y - button_size.y)); + if (ImGui::Button("Add server", button_size)) + { + ImGui::OpenPopup("add_server"); + strcpy(add_server_window_prettyname, ""); + strcpy(add_server_window_hostname, ""); + add_server_window_port = xrt::drivers::wivrn::default_port; + } + + if (ImGui::IsItemHovered()) + { + hovered_item = "add"; + ImGui::SetTooltip("TODO"); + } +#endif + + ImGui::SetCursorPos(ImVec2(bottom_right.x - button_size.x, bottom_right.y - button_size.y)); + if (ImGui::Button("Exit", button_size)) + application::pop_scene(); + + if (ImGui::IsItemHovered()) + hovered_item = "exit"; + + if (ImGui::BeginPopupModal("add_server", nullptr, + ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove)) + { + gui_add_server(); + ImGui::EndPopup(); + } + + // Check if an automatic connection has started + if ((async_session.valid() || next_scene) && !ImGui::IsPopupOpen("connecting")) + ImGui::OpenPopup("connecting"); + + if (ImGui::BeginPopupModal("connecting", nullptr, + ImGuiWindowFlags_NoTitleBar | + ImGuiWindowFlags_NoResize | + ImGuiWindowFlags_NoMove)) + { + gui_connecting(); + ImGui::EndPopup(); + } + + ImGui::End(); +} + +void scenes::lobby::draw_gui(XrTime predicted_display_time) +{ + 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) + { + move_gui(head_position->first, head_position->second, predicted_display_time); + } + + imgui_ctx->new_frame(predicted_display_time); + // ImGui::ShowDemoWindow(); + + auto last_hovered = hovered_item; + hovered_item = ""; + + gui_server_list(); + + if (hovered_item != last_hovered && hovered_item != "") + { + 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); + } + + // Render the GUI to the imgui material + // imgui_material->base_color_texture->image_view = imgui_ctx->render(); + // imgui_material->ds_dirty = true; + + imgui_ctx->render(swapchain_imgui.images()[image_index].image); +} diff --git a/client/utils/handle.h b/client/utils/handle.h index 685c3bac..3f3cc1cc 100644 --- a/client/utils/handle.h +++ b/client/utils/handle.h @@ -66,6 +66,11 @@ public: id = null_value; return r; } + + void reset() + { + *this = handle{}; + } }; template