clang-format

This commit is contained in:
Guillaume Meunier
2024-03-30 17:00:34 +01:00
parent bb660cfb3f
commit 9cceaac648
122 changed files with 2904 additions and 2783 deletions
+9 -11
View File
@@ -59,29 +59,27 @@ hand_model::hand_model(const std::filesystem::path & gltf_path, scene_loader & l
// clang-format on
}
void hand_model::apply(const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>>& joints_location)
void hand_model::apply(const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints_location)
{
if (joints_location)
{
root_node->visible = true;
for(auto&& [joint, loc]: utils::zip(joints, *joints_location))
for (auto && [joint, loc]: utils::zip(joints, *joints_location))
{
if (!joint)
continue;
joint->position = {
loc.first.pose.position.x,
loc.first.pose.position.y,
loc.first.pose.position.z
};
loc.first.pose.position.x,
loc.first.pose.position.y,
loc.first.pose.position.z};
joint->orientation = {
loc.first.pose.orientation.w,
loc.first.pose.orientation.x,
loc.first.pose.orientation.y,
loc.first.pose.orientation.z
};
loc.first.pose.orientation.w,
loc.first.pose.orientation.x,
loc.first.pose.orientation.y,
loc.first.pose.orientation.z};
}
}
else
+2 -2
View File
@@ -27,7 +27,7 @@ struct hand_model
node_handle root_node;
std::vector<node_handle> joints;
hand_model(const std::filesystem::path & gltf_path, scene_loader& loader, scene_data& scene);
hand_model(const std::filesystem::path & gltf_path, scene_loader & loader, scene_data & scene);
void apply(const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>>& joints);
void apply(const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints);
};
+11 -12
View File
@@ -20,13 +20,13 @@
#include "application.h"
#include "asset.h"
#include <glm/gtc/quaternion.hpp>
#include <magic_enum.hpp>
#include <simdjson.h>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <glm/gtc/quaternion.hpp>
namespace
{
@@ -204,7 +204,7 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
}
}
for(auto&& [layout, model]: models)
for (auto && [layout, model]: models)
{
node_handle root_node = scene.new_node();
root_node->name = layout;
@@ -222,7 +222,7 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
scene.import(std::move(model), root_node);
}
for(auto& json_response: json_responses)
for (auto & json_response: json_responses)
{
std::string action_path = "/user/hand/" + json_response.layout + json_response.component_subpath;
@@ -236,11 +236,11 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
continue;
}
auto& response = responses.emplace_back();
auto & response = responses.emplace_back();
response.action = action.first;
response.type = action.second;
switch(json_response.property)
switch (json_response.property)
{
case component_property::button:
case component_property::state:
@@ -262,7 +262,7 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l
}
node_handle controller_root_node;
for(auto&& [i, j]: model_handles)
for (auto && [i, j]: model_handles)
{
if (j->name == json_response.layout)
{
@@ -366,11 +366,11 @@ void input_profile::apply(XrSpace world_space, XrTime predicted_display_time, bo
{
float scaled_value = *value * response.scale + response.bias;
if ((scaled_value < 0) || (scaled_value > 1))
if ((scaled_value < 0) || (scaled_value > 1))
{
std::string full_name = response.target.node->name;
for(auto i = response.target.node; i; i = i.parent())
for (auto i = response.target.node; i; i = i.parent())
{
full_name = i->name + "/" + full_name;
}
@@ -378,11 +378,10 @@ void input_profile::apply(XrSpace world_space, XrTime predicted_display_time, bo
spdlog::warn("Out of range value {} (scaled to {}) for node {}", *value, scaled_value, full_name);
}
std::visit([&](auto& transform)
{
std::visit([&](auto & transform) {
apply_visual_response(response.target.node, transform, scaled_value);
}, response.target.state);
},
response.target.state);
}
}
}
+4 -4
View File
@@ -19,10 +19,10 @@
#pragma once
#include <filesystem>
#include <variant>
#include <render/scene_data.h>
#include <openxr/openxr.h>
#include <glm/glm.hpp>
#include <render/scene_data.h>
#include <variant>
#include <openxr/openxr.h>
struct input_profile
{
@@ -60,7 +60,7 @@ struct input_profile
std::vector<visual_response> responses;
std::vector<std::pair<XrSpace, node_handle>> model_handles;
input_profile(const std::filesystem::path& json_profile, scene_loader& loader, scene_data& scene);
input_profile(const std::filesystem::path & json_profile, scene_loader & loader, scene_data & scene);
// application::poll_actions() must have been called before
void apply(XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right);
+191 -186
View File
@@ -18,38 +18,38 @@
*/
#include "lobby.h"
#include "version.h"
#include "application.h"
#include "glm/geometric.hpp"
#include "hardware.h"
#include "imgui.h"
#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 "utils/contains.h"
#include "version.h"
#include "wivrn_client.h"
#include "xr/passthrough.h"
#include <glm/gtc/matrix_access.hpp>
#include "wivrn_discover.h"
#include <cstdint>
#include <fstream>
#include <glm/gtc/quaternion.hpp>
#include <ios>
#include <magic_enum.hpp>
#include <simdjson.h>
#include <spdlog/spdlog.h>
#include <sstream>
#include <string>
#include <utils/ranges.h>
#include <vulkan/vulkan_raii.hpp>
#include <simdjson.h>
#include <fstream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
static const std::string discover_service = "_wivrn._tcp.local.";
static bool force_autoconnect = false;
@@ -68,7 +68,7 @@ static std::string choose_webxr_profile()
return controller;
#endif
switch(guess_model())
switch (guess_model())
{
case model::oculus_quest:
return "oculus-touch-v2";
@@ -92,16 +92,16 @@ static std::string choose_webxr_profile()
__builtin_unreachable();
}
static std::string json_string(const std::string& in)
static std::string json_string(const std::string & in)
{
std::string out;
out.reserve(in.size() + 2);
out += '"';
for(char c: in)
for (char c: in)
{
switch(c)
switch (c)
{
case '\b':
out += "\\b";
@@ -143,10 +143,9 @@ static std::string json_string(const std::string& in)
}
static const std::array supported_formats =
{
vk::Format::eR8G8B8A8Srgb,
vk::Format::eB8G8R8A8Srgb
};
{
vk::Format::eR8G8B8A8Srgb,
vk::Format::eB8G8R8A8Srgb};
void scenes::lobby::move_gui(glm::vec3 position, glm::quat orientation, XrTime predicted_display_time)
{
@@ -175,7 +174,7 @@ void scenes::lobby::move_gui(glm::vec3 position, glm::quat orientation, XrTime p
gui_yaw += gui_yaw_error;
imgui_ctx->position() += gui_position_error;
imgui_ctx->orientation() = glm::quat(cos(gui_yaw/2), 0, sin(gui_yaw/2), 0) * glm::quat(cos(gui_target_pitch/2), sin(gui_target_pitch/2), 0, 0);
imgui_ctx->orientation() = glm::quat(cos(gui_yaw / 2), 0, sin(gui_yaw / 2), 0) * glm::quat(cos(gui_target_pitch / 2), sin(gui_target_pitch / 2), 0, 0);
}
}
@@ -191,21 +190,20 @@ scenes::lobby::lobby()
{
simdjson::dom::parser parser;
simdjson::dom::element root = parser.load(application::get_config_path() / "client.json");
for(simdjson::dom::object i: simdjson::dom::array(root["servers"]))
for (simdjson::dom::object i: simdjson::dom::array(root["servers"]))
{
server_data data{
.autoconnect = i["autoconnect"].get_bool(),
.manual = i["manual"].get_bool(),
.visible = false,
.compatible = true,
.service = {
.name = (std::string)i["pretty_name"],
.hostname = (std::string)i["hostname"],
.port = (int)i["port"].get_int64(),
.txt = {{"cookie", (std::string)i["cookie"]}}
.autoconnect = i["autoconnect"].get_bool(),
.manual = i["manual"].get_bool(),
.visible = false,
.compatible = true,
.service = {
.name = (std::string)i["pretty_name"],
.hostname = (std::string)i["hostname"],
.port = (int)i["port"].get_int64(),
.txt = {{"cookie", (std::string)i["cookie"]}}
}
};
}};
servers.emplace(data.service.txt["cookie"], data);
}
@@ -228,7 +226,7 @@ scenes::lobby::lobby()
if (passthrough.is_bool())
passthrough_enabled = passthrough.get_bool();
}
catch(std::exception& e)
catch (std::exception & e)
{
spdlog::warn("Cannot read configuration: {}", e.what());
servers.clear();
@@ -236,7 +234,7 @@ scenes::lobby::lobby()
}
spdlog::info("{} known server(s):", servers.size());
for(auto& i: servers)
for (auto & i: servers)
{
spdlog::info(" {}", i.second.service.name);
}
@@ -270,7 +268,7 @@ void scenes::lobby::save_config()
{
std::stringstream ss;
for (auto& [cookie, server_data]: servers)
for (auto & [cookie, server_data]: servers)
{
if (server_data.autoconnect || server_data.manual)
{
@@ -294,20 +292,20 @@ void scenes::lobby::save_config()
json << "{\"servers\":[" << servers_str << "],"
<< "\"show_performance_metrics\":" << std::boolalpha << show_performance_metrics;
if (preferred_refresh_rate != 0.)
json << ",\"preferred_refresh_rate\":" << preferred_refresh_rate ;
json << ",\"preferred_refresh_rate\":" << preferred_refresh_rate;
json << ",\"microphone\":" << std::boolalpha << microphone;
json << ",\"passthrough_enabled\":" << std::boolalpha << passthrough_enabled;
json << "}";
}
static std::string ip_address_to_string(const in_addr& addr)
static std::string ip_address_to_string(const in_addr & addr)
{
char buf[100];
inet_ntop(AF_INET, &addr, buf, sizeof(buf));
return buf;
}
static std::string ip_address_to_string(const in6_addr& addr)
static std::string ip_address_to_string(const in6_addr & addr)
{
char buf[100];
inet_ntop(AF_INET6, &addr, buf, sizeof(buf));
@@ -323,7 +321,7 @@ std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service servic
spdlog::debug("Client protocol version: {}", protocol_string);
spdlog::debug("Server TXT:");
for(auto& [i,j]: service.txt)
for (auto & [i, j]: service.txt)
{
spdlog::debug(" {}=\"{}\"", i, j);
}
@@ -339,11 +337,10 @@ std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service servic
// Only the automatically discovered servers already have their IP addresses available
if (manual_connection)
{
addrinfo hint
{
.ai_flags = AI_ADDRCONFIG,
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM,
addrinfo hint{
.ai_flags = AI_ADDRCONFIG,
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM,
};
addrinfo * addresses;
if (int err = getaddrinfo(service.hostname.c_str(), nullptr, &hint, &addresses))
@@ -352,15 +349,15 @@ std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service servic
throw std::runtime_error("Cannot resolve hostname: " + std::string(gai_strerror(err)));
}
for(auto i = addresses; i; i = i->ai_next)
for (auto i = addresses; i; i = i->ai_next)
{
switch (i->ai_family)
{
case AF_INET:
service.addresses.push_back(((sockaddr_in*)i->ai_addr)->sin_addr);
service.addresses.push_back(((sockaddr_in *)i->ai_addr)->sin_addr);
break;
case AF_INET6:
service.addresses.push_back(((sockaddr_in6*)i->ai_addr)->sin6_addr);
service.addresses.push_back(((sockaddr_in6 *)i->ai_addr)->sin6_addr);
break;
}
}
@@ -372,7 +369,8 @@ std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service servic
{
std::string address_string = std::visit([](auto & address) {
return ip_address_to_string(address);
}, address);
},
address);
try
{
@@ -381,7 +379,7 @@ std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service servic
return std::visit([port = service.port](auto & address) {
return std::make_unique<wivrn_session>(address, port);
},
address);
address);
}
catch (std::exception & e)
{
@@ -434,7 +432,7 @@ void scenes::lobby::update_server_list()
std::vector<wivrn_discover::service> discovered_services = discover->get_services();
// TODO: only if discovered_services changed
for(auto& [cookie, data]: servers)
for (auto & [cookie, data]: servers)
{
data.visible = false;
}
@@ -442,7 +440,7 @@ void scenes::lobby::update_server_list()
char protocol_string[17];
sprintf(protocol_string, "%016lx", xrt::drivers::wivrn::protocol_version);
for(auto& service: discovered_services)
for (auto & service: discovered_services)
{
std::string cookie;
bool compatible = true;
@@ -467,13 +465,15 @@ void scenes::lobby::update_server_list()
if (server == servers.end())
{
// Newly discovered server: add it to the list
servers.emplace(cookie, server_data{
.autoconnect = false,
.manual = false,
.visible = true,
.compatible = compatible,
.service = service
});
servers.emplace(
cookie,
server_data{
.autoconnect = false,
.manual = false,
.visible = true,
.compatible = compatible,
.service = service,
});
}
else
{
@@ -484,19 +484,21 @@ void scenes::lobby::update_server_list()
}
}
void scenes::lobby::connect(server_data& data)
void scenes::lobby::connect(server_data & data)
{
server_name = data.service.name;
async_error.reset();
async_session = utils::async<std::unique_ptr<wivrn_session>, std::string>([](auto token, wivrn_discover::service service, bool manual)
{
token.set_progress("Waiting for connection");
return connect_to_session(service, manual);
}, data.service, data.manual);
async_session = utils::async<std::unique_ptr<wivrn_session>, std::string>(
[](auto token, wivrn_discover::service service, bool manual) {
token.set_progress("Waiting for connection");
return connect_to_session(service, manual);
},
data.service,
data.manual);
}
static std::vector<XrCompositionLayerProjectionView> render_layer(std::vector<XrView>& views, std::vector<xr::swapchain>& swapchains, scene_renderer& renderer, scene_data& data, const std::array<float, 4>& clear_color)
static std::vector<XrCompositionLayerProjectionView> render_layer(std::vector<XrView> & views, std::vector<xr::swapchain> & swapchains, scene_renderer & renderer, scene_data & data, const std::array<float, 4> & clear_color)
{
std::vector<scene_renderer::frame_info> frames;
frames.reserve(views.size());
@@ -509,19 +511,23 @@ static std::vector<XrCompositionLayerProjectionView> render_layer(std::vector<Xr
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)});
frames.push_back({
.destination = swapchain.images()[image_index].image,
.projection = projection_matrix(view.fov),
.view = view_matrix(view.pose),
});
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()}},
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW,
.pose = view.pose,
.fov = view.fov,
.subImage = {
.swapchain = swapchain,
.imageRect = {
.offset = {0, 0},
.extent = swapchain.extent(),
},
},
});
}
@@ -542,7 +548,7 @@ void scenes::lobby::render(XrTime predicted_display_time, bool should_render)
async_session.reset();
}
catch(std::exception& e)
catch (std::exception & e)
{
spdlog::error("Error connecting to server: {}", e.what());
async_session.cancel();
@@ -563,12 +569,10 @@ void scenes::lobby::render(XrTime predicted_display_time, bool should_render)
imgui_ctx->set_current();
if (!async_session.valid() && !next_scene && !ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopup))
{
for(auto&& [cookie, data]: servers)
for (auto && [cookie, data]: servers)
{
if (data.visible && (data.autoconnect || force_autoconnect) && data.compatible)
{
connect(data);
}
}
}
@@ -591,7 +595,7 @@ void scenes::lobby::render(XrTime predicted_display_time, bool should_render)
{
if (left_hand)
{
auto& hand = application::get_left_hand();
auto & hand = application::get_left_hand();
auto joints = hand.locate(world_space, predicted_display_time);
left_hand->apply(joints);
@@ -601,7 +605,7 @@ void scenes::lobby::render(XrTime predicted_display_time, bool should_render)
if (right_hand)
{
auto& hand = application::get_right_hand();
auto & hand = application::get_right_hand();
auto joints = hand.locate(world_space, predicted_display_time);
right_hand->apply(joints);
@@ -653,9 +657,11 @@ void scenes::lobby::render(XrTime predicted_display_time, bool should_render)
if (passthrough_enabled)
{
std::visit([&](auto& p){
layers_base.push_back(p.layer());
}, passthrough);
std::visit(
[&](auto & p) {
layers_base.push_back(p.layer());
},
passthrough);
}
else
{
@@ -708,25 +714,25 @@ void scenes::lobby::on_focused()
if (application::get_hand_tracking_supported())
{
left_hand.emplace( "left-hand.glb", loader, *controllers_scene);
left_hand.emplace("left-hand.glb", loader, *controllers_scene);
right_hand.emplace("right-hand.glb", loader, *controllers_scene);
}
std::array imgui_inputs{
imgui_context::controller{
.aim = get_action_space("left_aim"),
.trigger = get_action("left_trigger").first,
.squeeze = get_action("left_squeeze").first,
.scroll = get_action("left_scroll").first,
.hand = application::get_left_hand(),
},
imgui_context::controller{
.aim = get_action_space("right_aim"),
.trigger = get_action("right_trigger").first,
.squeeze = get_action("right_squeeze").first,
.scroll = get_action("right_scroll").first,
.hand = application::get_right_hand(),
},
imgui_context::controller{
.aim = get_action_space("left_aim"),
.trigger = get_action("left_trigger").first,
.squeeze = get_action("left_squeeze").first,
.scroll = get_action("left_scroll").first,
.hand = application::get_left_hand(),
},
imgui_context::controller{
.aim = get_action_space("right_aim"),
.trigger = get_action("right_trigger").first,
.squeeze = get_action("right_squeeze").first,
.scroll = get_action("right_scroll").first,
.hand = application::get_right_hand(),
},
};
swapchain_imgui = xr::swapchain(session, device, swapchain_format, 1500, 1000);
@@ -736,7 +742,7 @@ void scenes::lobby::on_focused()
{
about_picture = imgui_ctx->load_texture("wivrn.ktx2");
}
catch(...)
catch (...)
{
about_picture = imgui_ctx->load_texture("wivrn.png");
}
@@ -752,7 +758,7 @@ void scenes::lobby::on_focused()
passthrough.emplace<xr::passthrough_htc>(instance, session);
}
std::visit([](auto& p) {p.start();}, passthrough);
std::visit([](auto & p) { p.start(); }, passthrough);
}
}
@@ -784,96 +790,95 @@ void scenes::lobby::on_session_state_changed(XrSessionState state)
discover.reset();
}
scene::meta& scenes::lobby::get_meta_scene()
scene::meta & scenes::lobby::get_meta_scene()
{
static meta m{
.name = "Lobby",
.actions = {
{"left_aim", XR_ACTION_TYPE_POSE_INPUT},
{"left_trigger", XR_ACTION_TYPE_FLOAT_INPUT},
{"left_squeeze", XR_ACTION_TYPE_FLOAT_INPUT},
{"left_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT},
{"left_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"right_aim", XR_ACTION_TYPE_POSE_INPUT},
{"right_trigger", XR_ACTION_TYPE_FLOAT_INPUT},
{"right_squeeze", XR_ACTION_TYPE_FLOAT_INPUT},
{"right_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT},
{"right_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
},
.bindings = {
suggested_binding{
"/interaction_profiles/oculus/touch_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
}
},
suggested_binding{
"/interaction_profiles/bytedance/pico_neo3_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
}
},
suggested_binding{
"/interaction_profiles/bytedance/pico4_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
}
},
suggested_binding{
"/interaction_profiles/htc/vive_focus3_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
}
},
suggested_binding{
"/interaction_profiles/khr/simple_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/select/click"},
{"left_squeeze", "/user/hand/left/input/menu/click"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/select/click"},
{"right_squeeze", "/user/hand/right/input/menu/click"},
}
},
}
};
.name = "Lobby",
.actions = {
{"left_aim", XR_ACTION_TYPE_POSE_INPUT},
{"left_trigger", XR_ACTION_TYPE_FLOAT_INPUT},
{"left_squeeze", XR_ACTION_TYPE_FLOAT_INPUT},
{"left_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT},
{"left_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
{"right_aim", XR_ACTION_TYPE_POSE_INPUT},
{"right_trigger", XR_ACTION_TYPE_FLOAT_INPUT},
{"right_squeeze", XR_ACTION_TYPE_FLOAT_INPUT},
{"right_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT},
{"right_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
},
.bindings = {
suggested_binding{
"/interaction_profiles/oculus/touch_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
},
},
suggested_binding{
"/interaction_profiles/bytedance/pico_neo3_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
},
},
suggested_binding{
"/interaction_profiles/bytedance/pico4_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
},
},
suggested_binding{
"/interaction_profiles/htc/vive_focus3_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/trigger/value"},
{"left_squeeze", "/user/hand/left/input/squeeze/value"},
{"left_scroll", "/user/hand/left/input/thumbstick"},
{"left_haptic", "/user/hand/left/output/haptic"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/trigger/value"},
{"right_squeeze", "/user/hand/right/input/squeeze/value"},
{"right_scroll", "/user/hand/right/input/thumbstick"},
{"right_haptic", "/user/hand/right/output/haptic"},
},
},
suggested_binding{
"/interaction_profiles/khr/simple_controller",
{
{"left_aim", "/user/hand/left/input/aim/pose"},
{"left_trigger", "/user/hand/left/input/select/click"},
{"left_squeeze", "/user/hand/left/input/menu/click"},
{"right_aim", "/user/hand/right/input/aim/pose"},
{"right_trigger", "/user/hand/right/input/select/click"},
{"right_squeeze", "/user/hand/right/input/menu/click"},
},
},
}};
return m;
}
+6 -7
View File
@@ -21,18 +21,18 @@
#include "render/scene_data.h"
#include "scene.h"
#include <vulkan/vulkan_raii.hpp>
#include "scenes/hand_model.h"
#include "wivrn_discover.h"
#include <vulkan/vulkan_raii.hpp>
#include "xr/passthrough.h"
#include <map>
#include <optional>
#include <vector>
#include <map>
#include "render/scene_renderer.h"
#include "render/imgui_impl.h"
#include "input_profile.h"
#include "render/imgui_impl.h"
#include "render/scene_renderer.h"
#include "utils/async.h"
class wivrn_session;
@@ -73,7 +73,6 @@ class lobby : public scene_impl<lobby>
std::shared_ptr<stream> next_scene;
std::string server_name;
std::optional<scene_renderer> renderer;
std::optional<scene_data> lobby_scene;
std::optional<scene_data> controllers_scene;
@@ -130,7 +129,7 @@ class lobby : public scene_impl<lobby>
void vibrate_on_hover();
void connect(server_data& data);
void connect(server_data & data);
public:
virtual ~lobby();
@@ -141,6 +140,6 @@ public:
void on_focused() override;
void on_session_state_changed(XrSessionState state) override;
static meta& get_meta_scene();
static meta & get_meta_scene();
};
} // namespace scenes
+43 -56
View File
@@ -21,11 +21,11 @@
#include "application.h"
#include "imgui.h"
#include "implot.h"
#include "imgui_internal.h"
#include "implot.h"
#include "lobby.h"
#include "version.h"
#include "stream.h"
#include "version.h"
#include <spdlog/fmt/fmt.h>
#include <utils/strings.h>
@@ -35,7 +35,7 @@
#include "IconsFontAwesome6.h"
static void CenterTextH(const std::string& text)
static void CenterTextH(const std::string & text)
{
float win_width = ImGui::GetWindowSize().x;
float text_width = ImGui::CalcTextSize(text.c_str()).x;
@@ -44,20 +44,20 @@ static void CenterTextH(const std::string& text)
ImGui::Text("%s", text.c_str());
}
static void CenterTextHV(const std::string& text)
static void CenterTextHV(const std::string & text)
{
ImVec2 size = ImGui::GetWindowSize();
std::vector<std::string> lines = utils::split(text);
float text_height = 0;
for(const auto& i: lines)
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)
for (const auto & i: lines)
{
float text_width = ImGui::CalcTextSize(i.c_str()).x;
ImGui::SetCursorPosX((size.x - text_width) / 2);
@@ -98,7 +98,6 @@ void scenes::lobby::gui_connecting()
ImGui::Dummy({1000, 1});
ImGui::PushFont(imgui_ctx->large_font);
CenterTextH(fmt::format("Connection to {}", server_name));
ImGui::PopFont();
@@ -175,19 +174,17 @@ void scenes::lobby::gui_add_server()
if (ImGui::Button("Save", button_size))
{
current_tab = tab::server_list;
server_data data
{
.manual = true,
.service = {
.name = add_server_window_prettyname,
.hostname = add_server_window_hostname,
.port = add_server_window_port,
},
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();
}
vibrate_on_hover();
}
@@ -196,14 +193,14 @@ void scenes::lobby::gui_server_list()
{
// Build an index of the cookies sorted by server name
std::multimap<std::string, std::string> sorted_cookies;
for(auto&& [cookie, data]: servers)
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();
auto & style = ImGui::GetStyle();
std::string cookie_to_remove;
if (sorted_cookies.empty())
@@ -220,9 +217,9 @@ void scenes::lobby::gui_server_list()
ImGui::PushStyleColor(ImGuiCol_Header, 0);
ImGui::PushStyleColor(ImGuiCol_HeaderHovered, 0);
ImGui::PushStyleColor(ImGuiCol_HeaderActive, 0);
for(const auto& [name, cookie]: sorted_cookies)
for (const auto & [name, cookie]: sorted_cookies)
{
server_data& data = servers.at(cookie);
server_data & data = servers.at(cookie);
bool is_selected = (cookie == selected_item);
ImGui::SetCursorPos(pos);
@@ -247,7 +244,7 @@ void scenes::lobby::gui_server_list()
// TODO
// if (ImGui::IsItemHovered())
// {
// ImGui::SetTooltip("Tooltip");
// ImGui::SetTooltip("Tooltip");
// }
ImVec2 button_position(ImGui::GetWindowContentRegionMax().x - style.WindowPadding.x - 20, pos.y + (list_item_height - button_size.y) / 2);
@@ -259,15 +256,15 @@ void scenes::lobby::gui_server_list()
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_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));
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_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));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.5f, 0.2f, 1.00f));
}
if (ImGui::Button(("Connect##" + cookie).c_str(), button_size))
{
@@ -291,9 +288,9 @@ void scenes::lobby::gui_server_list()
if (data.manual)
{
ImGui::SetCursorPos(button_position);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f));
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));
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;
@@ -316,13 +313,10 @@ void scenes::lobby::gui_server_list()
if ((async_session.valid() || next_scene) && !ImGui::IsPopupOpen("connecting"))
ImGui::OpenPopup("connecting");
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(20,20));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(20, 20));
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 10);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 2);
if (ImGui::BeginPopupModal("connecting", nullptr,
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove))
if (ImGui::BeginPopupModal("connecting", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove))
{
gui_connecting();
ImGui::EndPopup();
@@ -404,11 +398,9 @@ void scenes::lobby::gui_settings()
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
};
win_width / 2 - style.ItemSpacing.x / 2,
win_height / 2};
static std::array<float, 300> cpu_time;
static std::array<float, 300> gpu_time;
@@ -417,7 +409,6 @@ void scenes::lobby::gui_settings()
float min_v = 0;
float max_v = 20;
cpu_time[offset] = application::get_cpu_time().count() * 1.0e-6;
gpu_time[offset] = renderer->get_gpu_time() * 1'000;
offset = (offset + 1) % cpu_time.size();
@@ -428,7 +419,7 @@ void scenes::lobby::gui_settings()
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))
if (ImPlot::BeginPlot("CPU time", plot_size, ImPlotFlags_CanvasOnly | ImPlotFlags_NoChild))
{
auto col = ImPlot::GetColormapColor(0);
@@ -442,11 +433,11 @@ void scenes::lobby::gui_settings()
ImGui::SameLine();
if (ImPlot::BeginPlot("GPU time", plot_size, ImPlotFlags_CanvasOnly|ImPlotFlags_NoChild))
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::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);
@@ -512,7 +503,7 @@ static bool RadioButtonWithoutCheckBox(const char * label, bool active, ImVec2 s
return pressed;
}
template<typename T>
template <typename T>
static bool RadioButtonWithoutCheckBox(const char * label, T * v, T v_button, ImVec2 size_arg)
{
const bool pressed = RadioButtonWithoutCheckBox(label, *v == v_button, size_arg);
@@ -524,8 +515,8 @@ static bool RadioButtonWithoutCheckBox(const char * label, T * v, T v_button, Im
static void ScrollWhenDraggingOnVoid(ImVec2 delta)
{
// https://github.com/ocornut/imgui/issues/3379#issuecomment-1678718752
ImGuiContext& g = *ImGui::GetCurrentContext();
ImGuiWindow* window = g.CurrentWindow;
ImGuiContext & g = *ImGui::GetCurrentContext();
ImGuiWindow * window = g.CurrentWindow;
bool hovered = false;
bool held = false;
ImGuiID id = window->GetID("##scrolldraggingoverlay");
@@ -567,10 +558,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time)
// ImGui::SetNextWindowPos({0, 0});
// ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size);
ImGui::Begin("WiVRn", nullptr,
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove);
ImGui::Begin("WiVRn", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
ImGui::SetCursorPos({MinTabWidth + 20, 0});
@@ -579,7 +567,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time)
ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0));
ImGui::SetCursorPosY(20);
switch(current_tab)
switch (current_tab)
{
case tab::server_list:
gui_server_list();
@@ -607,7 +595,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time)
ImGui::SetScrollY(0);
}
ImGui::Dummy(ImVec2(0,20));
ImGui::Dummy(ImVec2(0, 20));
ImVec2 mouse_delta = ImGui::GetIO().MouseDelta;
ScrollWhenDraggingOnVoid(ImVec2(0.0f, -mouse_delta.y));
@@ -622,21 +610,20 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time)
static float TabWidth = MinTabWidth;
ImGui::BeginChild("Tabs", {TabWidth, ImGui::GetContentRegionMax().y - ImGui::GetWindowContentRegionMin().y});
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10,10));
RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " Server list", &current_tab, tab::server_list, {TabWidth, 0});
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 10));
RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " Server list", &current_tab, tab::server_list, {TabWidth, 0});
vibrate_on_hover();
RadioButtonWithoutCheckBox(ICON_FA_GEARS " Settings", &current_tab, tab::settings, {TabWidth, 0});
RadioButtonWithoutCheckBox(ICON_FA_GEARS " Settings", &current_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);
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", &current_tab, tab::about, {TabWidth, 0});
vibrate_on_hover();
RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " Exit", &current_tab, tab::exit, {TabWidth, 0});
RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " Exit", &current_tab, tab::exit, {TabWidth, 0});
vibrate_on_hover();
if (!ImGui::IsMouseDown(ImGuiMouseButton_Left))
{
if (ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows))
@@ -651,7 +638,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time)
ImGui::PopStyleColor(); // ImGuiCol_ChildBg
ImGui::End();
ImGui::PopStyleColor(); // ImGuiCol_WindowBg
ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_ScrollbarSize
ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_ScrollbarSize
if (hovered_item != last_hovered && hovered_item != 0)
{
+220 -220
View File
@@ -38,84 +38,82 @@ struct key
using keyboard_layout = std::vector<std::vector<key>>;
keyboard_layout azerty = {
{
{ 1, U"aàâæ" },
{ 1, U"z" },
{ 1, U"eéèêë" },
{ 1, U"r" },
{ 1, U"t" },
{ 1, U"yÿ" },
{ 1, U"uùûü" },
{ 1, U"iîï" },
{ 1, U"oôœ" },
{ 1, U"p" },
{ 2, U"", ImGuiKey_Backslash },
},
{
{ 1, U"q" },
{ 1, U"s" },
{ 1, U"d" },
{ 1, U"f" },
{ 1, U"g" },
{ 1, U"h" },
{ 1, U"j" },
{ 1, U"k" },
{ 1, U"l" },
{ 1, U"m" },
},
{
{ 2, U"", ImGuiKey_LeftShift },
{ 1, U"w" },
{ 1, U"x" },
{ 1, U"cç" },
{ 1, U"v" },
{ 1, U"b" },
{ 1, U"n" },
{ 1, U",?" },
{ 1, U";." },
{ 1, U":/" },
{ 1, U"!§" },
}
};
{
{1, U"aàâæ"},
{1, U"z"},
{1, U"eéèêë"},
{1, U"r"},
{1, U"t"},
{1, U"yÿ"},
{1, U"uùûü"},
{1, U"iîï"},
{1, U"oôœ"},
{1, U"p"},
{2, U"", ImGuiKey_Backslash},
},
{
{1, U"q"},
{1, U"s"},
{1, U"d"},
{1, U"f"},
{1, U"g"},
{1, U"h"},
{1, U"j"},
{1, U"k"},
{1, U"l"},
{1, U"m"},
},
{
{2, U"", ImGuiKey_LeftShift},
{1, U"w"},
{1, U"x"},
{1, U"cç"},
{1, U"v"},
{1, U"b"},
{1, U"n"},
{1, U",?"},
{1, U";."},
{1, U":/"},
{1, U"!§"},
}};
keyboard_layout symbols = {
{
{ 1, U"1" },
{ 1, U"2" },
{ 1, U"3" },
{ 1, U"4" },
{ 1, U"5" },
{ 1, U"6" },
{ 1, U"7" },
{ 1, U"8" },
{ 1, U"9" },
{ 1, U"0" },
},
{
{ 1, U"@" },
{ 1, U"#" },
{ 1, U"%" },
{ 1, U"&" },
{ 1, U"*" },
{ 1, U"_" },
{ 1, U"-" },
{ 1, U"+" },
{ 1, U"(" },
{ 1, U")" },
},
{
{ 1, U"\"" },
{ 1, U"<" },
{ 1, U">" },
{ 1, U"'" },
{ 1, U"*" },
{ 1, U":" },
{ 1, U"/" },
{ 1, U"!" },
{ 1, U"?" },
{ 1, U"" },
}
};
{
{1, U"1"},
{1, U"2"},
{1, U"3"},
{1, U"4"},
{1, U"5"},
{1, U"6"},
{1, U"7"},
{1, U"8"},
{1, U"9"},
{1, U"0"},
},
{
{1, U"@"},
{1, U"#"},
{1, U"%"},
{1, U"&"},
{1, U"*"},
{1, U"_"},
{1, U"-"},
{1, U"+"},
{1, U"("},
{1, U")"},
},
{
{1, U"\""},
{1, U"<"},
{1, U">"},
{1, U"'"},
{1, U"*"},
{1, U":"},
{1, U"/"},
{1, U"!"},
{1, U"?"},
{1, U""},
}};
static std::string to_utf8(char32_t c)
{
@@ -147,144 +145,152 @@ static std::string to_utf8(char32_t c)
return s;
}
static bool button_behavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
static bool button_behavior(const ImRect & bb, ImGuiID id, bool * out_hovered, bool * out_held, ImGuiButtonFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = ImGui::GetCurrentWindow();
ImGuiContext & g = *GImGui;
ImGuiWindow * window = ImGui::GetCurrentWindow();
// Default behavior inherited from item flags
// Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
if (flags & ImGuiButtonFlags_AllowOverlap)
item_flags |= ImGuiItemFlags_AllowOverlap;
if (flags & ImGuiButtonFlags_Repeat)
item_flags |= ImGuiItemFlags_ButtonRepeat;
// Default behavior inherited from item flags
// Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
if (flags & ImGuiButtonFlags_AllowOverlap)
item_flags |= ImGuiItemFlags_AllowOverlap;
if (flags & ImGuiButtonFlags_Repeat)
item_flags |= ImGuiItemFlags_ButtonRepeat;
bool pressed = false;
bool hovered = ImGui::ItemHoverable(bb, id, item_flags);
bool pressed = false;
bool hovered = ImGui::ItemHoverable(bb, id, item_flags);
// Mouse handling
const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id;
if (hovered)
{
// Poll mouse buttons
// - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId.
// - Technically we only need some values in one code path, but since this is gated by hovered test this is fine.
int mouse_button_clicked = -1;
int mouse_button_released = -1;
for (int button = 0; button < 3; button++)
if (flags & (ImGuiButtonFlags_MouseButtonLeft << button)) // Handle ImGuiButtonFlags_MouseButtonRight and ImGuiButtonFlags_MouseButtonMiddle here.
{
if (ImGui::IsMouseClicked(button, test_owner_id) && mouse_button_clicked == -1) { mouse_button_clicked = button; }
if (ImGui::IsMouseReleased(button, test_owner_id) && mouse_button_released == -1) { mouse_button_released = button; }
}
// Mouse handling
const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id;
if (hovered)
{
// Poll mouse buttons
// - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId.
// - Technically we only need some values in one code path, but since this is gated by hovered test this is fine.
int mouse_button_clicked = -1;
int mouse_button_released = -1;
for (int button = 0; button < 3; button++)
if (flags & (ImGuiButtonFlags_MouseButtonLeft << button)) // Handle ImGuiButtonFlags_MouseButtonRight and ImGuiButtonFlags_MouseButtonMiddle here.
{
if (ImGui::IsMouseClicked(button, test_owner_id) && mouse_button_clicked == -1)
{
mouse_button_clicked = button;
}
if (ImGui::IsMouseReleased(button, test_owner_id) && mouse_button_released == -1)
{
mouse_button_released = button;
}
}
// Process initial action
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
if (mouse_button_clicked != -1 && g.ActiveId != id)
{
if (!(flags & ImGuiButtonFlags_NoSetKeyOwner))
ImGui::SetKeyOwner(ImGui::MouseButtonToKey(mouse_button_clicked), id);
if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere))
{
// ImGui::SetActiveID(id, window);
g.ActiveIdMouseButton = mouse_button_clicked;
if (!(flags & ImGuiButtonFlags_NoNavFocus))
ImGui::SetFocusID(id, window);
ImGui::FocusWindow(window);
}
if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2))
{
pressed = true;
// if (flags & ImGuiButtonFlags_NoHoldingActiveId)
// ImGui::ClearActiveID();
// else
// ImGui::SetActiveID(id, window); // Hold on ID
if (!(flags & ImGuiButtonFlags_NoNavFocus))
ImGui::SetFocusID(id, window);
g.ActiveIdMouseButton = mouse_button_clicked;
ImGui::FocusWindow(window);
}
}
if (flags & ImGuiButtonFlags_PressedOnRelease)
{
if (mouse_button_released != -1)
{
const bool has_repeated_at_least_once = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; // Repeat mode trumps on release behavior
if (!has_repeated_at_least_once)
pressed = true;
if (!(flags & ImGuiButtonFlags_NoNavFocus))
ImGui::SetFocusID(id, window);
// ImGui::ClearActiveID();
}
}
// Process initial action
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
if (mouse_button_clicked != -1 && g.ActiveId != id)
{
if (!(flags & ImGuiButtonFlags_NoSetKeyOwner))
ImGui::SetKeyOwner(ImGui::MouseButtonToKey(mouse_button_clicked), id);
if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere))
{
// ImGui::SetActiveID(id, window);
g.ActiveIdMouseButton = mouse_button_clicked;
if (!(flags & ImGuiButtonFlags_NoNavFocus))
ImGui::SetFocusID(id, window);
ImGui::FocusWindow(window);
}
if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2))
{
pressed = true;
// if (flags & ImGuiButtonFlags_NoHoldingActiveId)
// ImGui::ClearActiveID();
// else
// ImGui::SetActiveID(id, window); // Hold on ID
if (!(flags & ImGuiButtonFlags_NoNavFocus))
ImGui::SetFocusID(id, window);
g.ActiveIdMouseButton = mouse_button_clicked;
ImGui::FocusWindow(window);
}
}
if (flags & ImGuiButtonFlags_PressedOnRelease)
{
if (mouse_button_released != -1)
{
const bool has_repeated_at_least_once = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; // Repeat mode trumps on release behavior
if (!has_repeated_at_least_once)
pressed = true;
if (!(flags & ImGuiButtonFlags_NoNavFocus))
ImGui::SetFocusID(id, window);
// ImGui::ClearActiveID();
}
}
// 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
// Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
if (g.ActiveId == id && (item_flags & ImGuiItemFlags_ButtonRepeat))
if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && ImGui::IsMouseClicked(g.ActiveIdMouseButton, test_owner_id, ImGuiInputFlags_Repeat))
pressed = true;
}
// 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
// Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
if (g.ActiveId == id && (item_flags & ImGuiItemFlags_ButtonRepeat))
if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && ImGui::IsMouseClicked(g.ActiveIdMouseButton, test_owner_id, ImGuiInputFlags_Repeat))
pressed = true;
}
if (pressed)
g.NavDisableHighlight = true;
}
if (pressed)
g.NavDisableHighlight = true;
}
// Process while held
bool held = false;
if (g.ActiveId == id)
{
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (g.ActiveIdIsJustActivated)
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
// Process while held
bool held = false;
if (g.ActiveId == id)
{
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (g.ActiveIdIsJustActivated)
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
const int mouse_button = g.ActiveIdMouseButton;
if (mouse_button == -1)
{
// Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304).
// ImGui::ClearActiveID();
}
else if (ImGui::IsMouseDown(mouse_button, test_owner_id))
{
held = true;
}
else
{
bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0;
bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0;
if ((release_in || release_anywhere) && !g.DragDropActive)
{
// Report as pressed when releasing the mouse (this is the most common path)
bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2;
bool is_repeating_already = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps <on release>
bool is_button_avail_or_owned = ImGui::TestKeyOwner(ImGui::MouseButtonToKey(mouse_button), test_owner_id);
if (!is_double_click_release && !is_repeating_already && is_button_avail_or_owned)
pressed = true;
}
// ImGui::ClearActiveID();
}
if (!(flags & ImGuiButtonFlags_NoNavFocus))
g.NavDisableHighlight = true;
}
else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
{
// When activated using Nav, we hold on the ActiveID until activation button is released
// if (g.NavActivateDownId != id)
// ImGui::ClearActiveID();
}
if (pressed)
g.ActiveIdHasBeenPressedBefore = true;
}
const int mouse_button = g.ActiveIdMouseButton;
if (mouse_button == -1)
{
// Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304).
// ImGui::ClearActiveID();
}
else if (ImGui::IsMouseDown(mouse_button, test_owner_id))
{
held = true;
}
else
{
bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0;
bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0;
if ((release_in || release_anywhere) && !g.DragDropActive)
{
// Report as pressed when releasing the mouse (this is the most common path)
bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2;
bool is_repeating_already = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps <on release>
bool is_button_avail_or_owned = ImGui::TestKeyOwner(ImGui::MouseButtonToKey(mouse_button), test_owner_id);
if (!is_double_click_release && !is_repeating_already && is_button_avail_or_owned)
pressed = true;
}
// ImGui::ClearActiveID();
}
if (!(flags & ImGuiButtonFlags_NoNavFocus))
g.NavDisableHighlight = true;
}
else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
{
// When activated using Nav, we hold on the ActiveID until activation button is released
// if (g.NavActivateDownId != id)
// ImGui::ClearActiveID();
}
if (pressed)
g.ActiveIdHasBeenPressedBefore = true;
}
if (out_hovered) *out_hovered = hovered;
if (out_held) *out_held = held;
if (out_hovered)
*out_hovered = hovered;
if (out_held)
*out_held = held;
return pressed;
return pressed;
}
static void draw_single_key(const key& k, int key_id, ImVec2 size_arg)
static void draw_single_key(const key & k, int key_id, ImVec2 size_arg)
{
std::string label = k.characters == U"" ? "" : to_utf8(k.characters[0]);
label += "##virtual_keyboard_key_" + std::to_string(key_id);
@@ -293,12 +299,12 @@ static void draw_single_key(const key& k, int key_id, ImVec2 size_arg)
int flags = (int)ImGuiButtonFlags_PressedOnClickRelease | (int)ImGuiButtonFlags_MouseButtonLeft | (int)ImGuiButtonFlags_NoNavFocus;
ImGuiWindow* window = ImGui::GetCurrentWindow();
ImGuiWindow * window = ImGui::GetCurrentWindow();
if (window->SkipItems)
return /*false*/;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImGuiContext & g = *GImGui;
const ImGuiStyle & style = g.Style;
const ImGuiID id = window->GetID(label.c_str());
const ImVec2 label_size = ImGui::CalcTextSize(label.c_str(), NULL, true);
@@ -316,46 +322,40 @@ static void draw_single_key(const key& k, int key_id, ImVec2 size_arg)
[[maybe_unused]] bool pressed = button_behavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 col = ImGui::GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
const ImU32 col = ImGui::GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
ImGui::RenderNavHighlight(bb, id);
ImGui::RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
// if (g.LogEnabled)
// LogSetNextTextDecoration("[", "]");
// LogSetNextTextDecoration("[", "]");
ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label.c_str(), NULL, &label_size, style.ButtonTextAlign, &bb);
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
// IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
// return pressed;
}
void scenes::lobby::gui_keyboard(ImVec2 size)
{
const keyboard_layout& layout = azerty;
const keyboard_layout & layout = azerty;
int nb_rows = layout.size();
ImVec2 position = ImGui::GetCursorPos();
ImGuiStyle& style = ImGui::GetStyle();
ImGuiStyle & style = ImGui::GetStyle();
std::vector<float> keys_width;
// Size of a key including margin, scaled by the key width later
ImVec2 key_size{FLT_MAX, (size.y + style.FramePadding.y) / nb_rows};
for(const auto& row: layout)
for (const auto & row: layout)
{
float total_width = 0;
for(auto& key: row)
for (auto & key: row)
total_width += key.width;
keys_width.push_back(total_width);
@@ -364,11 +364,11 @@ void scenes::lobby::gui_keyboard(ImVec2 size)
}
int id = 0;
for(const auto& [row, width]: utils::zip(layout, keys_width))
for (const auto & [row, width]: utils::zip(layout, keys_width))
{
ImVec2 key_position = position;
for(const auto& key: row)
for (const auto & key: row)
{
if (key.visible)
{
+104 -82
View File
@@ -21,11 +21,14 @@
#include "stream.h"
#include "application.h"
#include "audio/audio.h"
#include "boost/pfr/core.hpp"
#include "decoder/shard_accumulator.h"
#include "hardware.h"
#include "spdlog/spdlog.h"
#include "utils/named_thread.h"
#include "utils/ranges.h"
#include "utils/sync_queue.h"
#include "utils/named_thread.h"
#include "vk/pipeline.h"
#include "vk/shader.h"
#include "wivrn_packets.h"
@@ -33,9 +36,6 @@
#include <mutex>
#include <thread>
#include <vulkan/vulkan_raii.hpp>
#include "boost/pfr/core.hpp"
#include "audio/audio.h"
#include "hardware.h"
using namespace xrt::drivers::wivrn;
@@ -69,15 +69,14 @@ static const std::unordered_map<std::string, device_id> device_ids = {
// clang-format on
static const std::array supported_formats =
{
vk::Format::eR8G8B8A8Srgb,
vk::Format::eB8G8R8A8Srgb
};
{
vk::Format::eR8G8B8A8Srgb,
vk::Format::eB8G8R8A8Srgb};
std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_session> network_session, bool show_performance_metrics, bool enable_microphone)
{
std::shared_ptr<stream> self{new stream};
spdlog::info("decoder_mutex.native_handle() = {}", (void*)self->decoder_mutex.native_handle());
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;
@@ -94,7 +93,9 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO,
self->instance.now(),
application::view());
assert(views.size() == info.fov.size());
for (auto [i, j]: utils::zip(views, info.fov))
{
j = i.fov;
@@ -122,9 +123,11 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
self->video_thread = utils::named_thread("video_thread", &stream::video, self.get());
self->command_buffer = std::move(self->device.allocateCommandBuffers({
.commandPool = *self->commandpool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1})[0]);
.commandPool = *self->commandpool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1,
})[0]);
self->fence = self->device.createFence({.flags = vk::FenceCreateFlagBits::eSignaled});
// Look up the XrActions for haptics
@@ -166,7 +169,12 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
spdlog::info("Using format {}", vk::to_string(self->swapchain_format));
self->query_pool = vk::raii::QueryPool(self->device, vk::QueryPoolCreateInfo{.queryType = vk::QueryType::eTimestamp, .queryCount = size_gpu_timestamps});
self->query_pool = vk::raii::QueryPool(
self->device,
vk::QueryPoolCreateInfo{
.queryType = vk::QueryType::eTimestamp,
.queryCount = size_gpu_timestamps,
});
return self;
}
@@ -176,21 +184,22 @@ void scenes::stream::on_focused()
if (show_performance_metrics)
{
swapchain_imgui = xr::swapchain(
session,
device,
swapchain_format,
1500, 1000);
session,
device,
swapchain_format,
1500,
1000);
imgui_ctx.emplace(physical_device,
device,
queue_family_index,
queue,
view_space,
std::span<imgui_context::controller>{},
swapchain_imgui,
glm::vec2{1.0, 0.6666});
device,
queue_family_index,
queue,
view_space,
std::span<imgui_context::controller>{},
swapchain_imgui,
glm::vec2{1.0, 0.6666});
imgui_ctx->set_position({0,0,-1}, {1,0,0,0});
imgui_ctx->set_position({0, 0, -1}, {1, 0, 0, 0});
}
assert(video_stream_description);
@@ -231,9 +240,9 @@ void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_p
if (i.decoder.get() == decoder)
{
std::swap(removed, i.latest_frames[0]);
for (size_t j = 1 ; j < i.latest_frames.size() ; ++j)
for (size_t j = 1; j < i.latest_frames.size(); ++j)
{
std::swap(i.latest_frames[j-1], i.latest_frames[j]);
std::swap(i.latest_frames[j - 1], i.latest_frames[j]);
}
std::swap(i.latest_frames.back(), handle);
break;
@@ -276,8 +285,7 @@ std::optional<uint64_t> scenes::stream::accumulator_images::common_frame(const s
{
std::vector<uint64_t> tmp;
auto x = set.frames();
std::set_intersection(
x.begin(), x.end(), common_frames.begin(), common_frames.end(), std::back_inserter(tmp));
std::ranges::set_intersection(x, common_frames, std::back_inserter(tmp));
common_frames = tmp;
if (common_frames.empty())
return {};
@@ -294,8 +302,10 @@ std::shared_ptr<shard_accumulator::blit_handle> scenes::stream::accumulator_imag
{
if (not *it)
continue;
if (id and (*it)->feedback.frame_index != *id)
continue;
return *it;
}
return nullptr;
@@ -357,7 +367,7 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
})[0]
.release();
const auto& description = i.decoder->desc();
const auto & description = i.decoder->desc();
vk::Extent2D image_size = i.decoder->image_size();
std::array useful_size{
float(description.width) / image_size.width,
@@ -416,8 +426,8 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
.topology = vk::PrimitiveTopology::eTriangleStrip,
}},
.ViewportState = {.flags = {}},
.Viewports = {{}},
.Scissors = {{}},
.Viewports = {{}},
.Scissors = {{}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
@@ -440,6 +450,7 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout)
throw std::runtime_error("Vulkan fence timeout");
device.resetFences(*fence);
// We don't need those after vkWaitForFences
@@ -449,15 +460,15 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
if (query_pool_filled)
{
auto [res, timestamps2] = query_pool.getResults<uint64_t>(
0,
size_gpu_timestamps,
size_gpu_timestamps * sizeof(uint64_t),
sizeof(uint64_t),
vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
0,
size_gpu_timestamps,
size_gpu_timestamps * sizeof(uint64_t),
sizeof(uint64_t),
vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
if (res == vk::Result::eSuccess)
{
boost::pfr::for_each_field(timestamps, [n = 1, &timestamps2](float& t) mutable {
boost::pfr::for_each_field(timestamps, [n = 1, &timestamps2](float & t) mutable {
t = (timestamps2[n++] - timestamps2[0]) * application::get_physical_device_properties().limits.timestampPeriod / 1e9;
});
}
@@ -497,8 +508,10 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
// Search for the most recent frame available on all decoders.
// If no such frame exists, use the latest frame for each decoder
auto common_frame = accumulator_images::common_frame(decoders, next_frame);
if (common_frame)
next_frame = *common_frame + 1;
// Blit images from the decoders
for (auto & i: decoders)
{
@@ -541,19 +554,19 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
.oldLayout = *blit_handle->current_layout,
.newLayout = vk::ImageLayout::eGeneral,
.image = blit_handle->image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.levelCount = 1,
.layerCount = 1,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.levelCount = 1,
.layerCount = 1,
},
};
command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {}, {}, {}, barrier);
*blit_handle->current_layout = vk::ImageLayout::eGeneral;
}
}
}
uint16_t x_offset = 0;
for (auto & out: decoder_output)
{
@@ -588,7 +601,8 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
.width = (float)description.width,
.height = (float)description.height,
.minDepth = 0,
.maxDepth = 1};
.maxDepth = 1,
};
x0 = std::clamp<int>(x0, 0, out.size.width);
x1 = std::clamp<int>(x1, 0, out.size.width);
@@ -639,15 +653,23 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
{
swapchains[swapchain_index].release();
layer_view[swapchain_index].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
layer_view[swapchain_index] =
{
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW,
.pose = views[swapchain_index].pose,
.fov = views[swapchain_index].fov,
layer_view[swapchain_index].pose = views[swapchain_index].pose;
layer_view[swapchain_index].fov = views[swapchain_index].fov;
layer_view[swapchain_index].subImage.swapchain = swapchains[swapchain_index];
layer_view[swapchain_index].subImage.imageRect.offset = {0, 0};
layer_view[swapchain_index].subImage.imageRect.extent.width = swapchains[swapchain_index].width();
layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height();
.subImage = {
.swapchain = swapchains[swapchain_index],
.imageRect = {
.offset = {0, 0},
.extent = {
swapchains[swapchain_index].width(),
swapchains[swapchain_index].height(),
},
},
},
};
}
float brightness = std::clamp<float>(dbrightness * (predicted_display_time - first_frame_time) / 1.e9, 0, 1);
@@ -655,7 +677,8 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
XrCompositionLayerColorScaleBiasKHR color_scale_bias{
.type = XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR,
.colorScale = {brightness, brightness, brightness, 1},
.colorBias = {}};
.colorBias = {},
};
XrCompositionLayerProjection layer{
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
@@ -683,7 +706,7 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render)
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)
for (const auto & handle: current_blit_handles)
send_feedback(handle->feedback);
read_actions();
@@ -753,37 +776,37 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
decoder_output[i].size.height = video_height;
vk::ImageCreateInfo image_info{
.flags = vk::ImageCreateFlags{},
.imageType = vk::ImageType::e2D,
.format = vk::Format::eA8B8G8R8SrgbPack32,
.extent = decoder_out_size,
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined,
.flags = vk::ImageCreateFlags{},
.imageType = vk::ImageType::e2D,
.format = vk::Format::eA8B8G8R8SrgbPack32,
.extent = decoder_out_size,
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined,
};
VmaAllocationCreateInfo alloc_info{
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
};
decoder_output[i].image = image_allocation{device, image_info, alloc_info};
vk::ImageViewCreateInfo image_view_info{
.image = vk::Image{decoder_output[i].image},
.viewType = vk::ImageViewType::e2D,
.format = vk::Format::eA8B8G8R8SrgbPack32,
.components = {},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
.image = vk::Image{decoder_output[i].image},
.viewType = vk::ImageViewType::e2D,
.format = vk::Format::eA8B8G8R8SrgbPack32,
.components = {},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
decoder_output[i].image_view = vk::raii::ImageView(device, image_view_info);
@@ -912,12 +935,11 @@ void scenes::stream::video()
}
}
scene::meta& scenes::stream::get_meta_scene()
scene::meta & scenes::stream::get_meta_scene()
{
static meta m{
"Stream",
{}
};
"Stream",
{}};
return m;
}
+8 -9
View File
@@ -19,7 +19,9 @@
#pragma once
#include "audio/audio.h"
#include "decoder/shard_accumulator.h"
#include "render/imgui_impl.h"
#include "scene.h"
#include "stream_reprojection.h"
#include "utils/sync_queue.h"
@@ -28,8 +30,6 @@
#include <mutex>
#include <thread>
#include <vulkan/vulkan_core.h>
#include "audio/audio.h"
#include "render/imgui_impl.h"
namespace scenes
{
@@ -82,7 +82,7 @@ private:
std::mutex decoder_mutex;
std::optional<to_headset::video_stream_description> video_stream_description;
uint64_t next_frame; // Preferred index for next frame
uint64_t next_frame; // Preferred index for next frame
std::vector<accumulator_images> decoders; // Locked by decoder_mutex
vk::raii::DescriptorPool blit_descriptor_pool = nullptr;
vk::raii::RenderPass blit_render_pass = nullptr;
@@ -124,13 +124,13 @@ public:
void on_focused() override;
void on_unfocused() override;
void operator()(to_headset::handshake&&) {};
void operator()(to_headset::handshake &&){};
void operator()(to_headset::video_stream_data_shard &&);
void operator()(to_headset::haptics &&);
void operator()(to_headset::timesync_query &&);
void operator()(to_headset::audio_stream_description &&);
void operator()(to_headset::video_stream_description &&);
void operator()(audio_data&&);
void operator()(audio_data &&);
void push_blit_handle(shard_accumulator * decoder, std::shared_ptr<shard_accumulator::blit_handle> handle);
@@ -138,7 +138,7 @@ public:
state current_state() const
{
return state_ ;
return state_;
}
bool alive() const
@@ -146,7 +146,7 @@ public:
return !exiting;
}
static meta& get_meta_scene();
static meta & get_meta_scene();
private:
void process_packets();
@@ -179,7 +179,6 @@ private:
float cpu_time = 0;
float bandwidth_rx = 0;
float bandwidth_tx = 0;
};
struct plot
@@ -215,7 +214,7 @@ private:
XrTime last_metric_time = 0;
int metrics_offset = 0;
void accumulate_metrics(XrTime predicted_display_time, const std::vector<std::shared_ptr<shard_accumulator::blit_handle>>& blit_handles, const gpu_timestamps& timestamps);
void accumulate_metrics(XrTime predicted_display_time, const std::vector<std::shared_ptr<shard_accumulator::blit_handle>> & blit_handles, const gpu_timestamps & timestamps);
XrCompositionLayerQuad plot_performance_metrics(XrTime predicted_display_time);
};
} // namespace scenes
+1 -1
View File
@@ -17,8 +17,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "stream.h"
#include "application.h"
#include "stream.h"
#include <spdlog/spdlog.h>
void scenes::stream::read_actions()
+1 -1
View File
@@ -65,7 +65,7 @@ void scenes::stream::operator()(to_headset::timesync_query && query)
network_session->send_stream(response);
}
void scenes::stream::operator()(audio_data&& data)
void scenes::stream::operator()(audio_data && data)
{
if (audio_handle)
(*audio_handle)(std::move(data));
+210 -199
View File
@@ -20,12 +20,12 @@
#include "stream_reprojection.h"
#include "application.h"
#include "vk/allocation.h"
#include "vk/shader.h"
#include "vk/pipeline.h"
#include <spdlog/spdlog.h>
#include "vk/shader.h"
#include <array>
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include <spdlog/spdlog.h>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan_core.h>
#include <vulkan/vulkan_raii.hpp>
@@ -43,31 +43,38 @@ struct stream_reprojection::uniform
const int nb_reprojection_vertices = 64;
stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, std::vector<vk::Image> input_images_, std::vector<vk::Image> output_images_, vk::Extent2D extent, vk::Format format, const xrt::drivers::wivrn::to_headset::video_stream_description & description) :
input_images(std::move(input_images_)),
output_images(std::move(output_images_)),
extent(extent)
stream_reprojection::stream_reprojection(
vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
std::vector<vk::Image> input_images_,
std::vector<vk::Image> output_images_,
vk::Extent2D extent,
vk::Format format,
const xrt::drivers::wivrn::to_headset::video_stream_description & description) :
input_images(std::move(input_images_)),
output_images(std::move(output_images_)),
extent(extent)
{
foveation_parameters = description.foveation;
vk::PhysicalDeviceProperties properties = physical_device.getProperties();
vk::SamplerCreateInfo sampler_info{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eNearest,
.addressModeU = vk::SamplerAddressMode::eClampToBorder,
.addressModeV = vk::SamplerAddressMode::eClampToBorder,
.addressModeW = vk::SamplerAddressMode::eClampToBorder,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareEnable = VK_FALSE,
.compareOp = vk::CompareOp::eNever,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = vk::BorderColor::eFloatOpaqueBlack,
.unnormalizedCoordinates = VK_FALSE,
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eNearest,
.addressModeU = vk::SamplerAddressMode::eClampToBorder,
.addressModeV = vk::SamplerAddressMode::eClampToBorder,
.addressModeW = vk::SamplerAddressMode::eClampToBorder,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareEnable = VK_FALSE,
.compareOp = vk::CompareOp::eNever,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = vk::BorderColor::eFloatOpaqueBlack,
.unnormalizedCoordinates = VK_FALSE,
};
sampler = vk::raii::Sampler(device, sampler_info);
@@ -76,13 +83,13 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy
uniform_size = uniform_size - uniform_size % properties.limits.minUniformBufferOffsetAlignment;
vk::BufferCreateInfo create_info{
.size = uniform_size * input_images.size(),
.usage = vk::BufferUsageFlagBits::eUniformBuffer,
.sharingMode = vk::SharingMode::eExclusive,
.size = uniform_size * input_images.size(),
.usage = vk::BufferUsageFlagBits::eUniformBuffer,
.sharingMode = vk::SharingMode::eExclusive,
};
VmaAllocationCreateInfo alloc_info{
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
};
buffer = buffer_allocation(device, create_info, alloc_info);
@@ -92,18 +99,18 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy
// Create VkDescriptorSetLayout
std::array layout_binding{
vk::DescriptorSetLayoutBinding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{
.binding = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
}
vk::DescriptorSetLayoutBinding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{
.binding = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
},
};
vk::DescriptorSetLayoutCreateInfo layout_info;
@@ -119,7 +126,7 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy
vk::DescriptorPoolSize{
.type = vk::DescriptorType::eUniformBuffer,
.descriptorCount = (uint32_t)input_images.size(),
}
},
};
vk::DescriptorPoolCreateInfo pool_info;
@@ -136,87 +143,86 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy
for (vk::Image image: input_images)
{
vk::ImageViewCreateInfo iv_info{
.image = image,
.viewType = vk::ImageViewType::e2D,
.format = vk::Format::eA8B8G8R8SrgbPack32,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
}
.image = image,
.viewType = vk::ImageViewType::e2D,
.format = vk::Format::eA8B8G8R8SrgbPack32,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
input_image_views.emplace_back(device, iv_info);
vk::DescriptorSetAllocateInfo ds_info{
.descriptorPool = *descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &*descriptor_set_layout,
.descriptorPool = *descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &*descriptor_set_layout,
};
descriptor_sets.push_back(device.allocateDescriptorSets(ds_info)[0].release());
vk::DescriptorImageInfo image_info{
.sampler = *sampler,
.imageView = *input_image_views.back(),
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.sampler = *sampler,
.imageView = *input_image_views.back(),
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
};
vk::DescriptorBufferInfo buffer_info{
.buffer = buffer,
.offset = offset,
.range = sizeof(uniform),
.buffer = buffer,
.offset = offset,
.range = sizeof(uniform),
};
offset += uniform_size;
std::array write{
vk::WriteDescriptorSet{
.dstSet = descriptor_sets.back(),
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info,
},
vk::WriteDescriptorSet{
.dstSet = descriptor_sets.back(),
.dstBinding = 1,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info,
}
vk::WriteDescriptorSet{
.dstSet = descriptor_sets.back(),
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info,
},
vk::WriteDescriptorSet{
.dstSet = descriptor_sets.back(),
.dstBinding = 1,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info,
},
};
device.updateDescriptorSets(write, {});
}
// Create renderpass
vk::AttachmentReference color_ref{
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::AttachmentDescription attachment{
.format = format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eDontCare,
.storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = vk::ImageLayout::eColorAttachmentOptimal,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
.format = format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eDontCare,
.storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = vk::ImageLayout::eColorAttachmentOptimal,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::SubpassDescription subpass{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
};
subpass.setColorAttachments(color_ref);
@@ -226,45 +232,42 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy
renderpass = vk::raii::RenderPass(device, renderpass_info);
// Create graphics pipeline
vk::raii::ShaderModule vertex_shader = load_shader(device, "reprojection.vert");
vk::raii::ShaderModule fragment_shader = load_shader(device, "reprojection.frag");
vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(*descriptor_set_layout);
layout = vk::raii::PipelineLayout(device, pipeline_layout_info);
int use_foveation[] = {
foveation_parameters[0].x.scale < 1,
foveation_parameters[0].y.scale < 1,
nb_reprojection_vertices,
nb_reprojection_vertices
};
foveation_parameters[0].x.scale < 1,
foveation_parameters[0].y.scale < 1,
nb_reprojection_vertices,
nb_reprojection_vertices};
std::array specialization_constants_desc{
vk::SpecializationMapEntry{
.constantID = 0,
.offset = 0,
.size = sizeof(int),
},
vk::SpecializationMapEntry{
.constantID = 1,
.offset = sizeof(int),
.size = sizeof(int),
},
vk::SpecializationMapEntry{
.constantID = 2,
.offset = 2 * sizeof(int),
.size = sizeof(int),
},
vk::SpecializationMapEntry{
.constantID = 3,
.offset = 3 * sizeof(int),
.size = sizeof(int),
}
vk::SpecializationMapEntry{
.constantID = 0,
.offset = 0,
.size = sizeof(int),
},
vk::SpecializationMapEntry{
.constantID = 1,
.offset = sizeof(int),
.size = sizeof(int),
},
vk::SpecializationMapEntry{
.constantID = 2,
.offset = 2 * sizeof(int),
.size = sizeof(int),
},
vk::SpecializationMapEntry{
.constantID = 3,
.offset = 3 * sizeof(int),
.size = sizeof(int),
},
};
vk::SpecializationInfo specialization_info;
@@ -272,53 +275,59 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy
specialization_info.setMapEntries(specialization_constants_desc);
specialization_info.setData<int>(use_foveation);
vk::pipeline_builder pipeline_info
{
.flags = {},
.Stages = {{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
.pSpecializationInfo = &specialization_info,
},{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
.pSpecializationInfo = &specialization_info,
}},
.VertexInputState = {.flags = {}},
.VertexBindingDescriptions = {},
.VertexAttributeDescriptions = {},
.InputAssemblyState = {{
.topology = vk::PrimitiveTopology::eTriangleList,
}},
.ViewportState = {.flags = {}},
.Viewports = {{
.x = 0,
.y = 0,
.width = (float)extent.width,
.height = (float)extent.height,
.minDepth = 0,
.maxDepth = 1,
}},
.Scissors = {{
.offset = { .x = 0, .y = 0 },
.extent= extent,
}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendState = {.flags = {}},
.ColorBlendAttachments = {{
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA
}},
.layout = *layout,
.renderPass = *renderpass,
.subpass = 0,
vk::pipeline_builder pipeline_info{
.flags = {},
.Stages = {
{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
.pSpecializationInfo = &specialization_info,
},
{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
.pSpecializationInfo = &specialization_info,
},
},
.VertexInputState = {
.flags = {},
},
.VertexBindingDescriptions = {},
.VertexAttributeDescriptions = {},
.InputAssemblyState = {{
.topology = vk::PrimitiveTopology::eTriangleList,
}},
.ViewportState = {
.flags = {},
},
.Viewports = {{
.x = 0,
.y = 0,
.width = (float)extent.width,
.height = (float)extent.height,
.minDepth = 0,
.maxDepth = 1,
}},
.Scissors = {{
.offset = {.x = 0, .y = 0},
.extent = extent,
}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendState = {.flags = {}},
.ColorBlendAttachments = {{
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA,
}},
.layout = *layout,
.renderPass = *renderpass,
.subpass = 0,
};
pipeline = vk::raii::Pipeline(device, application::get_pipeline_cache(), pipeline_info);
@@ -329,31 +338,31 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy
for (vk::Image image: output_images)
{
vk::ImageViewCreateInfo iv_info{
.image = image,
.viewType = vk::ImageViewType::e2D,
.format = format,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
.image = image,
.viewType = vk::ImageViewType::e2D,
.format = format,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
output_image_views.emplace_back(device, iv_info);
vk::FramebufferCreateInfo fb_create_info{
.renderPass = *renderpass,
.width = extent.width,
.height = extent.height,
.layers = 1,
.renderPass = *renderpass,
.width = extent.width,
.height = extent.height,
.layers = 1,
};
fb_create_info.setAttachments(*output_image_views.back());
@@ -361,7 +370,7 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy
}
}
void stream_reprojection::reproject(vk::raii::CommandBuffer& command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf dest_pose, XrFovf dest_fov)
void stream_reprojection::reproject(vk::raii::CommandBuffer & command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf dest_pose, XrFovf dest_fov)
{
if (source < 0 || source >= (int)input_images.size())
throw std::runtime_error("Invalid source image index");
@@ -382,31 +391,33 @@ void stream_reprojection::reproject(vk::raii::CommandBuffer& command_buffer, int
{ (l+r)/(r-l), (t+b)/(b-t), -1, -1 },
{ 0, 0, -2*zn, 0 }
};
// clang-format on
glm::mat4 hmd_unview = glm::mat4_cast(glm::quat(
dest_pose.w,
dest_pose.x,
dest_pose.y,
dest_pose.z));
dest_pose.w,
dest_pose.x,
dest_pose.y,
dest_pose.z));
r = tan(source_fov.angleRight);
l = tan(source_fov.angleLeft);
t = tan(source_fov.angleUp);
b = tan(source_fov.angleDown);
// clang-format off
glm::mat4 video_proj{
{ 2/(r-l), 0, 0, 0 },
{ 0, 2/(b-t), 0, 0 },
{ (l+r)/(r-l), (t+b)/(b-t), -1, -1 },
{ 0, 0, -2*zn, 0 }
};
// clang-format on
glm::mat4 video_view = glm::mat4_cast(glm::quat(
-source_pose.w,
source_pose.x,
source_pose.y,
source_pose.z));
// clang-format on
-source_pose.w,
source_pose.x,
source_pose.y,
source_pose.z));
ubo[source]->reprojection = video_proj * video_view * hmd_unview * glm::inverse(hmd_proj);
@@ -421,12 +432,12 @@ void stream_reprojection::reproject(vk::raii::CommandBuffer& command_buffer, int
ubo[source]->xc.y = foveation_parameters[source].y.center;
vk::RenderPassBeginInfo begin_info{
.renderPass = *renderpass,
.framebuffer = *framebuffers[destination],
.renderArea = {
.offset = {0, 0},
.extent = extent,
},
.renderPass = *renderpass,
.framebuffer = *framebuffers[destination],
.renderArea = {
.offset = {0, 0},
.extent = extent,
},
};
command_buffer.pipelineBarrier(
+18 -4
View File
@@ -21,9 +21,8 @@
#include "vk/allocation.h"
#include "wivrn_packets.h"
#include <vulkan/vulkan_core.h>
#include <openxr/openxr.h>
#include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h>
class stream_reprojection
{
@@ -56,8 +55,23 @@ class stream_reprojection
std::array<xrt::drivers::wivrn::to_headset::video_stream_description::foveation_parameter, 2> foveation_parameters;
public:
stream_reprojection(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, std::vector<vk::Image> input_images, std::vector<vk::Image> output_images, vk::Extent2D extent, vk::Format format, const xrt::drivers::wivrn::to_headset::video_stream_description & description);
stream_reprojection(
vk::raii::Device & device,
vk::raii::PhysicalDevice & physical_device,
std::vector<vk::Image> input_images,
std::vector<vk::Image> output_images,
vk::Extent2D extent,
vk::Format format,
const xrt::drivers::wivrn::to_headset::video_stream_description & description);
stream_reprojection(const stream_reprojection &) = delete;
void reproject(vk::raii::CommandBuffer& command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf destination_pose, XrFovf destination_fov);
void reproject(
vk::raii::CommandBuffer & command_buffer,
int source,
int destination,
XrQuaternionf source_pose,
XrFovf source_fov,
XrQuaternionf destination_pose,
XrFovf destination_fov);
};
+80 -94
View File
@@ -25,8 +25,8 @@
#include "implot.h"
#include "utils/ranges.h"
#include <cmath>
#include <spdlog/spdlog.h>
#include <limits>
#include <spdlog/spdlog.h>
namespace
{
@@ -34,9 +34,9 @@ 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++)
for (int i = 0; i < count; i++)
{
max = std::max(max, *(float*)(ptr + i * stride));
max = std::max(max, *(float *)(ptr + i * stride));
}
// First power of 10 less than the max
@@ -47,18 +47,18 @@ float compute_plot_max_value(float * data, int count, ptrdiff_t stride)
std::pair<float, std::string> compute_plot_unit(float max_value)
{
if (max_value > 1e9)
return { 1e-9, "G" };
return {1e-9, "G"};
if (max_value > 1e6)
return { 1e-6, "M" };
return {1e-6, "M"};
if (max_value > 1e3)
return { 1e-3, "k" };
return {1e-3, "k"};
if (max_value > 1)
return { 1, "" };
return {1, ""};
if (max_value > 1e-3)
return { 1e3, "m" };
return {1e3, "m"};
if (max_value > 1e-6)
return { 1e6, "u" };
return { 1e9, "n" };
return {1e6, "u"};
return {1e9, "n"};
}
struct getter_data
@@ -72,15 +72,15 @@ struct getter_data
ImPlotPoint getter(int index, void * data_)
{
getter_data& data = *(getter_data*)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);
}
return ImPlotPoint(index, *(float *)(data.data + offset_index * data.stride) * data.multiplier);
}
} // namespace
void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std::vector<std::shared_ptr<shard_accumulator::blit_handle>>& blit_handles, const gpu_timestamps& timestamps)
void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std::vector<std::shared_ptr<shard_accumulator::blit_handle>> & blit_handles, const gpu_timestamps & timestamps)
{
uint64_t rx = network_session->bytes_received();
uint64_t tx = network_session->bytes_sent();
@@ -88,13 +88,13 @@ void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std
float dt = (predicted_display_time - last_metric_time) * 1e-9f;
bandwidth_rx = 0.8 * bandwidth_rx + 0.2 * float(rx - bytes_received) / dt;
bandwidth_tx = 0.8 * bandwidth_tx + 0.2 * float(tx - bytes_sent ) /dt;
bandwidth_tx = 0.8 * bandwidth_tx + 0.2 * float(tx - bytes_sent) / dt;
last_metric_time = predicted_display_time;
bytes_received = rx;
bytes_sent = tx;
*(gpu_timestamps*)&global_metrics[metrics_offset] = timestamps;
*(gpu_timestamps *)&global_metrics[metrics_offset] = timestamps;
global_metrics[metrics_offset].cpu_time = application::get_cpu_time().count() * 1e-9f;
global_metrics[metrics_offset].bandwidth_rx = bandwidth_rx * 8;
global_metrics[metrics_offset].bandwidth_tx = bandwidth_tx * 8;
@@ -103,15 +103,16 @@ void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std
decoder_metrics.resize(blit_handles.size());
auto min_encode_begin = std::numeric_limits<decltype(blit_handles[0]->timing_info.encode_begin)>::max();
for(const auto& bh: blit_handles)
for (const auto & bh: blit_handles)
min_encode_begin = std::min(min_encode_begin, bh->timing_info.encode_begin);
for(auto&& [metrics, bh]: utils::zip(decoder_metrics, blit_handles))
for (auto && [metrics, bh]: utils::zip(decoder_metrics, blit_handles))
{
if (metrics.size() != global_metrics.size())
metrics.resize(global_metrics.size());
metrics[metrics_offset] = decoder_metric{
// clang-format off
.send_begin = (bh->timing_info.send_begin - min_encode_begin) * 1e-9f,
.send_end = (bh->timing_info.send_end - min_encode_begin) * 1e-9f,
.received_first_packet = (bh->feedback.received_first_packet - min_encode_begin) * 1e-9f,
@@ -120,6 +121,7 @@ void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std
.received_from_decoder = (bh->feedback.received_from_decoder - min_encode_begin) * 1e-9f,
.blitted = (bh->feedback.blitted - min_encode_begin) * 1e-9f,
.displayed = (bh->feedback.displayed - min_encode_begin) * 1e-9f,
// clang-format on
};
}
@@ -133,28 +135,20 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted
ImGui::SetNextWindowPos({0, 0});
ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size);
ImGui::Begin("Performance metrics", nullptr,
ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove);
ImGui::Begin("Performance metrics", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove);
ImVec2 window_size = ImGui::GetWindowSize() - ImVec2(2,2) * style.WindowPadding;
ImVec2 window_size = ImGui::GetWindowSize() - ImVec2(2, 2) * style.WindowPadding;
static const std::array plots = {
plot("CPU time", {
{"", &global_metric::cpu_time},
},
"s"),
plot("GPU time", {
{"Reproject", &global_metric::gpu_time},
{"Blit", &global_metric::gpu_barrier},
},
"s"),
plot("Network", {
{"Download", &global_metric::bandwidth_rx},
{"Upload", &global_metric::bandwidth_tx},
},
"bit/s"),
// clang-format off
plot("CPU time", {{"", &global_metric::cpu_time}}, "s"),
plot("GPU time", {{"Reproject", &global_metric::gpu_time},
{"Blit", &global_metric::gpu_barrier}}, "s"),
plot("Network", {{"Download", &global_metric::bandwidth_rx},
{"Upload", &global_metric::bandwidth_tx}}, "bit/s"),
// clang-format on
};
int n_plots = plots.size() + decoders.size();
@@ -164,8 +158,8 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted
int n_rows = ceil((float)n_plots / 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);
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));
@@ -174,17 +168,17 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted
ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, IM_COL32(0, 0, 0, 0));
int n = 0;
for(const auto& [title, subplots, unit]: plots)
for (const auto & [title, subplots, unit]: plots)
{
if (ImPlot::BeginPlot(title, plot_size, ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText | ImPlotFlags_NoChild))
{
float min_v = 0;
float max_v = 0;
for (const auto& [subtitle, data]: subplots)
for (const auto & [subtitle, data]: subplots)
{
max_v = std::max(max_v, compute_plot_max_value(&(global_metrics.data()->*data), global_metrics.size(), sizeof(global_metric)));
}
auto [ multiplier, prefix ] = compute_plot_unit(max_v);
auto [multiplier, prefix] = compute_plot_unit(max_v);
if (axis_scale[n] == 0 || std::isnan(axis_scale[n]))
axis_scale[n] = max_v;
@@ -199,7 +193,7 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted
ImPlot::SetNextLineStyle(color);
ImPlot::SetNextFillStyle(color, 0.25);
for (const auto& [subtitle, data]: subplots)
for (const auto & [subtitle, data]: subplots)
{
getter_data gdata{
.data = (uintptr_t) & (global_metrics.data()->*data),
@@ -217,7 +211,7 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted
ImGui::SameLine();
}
for(auto&& [index, metrics]: utils::enumerate(decoder_metrics))
for (auto && [index, metrics]: utils::enumerate(decoder_metrics))
{
std::string title = "Decoder " + std::to_string(index);
if (ImPlot::BeginPlot(title.c_str(), plot_size, ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText | ImPlotFlags_NoChild))
@@ -235,83 +229,75 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted
ImPlot::SetupAxes(nullptr, title_with_units, ImPlotAxisFlags_NoDecorations, 0);
ImPlot::SetupAxesLimits(0, metrics.size() - 1, min_v * 1e3f, axis_scale[n] * 1e3f, ImGuiCond_Always);
getter_data getter_send_begin{
.data = (uintptr_t)&(metrics.data()->send_begin),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f
};
.data = (uintptr_t) & (metrics.data()->send_begin),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f};
getter_data getter_send_end{
.data = (uintptr_t)&(metrics.data()->send_end),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f
};
.data = (uintptr_t) & (metrics.data()->send_end),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f};
getter_data getter_received_first_packet{
.data = (uintptr_t)&(metrics.data()->received_first_packet),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f
};
.data = (uintptr_t) & (metrics.data()->received_first_packet),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f};
getter_data getter_received_last_packet{
.data = (uintptr_t)&(metrics.data()->received_last_packet),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f
};
.data = (uintptr_t) & (metrics.data()->received_last_packet),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f};
getter_data getter_sent_to_decoder{
.data = (uintptr_t)&(metrics.data()->sent_to_decoder),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f
};
.data = (uintptr_t) & (metrics.data()->sent_to_decoder),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f};
getter_data getter_received_from_decoder{
.data = (uintptr_t)&(metrics.data()->received_from_decoder),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f
};
.data = (uintptr_t) & (metrics.data()->received_from_decoder),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f};
getter_data getter_blitted{
.data = (uintptr_t)&(metrics.data()->blitted),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f
};
.data = (uintptr_t) & (metrics.data()->blitted),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f};
getter_data getter_displayed{
.data = (uintptr_t)&(metrics.data()->displayed),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f
};
.data = (uintptr_t) & (metrics.data()->displayed),
.stride = sizeof(decoder_metric),
.offset = metrics_offset,
.count = (int)metrics.size(),
.multiplier = 1e3f};
// clang-format off
ImPlot::PlotShadedG("Send", getter, &getter_send_begin, getter, &getter_send_end, metrics.size());
ImPlot::PlotShadedG("Receive", getter, &getter_received_first_packet, getter, &getter_received_last_packet, metrics.size());
ImPlot::PlotShadedG("Decode", getter, &getter_sent_to_decoder, getter, &getter_received_from_decoder, metrics.size());
ImPlot::PlotLineG("Blitted", getter, &getter_blitted, metrics.size());
ImPlot::PlotLineG("Displayed", getter, &getter_displayed, metrics.size());
// clang-format on
ImPlot::EndPlot();
}
if (++n % n_cols != 0)
ImGui::SameLine();
}
ImPlot::PopStyleColor(5);
+14 -12
View File
@@ -17,20 +17,22 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "application.h"
#include "stream.h"
#include "utils/ranges.h"
#include "application.h"
#include <thread>
#include <spdlog/spdlog.h>
#include <thread>
static from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpace reference, XrTime time)
{
XrSpaceVelocity velocity{
.type = XR_TYPE_SPACE_VELOCITY};
.type = XR_TYPE_SPACE_VELOCITY,
};
XrSpaceLocation location{
.type = XR_TYPE_SPACE_LOCATION,
.next = &velocity};
.next = &velocity,
};
xrLocateSpace(space, reference, time, &location);
@@ -63,20 +65,20 @@ static from_headset::tracking::pose locate_space(device_id device, XrSpace space
return res;
}
static std::optional<std::array<from_headset::hand_tracking::pose, XR_HAND_JOINT_COUNT_EXT>> locate_hands(xr::hand_tracker& hand, XrSpace space, XrTime time)
static std::optional<std::array<from_headset::hand_tracking::pose, XR_HAND_JOINT_COUNT_EXT>> locate_hands(xr::hand_tracker & hand, XrSpace space, XrTime time)
{
auto joints = hand.locate(space, time);
if (joints)
{
std::array<from_headset::hand_tracking::pose, XR_HAND_JOINT_COUNT_EXT> poses;
for(int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++)
for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++)
{
poses[i] = {
.pose = (*joints)[i].first.pose,
.linear_velocity = (*joints)[i].second.linearVelocity,
.angular_velocity = (*joints)[i].second.angularVelocity,
.radius = (*joints)[i].first.radius,
.pose = (*joints)[i].first.pose,
.linear_velocity = (*joints)[i].second.linearVelocity,
.angular_velocity = (*joints)[i].second.angularVelocity,
.radius = (*joints)[i].first.radius,
};
if ((*joints)[i].first.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT)
@@ -115,8 +117,8 @@ void scenes::stream::tracking()
XrSpace view_space = application::view();
const XrDuration tracking_period = 1'000'000; // Send tracking data every 1ms
const XrDuration dt = 100'000; // Wake up 0.1ms before measuring the position
const XrDuration extrapolation_horizon = 1; // 50'000'000;
const XrDuration dt = 100'000; // Wake up 0.1ms before measuring the position
const XrDuration extrapolation_horizon = 1; // 50'000'000;
XrTime t0 = instance.now();
t0 = t0 - t0 % tracking_period;