From 1faa238d21339ef0cc01c1bb7dd4a3ac9bebe57c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Isabella=20Sko=C5=99epov=C3=A1?= Date: Thu, 25 May 2023 16:59:20 +0200 Subject: [PATCH] rust docs --- netvr-rust/analyse/src/main.rs | 7 ++ netvr-rust/analyse/src/parse.rs | 24 +++++ netvr-rust/analyse/src/plot.rs | 1 + netvr-rust/analyse/src/plot_positions.rs | 1 + netvr-rust/codegen/build.rs | 1 + netvr-rust/codegen/src/main.rs | 1 + netvr-rust/netvr_calibrate/src/calibrate.rs | 5 + netvr-rust/netvr_calibrate/src/input.rs | 2 + netvr-rust/netvr_calibrate/src/lib.rs | 2 + netvr-rust/netvr_client/src/error.rs | 1 + netvr-rust/netvr_client/src/lib.rs | 1 + netvr-rust/netvr_client/src/main.rs | 1 + netvr-rust/netvr_client/src/quinn_connect.rs | 2 + netvr-rust/netvr_data/src/app.rs | 4 + netvr-rust/netvr_data/src/framing.rs | 3 + .../netvr_data/src/handle_serializer.rs | 2 + netvr-rust/netvr_data/src/lib.rs | 15 +++ netvr-rust/netvr_data/src/net.rs | 19 ++++ netvr-rust/netvr_plugin/src/config.rs | 1 + netvr-rust/netvr_plugin/src/implementation.rs | 8 ++ netvr-rust/netvr_plugin/src/instance.rs | 3 +- netvr-rust/netvr_plugin/src/lib.rs | 1 + .../netvr_plugin/src/local_configuration.rs | 3 + netvr-rust/netvr_plugin/src/overrides.rs | 95 ++++++++++++++++++- netvr-rust/netvr_plugin/src/xr_wrap.rs | 1 + .../netvr_server/src/accept_connection.rs | 2 + netvr-rust/netvr_server/src/app.rs | 5 + .../netvr_server/src/calibration_protocol.rs | 6 ++ netvr-rust/netvr_server/src/client.rs | 12 +++ netvr-rust/netvr_server/src/dashboard.rs | 8 ++ netvr-rust/netvr_server/src/main.rs | 1 + netvr-rust/netvr_server/src/server.rs | 11 +++ netvr-rust/xr_layer/build.rs | 2 + netvr-rust/xr_layer/src/loader.rs | 2 + netvr-rust/xr_layer/src/log.rs | 2 + netvr-rust/xr_layer/src/utils.rs | 3 + netvr-rust/xr_layer/src/xr_debug.rs | 2 +- netvr-rust/xr_layer/src/xr_listings.rs | 1 + netvr-rust/xr_layer/src/xr_struct.rs | 3 + netvr-rust/xr_layer/src/xr_struct_chain.rs | 1 + 40 files changed, 262 insertions(+), 3 deletions(-) diff --git a/netvr-rust/analyse/src/main.rs b/netvr-rust/analyse/src/main.rs index 3dd31de..d2d9f9e 100644 --- a/netvr-rust/analyse/src/main.rs +++ b/netvr-rust/analyse/src/main.rs @@ -7,6 +7,13 @@ use parse::{LogFile, Sample}; use crate::parse::Line; +/** + * The entrypoint of the analyse program. This is basically a script and python + * with matplotlib would probably be a better choice, but I wanted to try using + * rust for this. + * + * The nom library is nice for parsing stuff though. + */ fn main() -> Result<()> { // read file from argv let args: Vec = std::env::args().collect(); diff --git a/netvr-rust/analyse/src/parse.rs b/netvr-rust/analyse/src/parse.rs index d053e53..fff71b7 100644 --- a/netvr-rust/analyse/src/parse.rs +++ b/netvr-rust/analyse/src/parse.rs @@ -10,17 +10,22 @@ use nom::{ }; use serde::Serialize; +/// parser input pub type Input<'a> = &'a str; +/// parser result pub type Result<'a, T> = nom::IResult, T, ()>; +/// parse a integer fn decimal(input: Input) -> Result<&str> { recognize(many1(terminated(one_of("0123456789"), many0(char('_')))))(input) } +/// parse u32. This is what ids look like. fn id(input: Input) -> Result { map_res(decimal, |r| r.parse::())(input) } +/// parse a float which uses a comma as decimal separator fn float_comma(input: Input) -> Result { map_res( recognize(tuple(( @@ -36,6 +41,7 @@ fn float_comma(input: Input) -> Result { )(input) } +/// parse a float which uses a dot as decimal separator fn float_dot(input: Input) -> Result { map_res( recognize(tuple(( @@ -51,6 +57,7 @@ fn float_dot(input: Input) -> Result { )(input) } +/// parse a 3d vector in the form of (0, 0, 0) fn vec3(input: Input) -> Result<(f64, f64, f64)> { map( tuple(( @@ -68,6 +75,7 @@ fn vec3(input: Input) -> Result<(f64, f64, f64)> { )(input) } +/// parse a quaternion in the form of (0, 0, 0, 0) fn quat(input: Input) -> Result<(f64, f64, f64, f64)> { map( tuple(( @@ -88,6 +96,8 @@ fn quat(input: Input) -> Result<(f64, f64, f64, f64)> { )(input) } +/// sample for a single controller/device at a single point in time on a remote +/// machine #[derive(Debug, Serialize, Clone)] pub struct Sample { pub position: (f64, f64, f64), @@ -107,6 +117,8 @@ impl Sample { } } +/// a local sample is a sample which is recorded on the same machine as the +/// logger is running on #[derive(Debug, Serialize, Clone)] pub struct LocalSample { pub id: u32, @@ -114,6 +126,7 @@ pub struct LocalSample { pub sample: Sample, } +/// parse characteristics string representation fn characteristics(input: Input) -> Result<&str> { recognize(many1(one_of( "abcdefghijklmnopqrstuvwxyz,ABCDEFGHIJKLMNOPQRSTUVWXYZ", @@ -147,6 +160,7 @@ impl From for Sample { } } +/// a remote sample is a sample which is recorded for a remote machine #[derive(Debug, Serialize, Clone)] pub struct RemoteSample { pub id: u32, @@ -155,6 +169,8 @@ pub struct RemoteSample { pub sample: Sample, } +/// parse a path, or rather a pseudopath, which is a path with less validations +/// (all paths are pseudopaths, but not all pseudopaths are paths) fn pseudopath(input: Input) -> Result<&str> { recognize(many1(one_of("abcdefghijklmnopqrstuvwxyz/_")))(input) } @@ -189,6 +205,8 @@ impl From for Sample { } } +/// represents data that are stored on a signle line in the log file +/// (i.e. a single point in time) #[derive(Debug, Serialize, Clone)] pub struct Line { pub time: f64, @@ -215,12 +233,14 @@ impl Line { } } +/// the log file itself as parsed by the parser #[derive(Debug, Serialize, Clone)] pub struct LogFile { pub lines: Vec, } impl LogFile { + /// parses the log file pub fn parse(input: Input) -> Result { map( many0(map(tuple((Line::parse, multispace0)), |r| r.0)), @@ -228,6 +248,7 @@ impl LogFile { )(input) } + /// utility for getting all ids of all local devices that are recorded in the log pub fn local_ids(&self) -> Vec { self.lines .iter() @@ -235,6 +256,7 @@ impl LogFile { .collect() } + /// utility for getting all samples for a specific local device pub fn local(&self, id: u32) -> Vec { self.lines .iter() @@ -243,6 +265,7 @@ impl LogFile { .collect() } + /// utility for getting all ids of all remote devices that are recorded in the log pub fn remote_ids(&self) -> Vec { self.lines .iter() @@ -250,6 +273,7 @@ impl LogFile { .collect() } + /// utility for getting all samples for a specific remote device pub fn remote(&self, id: u32) -> Vec { self.lines .iter() diff --git a/netvr-rust/analyse/src/plot.rs b/netvr-rust/analyse/src/plot.rs index 09a06d8..5893d88 100644 --- a/netvr-rust/analyse/src/plot.rs +++ b/netvr-rust/analyse/src/plot.rs @@ -14,6 +14,7 @@ fn f64_cmp(a: &&f64, b: &&f64) -> std::cmp::Ordering { a.partial_cmp(b).unwrap_or(Equal) } +/// plots stuff and writes to file pub fn plot(input: PlotInput) -> Result<()> { let root = SVGBackend::new(&input.out_file_name, (800, 400)).into_drawing_area(); diff --git a/netvr-rust/analyse/src/plot_positions.rs b/netvr-rust/analyse/src/plot_positions.rs index e0e8595..a917fbb 100644 --- a/netvr-rust/analyse/src/plot_positions.rs +++ b/netvr-rust/analyse/src/plot_positions.rs @@ -44,6 +44,7 @@ fn expand_range(range: &std::ops::Range, target_size: f64) -> std::ops::Ran range.start - diff / 2.0..range.end + diff / 2.0 } +/// plots positions and saves to file pub fn plot(input: PlotInput) -> Result<()> { let area = SVGBackend::new(&input.out_file_name, (1024, 760)).into_drawing_area(); diff --git a/netvr-rust/codegen/build.rs b/netvr-rust/codegen/build.rs index 3c843e8..eba35d7 100644 --- a/netvr-rust/codegen/build.rs +++ b/netvr-rust/codegen/build.rs @@ -3,6 +3,7 @@ use std::{env, fs, path::Path}; use netvr_plugin::codegen; use serde_reflection::{Tracer, TracerConfig}; +/// Generate the C# code for the Unity plugin on build fn main() -> Result<(), Box> { let out_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let dest_path = Path::new(&out_dir) diff --git a/netvr-rust/codegen/src/main.rs b/netvr-rust/codegen/src/main.rs index f328e4d..6b52e0d 100644 --- a/netvr-rust/codegen/src/main.rs +++ b/netvr-rust/codegen/src/main.rs @@ -1 +1,2 @@ +/// does not do anything fn main() {} diff --git a/netvr-rust/netvr_calibrate/src/calibrate.rs b/netvr-rust/netvr_calibrate/src/calibrate.rs index 705d37a..cc3f8a0 100644 --- a/netvr-rust/netvr_calibrate/src/calibrate.rs +++ b/netvr-rust/netvr_calibrate/src/calibrate.rs @@ -282,6 +282,8 @@ fn match_samples(input: &CalibrationInput) -> Vec { matches } +/// Compute the calibration from the pairs of samples. +/// Port of the original C++ code from OpenVR Space Calibrator. pub fn calibrate(samples: &CalibrationInput) -> Result { // Notes from original code: // - it applies rotation right when it determines it @@ -333,6 +335,7 @@ pub fn calibrate(samples: &CalibrationInput) -> Result { }) } +/// Utility function for inverting the Y rotation of a quaternion. pub fn invert_y_rotation(quat: netvr_data::Quaternion) -> netvr_data::Quaternion { let quat = convert_quaternion(quat); let euler = quat.euler_angles(); @@ -346,6 +349,7 @@ pub fn invert_y_rotation(quat: netvr_data::Quaternion) -> netvr_data::Quaternion } } +/// Inverts a quaternion. pub fn invert_quaternion(quat: netvr_data::Quaternion) -> netvr_data::Quaternion { let quat = convert_quaternion(quat); let quat = quat.inverse(); @@ -359,6 +363,7 @@ pub fn invert_quaternion(quat: netvr_data::Quaternion) -> netvr_data::Quaternion } } +///Rotates a vector by a quaternion. pub fn rotate_vector(vec3: netvr_data::Vec3, quat: netvr_data::Quaternion) -> netvr_data::Vec3 { let quat = convert_quaternion(quat); let vec3 = convert_vector(vec3); diff --git a/netvr-rust/netvr_calibrate/src/input.rs b/netvr-rust/netvr_calibrate/src/input.rs index d910e1b..14bab66 100644 --- a/netvr-rust/netvr_calibrate/src/input.rs +++ b/netvr-rust/netvr_calibrate/src/input.rs @@ -1,12 +1,14 @@ use netvr_data::{net::CalibrationSample, Quaternion, Vec3}; use serde::{Deserialize, Serialize}; +/// Calibration result #[derive(Serialize, Default, Clone, Debug)] pub struct CalibrationResult { pub translation: Vec3, pub rotation: Quaternion, } +/// Everything needed to compute a calibration #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CalibrationInput { pub target: Vec, diff --git a/netvr-rust/netvr_calibrate/src/lib.rs b/netvr-rust/netvr_calibrate/src/lib.rs index b95c754..4bb50c1 100644 --- a/netvr-rust/netvr_calibrate/src/lib.rs +++ b/netvr-rust/netvr_calibrate/src/lib.rs @@ -8,6 +8,7 @@ pub use input::*; #[cfg(target_arch = "wasm32")] use wasm_bindgen::prelude::*; +/// Calibration result. Only used on the web. #[cfg(target_arch = "wasm32")] #[derive(serde::Serialize)] pub struct CalibrationResultCompat { @@ -16,6 +17,7 @@ pub struct CalibrationResultCompat { pub rotateq: netvr_data::Quaternion, } +/// Compute calibration from samples. Only used on the web. #[cfg(target_arch = "wasm32")] #[wasm_bindgen] pub fn compute(samples: &str) -> String { diff --git a/netvr-rust/netvr_client/src/error.rs b/netvr-rust/netvr_client/src/error.rs index f7eff05..742fbe1 100644 --- a/netvr-rust/netvr_client/src/error.rs +++ b/netvr-rust/netvr_client/src/error.rs @@ -1,6 +1,7 @@ use netvr_data::bincode; use tokio::io; +/// Error type for netvr_client #[derive(thiserror::Error, Debug)] pub enum Error { #[error("netvr connection encountered IO problem")] diff --git a/netvr-rust/netvr_client/src/lib.rs b/netvr-rust/netvr_client/src/lib.rs index 04ca06a..847ced5 100644 --- a/netvr-rust/netvr_client/src/lib.rs +++ b/netvr-rust/netvr_client/src/lib.rs @@ -65,6 +65,7 @@ pub async fn connect(log: fn(String) -> ()) -> Result { } } +/// Sets up a connection to the server. async fn setup_connection( log: fn(String) -> (), addr: SocketAddr, diff --git a/netvr-rust/netvr_client/src/main.rs b/netvr-rust/netvr_client/src/main.rs index b8b9d54..1e6ddf9 100644 --- a/netvr-rust/netvr_client/src/main.rs +++ b/netvr-rust/netvr_client/src/main.rs @@ -3,6 +3,7 @@ use std::time::Duration; use netvr_client::connect; use quinn::VarInt; +/// Utility for verifying that the connection code still works. #[tokio::main] async fn main() -> Result<(), Box> { println!("Hello there! I'm looking for NetVR devices..."); diff --git a/netvr-rust/netvr_client/src/quinn_connect.rs b/netvr-rust/netvr_client/src/quinn_connect.rs index a9b8e03..002abcd 100644 --- a/netvr-rust/netvr_client/src/quinn_connect.rs +++ b/netvr-rust/netvr_client/src/quinn_connect.rs @@ -7,6 +7,8 @@ use quinn::{ClientConfig, Connection, Endpoint}; use crate::error::Error; +/// Connects the the server and returns the endpoint and connection. +/// Makes sure that certificates are ignored. pub(crate) async fn quinn_connect( server_addr: SocketAddr, ) -> Result<(Endpoint, Connection), Error> { diff --git a/netvr-rust/netvr_data/src/app.rs b/netvr-rust/netvr_data/src/app.rs index 9b2bbfc..187c658 100644 --- a/netvr-rust/netvr_data/src/app.rs +++ b/netvr-rust/netvr_data/src/app.rs @@ -2,22 +2,26 @@ use serde::{Deserialize, Serialize}; use crate::Pose; +/// List of all poses of all objects in the scene #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct Snapshot { pub objects: Vec, } +/// Messages that the client can send to the server about the syncrhonized objects #[derive(Serialize, Deserialize, Clone, Debug)] pub enum AppUp { Init(Snapshot), Grab(u32), } +/// Messages that the server can send to the client about the synchronized objects #[derive(Serialize, Deserialize, Clone, Debug)] pub enum AppDown { Release(u32), } +/// Datagrams that the client can send to the server about the synchronized objects #[derive(Serialize, Deserialize, Clone, Debug)] pub enum AppDatagramUp { SetPose(usize, Pose), diff --git a/netvr-rust/netvr_data/src/framing.rs b/netvr-rust/netvr_data/src/framing.rs index d12b578..46e2ebf 100644 --- a/netvr-rust/netvr_data/src/framing.rs +++ b/netvr-rust/netvr_data/src/framing.rs @@ -3,6 +3,7 @@ use quinn::Connection; use thiserror::Error; +/// Error type for when framing fails #[derive(Debug, Error)] pub enum FramingError { #[error("failed to read from stream")] @@ -19,6 +20,7 @@ pub enum FramingError { ConnectionError(#[from] quinn::ConnectionError), } +/// Converts a stream to Frames. You can read from this. pub struct RecvFrames { __marker: std::marker::PhantomData, inner: quinn::RecvStream, @@ -58,6 +60,7 @@ impl RecvFrames { } } +/// Converts a stream to Frames. You can write into this. pub struct SendFrames { __marker: std::marker::PhantomData, inner: quinn::SendStream, diff --git a/netvr-rust/netvr_data/src/handle_serializer.rs b/netvr-rust/netvr_data/src/handle_serializer.rs index bf1de74..4bbbb2c 100644 --- a/netvr-rust/netvr_data/src/handle_serializer.rs +++ b/netvr-rust/netvr_data/src/handle_serializer.rs @@ -1,5 +1,7 @@ #![allow(dead_code)] +/// Create a handle serializer so that raw openxr handles can be used in serde +/// structs instead of having to drop down to u64. macro_rules! handle { ($mod:ident, $id:ident) => { #[cfg(not(target_arch = "wasm32"))] diff --git a/netvr-rust/netvr_data/src/lib.rs b/netvr-rust/netvr_data/src/lib.rs index b15009d..966166b 100644 --- a/netvr-rust/netvr_data/src/lib.rs +++ b/netvr-rust/netvr_data/src/lib.rs @@ -7,6 +7,7 @@ use std::collections::HashMap; use net::{ClientId, RemoteConfigurationSnapshot, StateSnapshot}; use serde::{Deserialize, Serialize}; +/// 3D vector for network communication #[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq)] pub struct Vec3 { pub x: f32, @@ -36,6 +37,7 @@ impl From for openxr_sys::Vector3f { } } +/// Quaternion for network communication #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct Quaternion { pub x: f32, @@ -79,6 +81,7 @@ impl From for openxr_sys::Quaternionf { } } +/// Device configuration of a device on a remote client #[derive(Serialize, Deserialize, Default)] pub struct RemoteDevice { // TODO: consider changing to u64 to be able to comfortably fit client id + @@ -90,6 +93,7 @@ pub struct RemoteDevice { pub interaction_profile: String, } +/// Pose. This is a position and orientation in 3D space #[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq)] pub struct Pose { pub position: Vec3, @@ -116,11 +120,13 @@ impl From for openxr_sys::Posef { } } +/// Result of reading remote devices #[derive(Serialize, Deserialize, Default)] pub struct ReadRemoteDevicesOutput { pub devices: Vec, } +/// Input type for interacting with functions which only need the OpenXR instance #[cfg(not(target_arch = "wasm32"))] #[derive(Serialize, Deserialize)] pub struct JustInstance { @@ -128,6 +134,7 @@ pub struct JustInstance { pub instance: openxr_sys::Instance, } +/// Input type for interacting with functions which only need the OpenXR instance + session #[cfg(not(target_arch = "wasm32"))] #[derive(Serialize, Deserialize)] pub struct InstanceAndSession { @@ -137,6 +144,7 @@ pub struct InstanceAndSession { pub session: openxr_sys::Session, } +/// Input for Start function #[cfg(not(target_arch = "wasm32"))] #[derive(Serialize, Deserialize)] pub struct StartInput { @@ -147,23 +155,28 @@ pub struct StartInput { pub data_directory: String, } +/// Snaphot for remote client #[derive(Default, Serialize, Deserialize, Debug, Clone)] pub struct RemoteClientSnapshot { pub configuration: RemoteConfigurationSnapshot, pub state: StateSnapshot, } +/// Snaphot for all remote clients #[derive(Default, Serialize, Deserialize, Debug, Clone)] pub struct RemoteSnapshot { pub clients: HashMap, } +/// Functions which don't need any output should return this #[derive(Serialize, Deserialize, Default)] pub struct Nothing(u8); +/// For passing strings #[derive(Serialize, Deserialize, Default)] pub struct OnlyString(pub String); +/// Input for InitRemoteOjbects function #[cfg(not(target_arch = "wasm32"))] #[derive(Serialize, Deserialize)] pub struct InitRemoteObjectsInput { @@ -174,6 +187,7 @@ pub struct InitRemoteObjectsInput { pub snapshot: app::Snapshot, } +/// Input for Grab function #[cfg(not(target_arch = "wasm32"))] #[derive(Serialize, Deserialize)] pub struct GrabInput { @@ -184,6 +198,7 @@ pub struct GrabInput { pub object_id: u32, } +/// Input for SetPose function #[cfg(not(target_arch = "wasm32"))] #[derive(Serialize, Deserialize)] pub struct SetPoseInput { diff --git a/netvr-rust/netvr_data/src/net.rs b/netvr-rust/netvr_data/src/net.rs index 0cb03a2..b4eb114 100644 --- a/netvr-rust/netvr_data/src/net.rs +++ b/netvr-rust/netvr_data/src/net.rs @@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize}; use crate::{app, Pose}; +/// Response from discovery server #[derive(Serialize, Deserialize)] pub struct DiscoveryResponse { header: [u8; 5], @@ -23,12 +24,14 @@ impl Default for DiscoveryResponse { } } +/// Space to be used for calibration sample collection #[derive(Serialize, Deserialize, Debug, Clone, Copy)] pub enum BaseSpace { Server, Stage, } +/// What is sent for changing calibration from server to clients #[derive(Serialize, Deserialize, Clone, Debug)] pub enum ConfigurationDown { Snapshot(ConfigurationSnapshotSet), @@ -39,6 +42,7 @@ pub enum ConfigurationDown { ChangeName(String), } +/// Controller data #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct Controller { pub interaction_profile: u8, @@ -46,6 +50,7 @@ pub struct Controller { pub pose: Pose, } +/// State snapshot #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct StateSnapshot { pub controllers: Vec, @@ -53,6 +58,7 @@ pub struct StateSnapshot { pub required_configuration: u32, } +/// Type of OpenXR acction but serializable #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub enum ActionType { Boolean = 1, @@ -78,6 +84,7 @@ impl From for ActionType { } } +/// Remote OpenXR action data #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct RemoteAction { #[serde(rename = "type")] @@ -87,12 +94,14 @@ pub struct RemoteAction { pub binding: String, } +/// Remote interaction profile data #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct RemoteInteractionProfile { pub path: String, pub bindings: Vec, } +/// Data of a remote configuration. #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct RemoteConfigurationSnapshot { pub version: u32, @@ -101,17 +110,20 @@ pub struct RemoteConfigurationSnapshot { pub name: String, } +/// Data of all remote configurations. #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct ConfigurationSnapshotSet { pub clients: HashMap, } +/// What is sent when local configuration changes to notify the server #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ConfigurationUp { Hello, ConfigurationSnapshot(RemoteConfigurationSnapshot), } +/// Sample used for calibration #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CalibrationSample { pub flags: u64, @@ -124,14 +136,17 @@ pub struct CalibrationSample { pub now_nanos: i64, } +/// Configratiuon options for calibration #[derive(Serialize, Deserialize, Debug, Clone, Copy)] pub struct CalibrationConfiguration { pub sample_count: usize, pub sample_interval_nanos: i64, } +/// Id of a client pub type ClientId = u32; +/// All remote snapshots + order to make sure stale snapshots are not applied. #[derive(Serialize, Deserialize, Default, Clone, Debug)] pub struct RemoteStateSnapshotSet { /// Makes sure that we do not apply older snapshots, if they arrive out of @@ -140,18 +155,22 @@ pub struct RemoteStateSnapshotSet { pub clients: HashMap, } +/// What is sent from server to client over unrealiable channel #[derive(Serialize, Deserialize, Clone, Debug)] pub enum DatagramDown { App(app::Snapshot), State(RemoteStateSnapshotSet), } +/// Whati s sent from client to server over unrealiable channel #[derive(Serialize, Deserialize, Clone, Debug)] pub enum DatagramUp { State(StateSnapshot), App(app::AppDatagramUp), } +/// Sent periodically to check that connection is still alive +/// ... this was triumph, I'm making a note here: huge success #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Heartbeat { _buf: [u8; 5], diff --git a/netvr-rust/netvr_plugin/src/config.rs b/netvr-rust/netvr_plugin/src/config.rs index 86e3af5..1de1379 100644 --- a/netvr-rust/netvr_plugin/src/config.rs +++ b/netvr-rust/netvr_plugin/src/config.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use tokio::fs; use xr_layer::log::LogWarn; +/// Stored data to be recovered on app restarts #[derive(Serialize, Deserialize, Debug, Default)] pub(crate) struct Config { pub name: String, diff --git a/netvr-rust/netvr_plugin/src/implementation.rs b/netvr-rust/netvr_plugin/src/implementation.rs index bf789d6..60954c4 100644 --- a/netvr-rust/netvr_plugin/src/implementation.rs +++ b/netvr-rust/netvr_plugin/src/implementation.rs @@ -47,6 +47,7 @@ pub(crate) fn start(input: StartInput) -> Result { }) } +/// Reads information about the remote devices. pub(crate) fn read_remote_devices( input: InstanceAndSession, ) -> Result { @@ -99,6 +100,7 @@ pub(crate) fn read_remote_devices( }) } +/// Sets poses of all objects. pub(crate) fn read_remote_objects(input: InstanceAndSession) -> Result { with_layer(input.instance, |instance| { let session = instance @@ -125,6 +127,7 @@ pub(crate) fn read_remote_objects(input: InstanceAndSession) -> Result Result { with_layer(input.instance, |instance| { let session = instance @@ -143,6 +146,7 @@ pub(crate) fn init_remote_objects(input: InitRemoteObjectsInput) -> Result Result { with_layer(input.instance, |instance| { let session = instance @@ -174,6 +178,7 @@ pub(crate) fn grab(input: GrabInput) -> Result { }) } +/// Revokes ownership of an object so that we don't have to send its pose anymore. pub(crate) fn release(input: GrabInput) -> Result { with_layer(input.instance, |instance| { let session = instance @@ -190,6 +195,7 @@ pub(crate) fn release(input: GrabInput) -> Result { }) } +/// Set pose of an object. pub(crate) fn object_set_pose(input: SetPoseInput) -> Result { with_layer(input.instance, |instance| { let session = instance @@ -211,6 +217,8 @@ pub(crate) fn object_set_pose(input: SetPoseInput) -> Result { }) } +/// Returns the server address of the server so that you can upload files if you +/// want to. pub(crate) fn get_server_address(input: InstanceAndSession) -> Result { with_layer(input.instance, |instance| { let session = instance diff --git a/netvr-rust/netvr_plugin/src/instance.rs b/netvr-rust/netvr_plugin/src/instance.rs index 7f0c729..f5d0bde 100644 --- a/netvr-rust/netvr_plugin/src/instance.rs +++ b/netvr-rust/netvr_plugin/src/instance.rs @@ -176,6 +176,7 @@ impl Debug for Session { } } +/// Data stored relevant to this OpenXR object #[derive(Debug, Clone)] pub(crate) struct Action { pub(crate) handle: sys::Action, @@ -200,7 +201,7 @@ impl XrDebug for Action { .finish() } } - +/// Data stored relevant to this OpenXR object #[derive(Debug, Clone, Default)] pub(crate) struct ActionSet { pub(crate) actions: Vec, diff --git a/netvr-rust/netvr_plugin/src/lib.rs b/netvr-rust/netvr_plugin/src/lib.rs index 3649b23..3d035bf 100644 --- a/netvr-rust/netvr_plugin/src/lib.rs +++ b/netvr-rust/netvr_plugin/src/lib.rs @@ -68,6 +68,7 @@ pub extern "C" fn netvr_set_logger(func: log::LoggerFn) { pub use bincode_abi::netvr_cleanup; +/// Exposes the functions to C# bincode_expose!( expose read_remote_devices as ReadRemoteDevices taking InstanceAndSession and outputting ReadRemoteDevicesOutput, expose start as Start taking StartInput and outputting Nothing, diff --git a/netvr-rust/netvr_plugin/src/local_configuration.rs b/netvr-rust/netvr_plugin/src/local_configuration.rs index 67ef1ef..48f9fc0 100644 --- a/netvr-rust/netvr_plugin/src/local_configuration.rs +++ b/netvr-rust/netvr_plugin/src/local_configuration.rs @@ -5,6 +5,7 @@ use netvr_data::net::{ }; use xr_layer::sys; +/// Local info for this OpenXR structure #[derive(Default, Clone, Debug)] pub(crate) struct Action { pub ty: ActionType, @@ -26,6 +27,7 @@ impl From for RemoteAction { } } +/// Local info for this OpenXR structure #[derive(Default, Clone, Debug)] pub(crate) struct InteractionProfile { pub path: String, @@ -42,6 +44,7 @@ impl From for RemoteInteractionProfile { } } +/// All local configuration to be synchronized with the server #[derive(Default, Clone, Debug)] pub(crate) struct LocalConfigurationSnapshot { pub version: u32, diff --git a/netvr-rust/netvr_plugin/src/overrides.rs b/netvr-rust/netvr_plugin/src/overrides.rs index c14e52e..6033951 100644 --- a/netvr-rust/netvr_plugin/src/overrides.rs +++ b/netvr-rust/netvr_plugin/src/overrides.rs @@ -175,6 +175,9 @@ where }) } +/// To be returned from the hook. This is the main workhorse of the layer as it +/// is the function that is called by the runtime when it wants to call any +/// other function from openxr and this allows use to do our magic. extern "system" fn get_instance_proc_addr( instance: sys::Instance, name: *const c_char, @@ -212,6 +215,8 @@ extern "system" fn get_instance_proc_addr( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn create_instance( create_info_ptr: *const sys::InstanceCreateInfo, instance_ptr: *mut sys::Instance, @@ -285,7 +290,8 @@ extern "system" fn create_instance( result.into_result() }) } - +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn destroy_instance(instance_handle: sys::Instance) -> sys::Result { wrap_mut(|layer| { let _span = trace_span!("destroy_instance").entered(); @@ -362,6 +368,8 @@ fn instance_ref_delete( read_instance_mut(&mut layer.instances, instance_handle) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn poll_event( instance_handle: sys::Instance, event_data: *mut sys::EventDataBuffer, @@ -396,6 +404,8 @@ extern "system" fn poll_event( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn create_action_set( instance_handle: sys::Instance, info: *const sys::ActionSetCreateInfo, @@ -424,6 +434,8 @@ extern "system" fn create_action_set( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn destroy_action_set(action_set: sys::ActionSet) -> sys::Result { wrap_mut(|layer| { let _span = trace_span!("create_action_set").entered(); @@ -438,6 +450,8 @@ extern "system" fn destroy_action_set(action_set: sys::ActionSet) -> sys::Result }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn create_action( action_set_handle: sys::ActionSet, info_in: *const sys::ActionCreateInfo, @@ -475,6 +489,8 @@ extern "system" fn create_action( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn string_to_path( instance_handle: sys::Instance, path_string_raw: *const c_char, @@ -500,6 +516,8 @@ extern "system" fn string_to_path( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn suggest_interaction_profile_bindings( instance_handle: sys::Instance, suggested_bindings: *const sys::InteractionProfileSuggestedBinding, @@ -544,6 +562,8 @@ extern "system" fn suggest_interaction_profile_bindings( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn create_session( instance_handle: sys::Instance, create_info_ptr: *const sys::SessionCreateInfo, @@ -584,6 +604,8 @@ extern "system" fn create_session( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn destroy_session(session_handle: sys::Session) -> sys::Result { wrap_mut(|layer| { let _span = trace_span!("destroy_session").entered(); @@ -603,6 +625,8 @@ extern "system" fn destroy_session(session_handle: sys::Session) -> sys::Result }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn begin_session( session_handle: sys::Session, begin_info_ptr: *const sys::SessionBeginInfo, @@ -627,6 +651,8 @@ extern "system" fn begin_session( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn get_current_interaction_profile( session_handle: sys::Session, top_level_user_path: sys::Path, @@ -665,6 +691,8 @@ extern "system" fn get_current_interaction_profile( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn sync_actions( session_handle: sys::Session, sync_info: *const sys::ActionsSyncInfo, @@ -691,6 +719,8 @@ extern "system" fn sync_actions( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn get_action_state_boolean( session_handle: sys::Session, get_info_ptr: *const sys::ActionStateGetInfo, @@ -715,6 +745,8 @@ extern "system" fn get_action_state_boolean( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn get_action_state_vector2f( session_handle: sys::Session, get_info: *const sys::ActionStateGetInfo, @@ -730,6 +762,8 @@ extern "system" fn get_action_state_vector2f( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn get_action_state_pose( session_handle: sys::Session, get_info: *const sys::ActionStateGetInfo, @@ -745,6 +779,8 @@ extern "system" fn get_action_state_pose( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn apply_haptic_feedback( session_handle: sys::Session, haptic_action_info: *const sys::HapticActionInfo, @@ -765,6 +801,7 @@ extern "system" fn apply_haptic_feedback( }) } +/// Utility function for getting the layer data for a given instance. pub(crate) fn with_layer(handle: sys::Instance, cb: T) -> anyhow::Result where T: FnOnce(&Instance) -> anyhow::Result, @@ -777,6 +814,8 @@ where layer.trace.wrap(|| cb(instance)) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn wait_frame( session_handle: sys::Session, frame_wait_info: *const sys::FrameWaitInfo, @@ -801,6 +840,8 @@ extern "system" fn wait_frame( }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. macro_rules! simple_s { ($id: ident ($farg: ident: $fty: ty, $($arg: ident: $ty: ty, ) *)) => { extern "system" fn $id( @@ -818,6 +859,8 @@ macro_rules! simple_s { }; } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. macro_rules! simple_i { ($id: ident ($farg: ident: $fty: ty, $($arg: ident: $ty: ty), *,)) => { #[allow(dead_code)] @@ -836,6 +879,8 @@ macro_rules! simple_i { }; } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn locate_views( session_handle: sys::Session, view_locate_info: *const sys::ViewLocateInfo, @@ -868,6 +913,8 @@ extern "system" fn locate_views( }) } +/// Main workhorse of calibration application. If it detects Stage space it +/// rewrites it to be the Server space. fn rewrite_space(session: &Session, space: &mut sys::Space) { if let Ok(spaces) = session.application_stage_spaces.read() { if spaces.contains(space) { @@ -889,6 +936,8 @@ simple_s!(get_action_state_float( state: *mut sys::ActionStateFloat, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn attach_session_action_sets( session_handle: sys::Session, attach_info: *const sys::SessionActionSetsAttachInfo, @@ -994,38 +1043,56 @@ fn util_create_action_space( Ok(space) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(result_to_string( instance: sys::Instance, value: sys::Result, buffer: *mut c_char, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(structure_type_to_string( instance: sys::Instance, value: sys::StructureType, buffer: *mut c_char, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(get_instance_properties( instance: sys::Instance, instance_properties: *mut sys::InstanceProperties, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(get_system( instance: sys::Instance, get_info: *const sys::SystemGetInfo, system_id: *mut sys::SystemId, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(get_system_properties( instance: sys::Instance, system_id: sys::SystemId, properties: *mut sys::SystemProperties, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_s!(end_session(session: sys::Session,)); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_s!(request_exit_session(session: sys::Session,)); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_s!(enumerate_reference_spaces( session: sys::Session, space_capacity_input: u32, space_count_output: *mut u32, spaces: *mut sys::ReferenceSpaceType, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn create_reference_space( session: sys::Session, create_info: *const sys::ReferenceSpaceCreateInfo, @@ -1067,6 +1134,8 @@ extern "system" fn create_reference_space( result }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn create_action_space( session: sys::Session, create_info: *const sys::ActionSpaceCreateInfo, @@ -1099,6 +1168,8 @@ extern "system" fn create_action_space( result }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(enumerate_view_configurations( instance: sys::Instance, system_id: sys::SystemId, @@ -1106,6 +1177,8 @@ simple_i!(enumerate_view_configurations( view_configuration_type_count_output: *mut u32, view_configuration_types: *mut sys::ViewConfigurationType, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(enumerate_environment_blend_modes( instance: sys::Instance, system_id: sys::SystemId, @@ -1114,12 +1187,16 @@ simple_i!(enumerate_environment_blend_modes( environment_blend_mode_count_output: *mut u32, environment_blend_modes: *mut sys::EnvironmentBlendMode, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(get_view_configuration_properties( instance: sys::Instance, system_id: sys::SystemId, view_configuration_type: sys::ViewConfigurationType, configuration_properties: *mut sys::ViewConfigurationProperties, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(enumerate_view_configuration_views( instance: sys::Instance, system_id: sys::SystemId, @@ -1128,10 +1205,14 @@ simple_i!(enumerate_view_configuration_views( view_count_output: *mut u32, views: *mut sys::ViewConfigurationView, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_s!(begin_frame( session: sys::Session, frame_begin_info: *const sys::FrameBeginInfo, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn end_frame( session_handle: sys::Session, frame_end_info_ptr: *const sys::FrameEndInfo, @@ -1176,10 +1257,14 @@ extern "system" fn end_frame( result }) } +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_s!(stop_haptic_feedback( session: sys::Session, haptic_action_info: *const sys::HapticActionInfo, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_i!(path_to_string( instance: sys::Instance, path: sys::Path, @@ -1187,11 +1272,15 @@ simple_i!(path_to_string( buffer_count_output: *mut u32, buffer: *mut c_char, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_s!(get_reference_space_bounds_rect( session: sys::Session, reference_space_type: sys::ReferenceSpaceType, bounds: *mut sys::Extent2Df, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_s!(get_input_source_localized_name( session: sys::Session, get_info: *const sys::InputSourceLocalizedNameGetInfo, @@ -1199,6 +1288,8 @@ simple_s!(get_input_source_localized_name( buffer_count_output: *mut u32, buffer: *mut c_char, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. simple_s!(enumerate_bound_sources_for_action( session_handle: sys::Session, enumerate_info: *const sys::BoundSourcesForActionEnumerateInfo, @@ -1207,6 +1298,8 @@ simple_s!(enumerate_bound_sources_for_action( sources: *mut sys::Path, )); +/// Our implementation of this openxr function. Does our magic and then calls +/// the runtime's implementation, if appropriate. extern "system" fn locate_space( space: sys::Space, base_space: sys::Space, diff --git a/netvr-rust/netvr_plugin/src/xr_wrap.rs b/netvr-rust/netvr_plugin/src/xr_wrap.rs index f97d6dc..73a2b4d 100644 --- a/netvr-rust/netvr_plugin/src/xr_wrap.rs +++ b/netvr-rust/netvr_plugin/src/xr_wrap.rs @@ -183,6 +183,7 @@ impl Trace { } } +/// Useful for debugging and can be used for printing stuff more easily. pub(crate) trait RecordDebug { fn record_debug(&self, field: &'static str, debug: T) where diff --git a/netvr-rust/netvr_server/src/accept_connection.rs b/netvr-rust/netvr_server/src/accept_connection.rs index 0aa023c..35c140c 100644 --- a/netvr-rust/netvr_server/src/accept_connection.rs +++ b/netvr-rust/netvr_server/src/accept_connection.rs @@ -17,6 +17,7 @@ use crate::{ server::Server, }; +/// Accepts a connection and runs it until it is closed. pub(crate) async fn accept_connection( connecting: Connecting, server: Server, @@ -51,6 +52,7 @@ pub(crate) async fn accept_connection( server.remove_client(id).await; } +/// Handles the connection from start to end async fn run_connection( connecting: Connecting, token: CancellationToken, diff --git a/netvr-rust/netvr_server/src/app.rs b/netvr-rust/netvr_server/src/app.rs index 9e35458..a170aee 100644 --- a/netvr-rust/netvr_server/src/app.rs +++ b/netvr-rust/netvr_server/src/app.rs @@ -14,6 +14,7 @@ struct AppObject { pose: Pose, } +/// Holds data related to synchronized objects pub(crate) struct AppServer { channel: mpsc::UnboundedReceiver, initial_state: Vec, @@ -29,6 +30,7 @@ enum UpMessage { ResetObjects, } +/// Message for working with synchronized objects #[derive(Debug)] pub(crate) enum AppServerMessage { Datagram(ClientId, AppDatagramUp), @@ -36,9 +38,11 @@ pub(crate) enum AppServerMessage { ResetObjects, } +/// Channel for passing messages instructing changes to synchronized objects pub(crate) type AppChannel = mpsc::UnboundedSender; impl AppServer { + /// Prepare everything for running the synchronized object system pub(crate) fn start(server: Server) -> (Self, AppChannel) { let channel = mpsc::unbounded_channel::(); @@ -76,6 +80,7 @@ impl AppServer { )) } + /// Actually runs the synchronized object system pub(crate) async fn run(&mut self) -> Result<()> { let mut interval = tokio::time::interval(std::time::Duration::from_millis(20)); loop { diff --git a/netvr-rust/netvr_server/src/calibration_protocol.rs b/netvr-rust/netvr_server/src/calibration_protocol.rs index e78405f..a74e6cc 100644 --- a/netvr-rust/netvr_server/src/calibration_protocol.rs +++ b/netvr-rust/netvr_server/src/calibration_protocol.rs @@ -24,12 +24,15 @@ use tokio::{ use self::CalibrationProtocolMessage::*; use crate::{client::Client, dashboard::DashboardMessage, server::Server}; +/// Calibration protocol subsystem data pub(crate) struct CalibrationProtocol { recv: mpsc::UnboundedReceiver, } +/// Channel for passing messages instructing what to do in the calibration subsystem pub(crate) type CalibrationSender = mpsc::UnboundedSender; +/// All the things that could be done in the calibration subsystem #[derive(Debug, Clone)] pub(crate) enum CalibrationProtocolMessage { Begin { @@ -69,6 +72,7 @@ impl CalibrationProtocol { } } +/// Runs the calibration subsystem loop async fn run( mut recv: mpsc::UnboundedReceiver, server: Server, @@ -133,6 +137,7 @@ async fn run( Ok(()) } +/// Does one calibration async fn run_calibration( recv: &mut mpsc::UnboundedReceiver, client_target: (ClientId, String), @@ -234,6 +239,7 @@ async fn run_calibration( finish(tx.clone(), calibration, &client_target, &client_reference).await; } +/// Does one pseudo-calibration for logging data about the connected devices async fn run_hijack( recv: &mut mpsc::UnboundedReceiver, client_target: (ClientId, String), diff --git a/netvr-rust/netvr_server/src/client.rs b/netvr-rust/netvr_server/src/client.rs index 20f7bb0..8f35bf9 100644 --- a/netvr-rust/netvr_server/src/client.rs +++ b/netvr-rust/netvr_server/src/client.rs @@ -21,12 +21,14 @@ struct InnerClient { connection: Connection, } +/// Represnets one connected client #[derive(Clone)] pub(crate) struct Client { inner: Arc, } impl Client { + /// Crreate a new client pub(crate) fn new( ws: broadcast::Sender, token: CancellationToken, @@ -49,10 +51,12 @@ impl Client { } } + /// Call on configuration message pub async fn handle_configuration_up(&self, message: ConfigurationUp) { println!("Received configuration up {:?}", message); } + /// Call on datagram pub async fn handle_recv_snapshot(&self, message: StateSnapshot) -> Result<()> { // println!("Received datagram {:?}", message); let _ = self.ws().send(DashboardMessage::DatagramUp { @@ -65,21 +69,25 @@ impl Client { Ok(()) } + /// Dead code #[allow(dead_code)] pub(crate) fn ws(&self) -> &broadcast::Sender { &self.inner.ws } + /// Call when you want to send something to a client pub(crate) fn send_configuration_down(&self, message: ConfigurationDown) -> Result<()> { self.inner.configuration_down_queue.send(message)?; Ok(()) } + /// Call when you want to send something to a client pub(crate) fn send_app_down(&self, message: app::AppDown) -> Result<()> { self.inner.app_down_queue.send(message)?; Ok(()) } + /// Call when you want to send something to a client pub(crate) fn send_datagram(&self, datagram: &DatagramDown) -> Result<()> { self.inner .connection @@ -87,21 +95,25 @@ impl Client { Ok(()) } + /// Wait until the client is cancelled #[allow(dead_code)] pub(crate) fn cancelled(&self) -> tokio_util::sync::WaitForCancellationFuture { self.inner.token.cancelled() } + /// Check if the client is cancelled #[allow(dead_code)] pub(crate) fn is_cancelled(&self) -> bool { self.inner.token.is_cancelled() } + /// Cancel the client #[allow(dead_code)] pub(crate) fn cancel(&self) { self.inner.token.cancel() } + /// Get the client's id #[allow(dead_code)] pub(crate) fn id(&self) -> ClientId { self.inner.id diff --git a/netvr-rust/netvr_server/src/dashboard.rs b/netvr-rust/netvr_server/src/dashboard.rs index b496152..bd1be5f 100644 --- a/netvr-rust/netvr_server/src/dashboard.rs +++ b/netvr-rust/netvr_server/src/dashboard.rs @@ -29,6 +29,7 @@ use crate::{ server::Server, }; +/// All the messages that could be sent to the dashboard #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(tag = "type")] pub(crate) enum DashboardMessage { @@ -60,6 +61,7 @@ pub(crate) enum DashboardMessage { }, } +/// All the messages that could be received from the dashboard #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(tag = "type")] pub(crate) enum DashboardMessageRecv { @@ -112,6 +114,7 @@ pub(crate) enum DashboardMessageRecv { ResetObjects, } +/// Forward messages to the dashboard async fn dashboard_send( mut ws: SplitSink, mut receiver: broadcast::Receiver, @@ -157,6 +160,7 @@ async fn dashboard_send( } } +/// Handle messages from dashboard async fn dashboard_receive( mut ws: SplitStream, server: Server, @@ -329,6 +333,7 @@ async fn dashboard_receive( } } +/// Forward configuration changes to the dashboard. async fn dashboard_send_configuration( server: Server, reply: mpsc::UnboundedSender, @@ -349,6 +354,7 @@ async fn dashboard_send_configuration( } } +/// Handle when the dashboard connects. async fn dashboard_connected( ws: WebSocket, broadcast_receiver: broadcast::Receiver, @@ -370,6 +376,7 @@ fn get_upload_dir() -> std::path::PathBuf { upload_dir } +/// Main entry point for the dashboard subsystem. Serves dashboard on TCP port 13161 pub(crate) async fn serve_dashboard( tx: broadcast::Sender, server: Server, @@ -440,6 +447,7 @@ pub(crate) async fn serve_dashboard( Ok(()) } +/// Handles when a file is uploaded to the dashboard (used by logger.cs) async fn handle_upload( filename: String, bytes: Bytes, diff --git a/netvr-rust/netvr_server/src/main.rs b/netvr-rust/netvr_server/src/main.rs index c6e8b8b..316da94 100644 --- a/netvr-rust/netvr_server/src/main.rs +++ b/netvr-rust/netvr_server/src/main.rs @@ -28,6 +28,7 @@ mod my_socket; mod quinn_server; mod server; +/// Main entry point of netvr_server #[tokio::main(flavor = "multi_thread")] async fn main() -> Result<()> { let server_udp = Arc::new(UdpSocket::bind("0.0.0.0:0").await?); diff --git a/netvr-rust/netvr_server/src/server.rs b/netvr-rust/netvr_server/src/server.rs index ccc1b01..e96b3b1 100644 --- a/netvr-rust/netvr_server/src/server.rs +++ b/netvr-rust/netvr_server/src/server.rs @@ -27,6 +27,7 @@ type ServerChannel = tokio::sync::mpsc::Sender; type LatestSnaphots = Arc>; type LatestConfigurations = Arc>>; +/// Ful server state #[derive(Clone)] pub(crate) struct Server { clients: Arc>>, @@ -36,6 +37,7 @@ pub(crate) struct Server { } impl Server { + /// Prepare the server to be run pub async fn start() -> Self { let latest_snapshots: LatestSnaphots = Arc::default(); let latest_configurations: LatestConfigurations = @@ -101,10 +103,12 @@ impl Server { snapshot_channel } + /// Get the latest configuration snapshots pub async fn latest_configuration(&self) -> watch::Receiver { self.latest_configurations.read().await.subscribe() } + /// Set the latest state snapshot to a client pub async fn apply_snapshot(&self, id: ClientId, snapshot: StateSnapshot) { if let Err(err) = self .channel @@ -115,6 +119,7 @@ impl Server { } } + /// called when a new client connects pub async fn add_client(&self, client: Client) -> Result<()> { let mut clients = self.clients.lock().await; self.channel @@ -124,6 +129,7 @@ impl Server { Ok(()) } + /// Gets a random client (not really random, but only used for some debug stuff) pub async fn get_first_client(&self) -> Option { self.clients .lock() @@ -136,6 +142,7 @@ impl Server { .cloned() } + /// Gets all the clients pub async fn get_clients(&self) -> Vec<(u32, Client)> { self.clients .lock() @@ -145,11 +152,13 @@ impl Server { .collect() } + // Gets a client by id #[allow(dead_code)] pub async fn get_client(&self, id: ClientId) -> Option { self.clients.lock().await.get(&id).cloned() } + /// Deletes a client pub async fn remove_client(&self, id: ClientId) { let mut clients = self.clients.lock().await; if let Err(err) = self.channel.send(ServerChange::RemoveClient(id)).await { @@ -158,6 +167,7 @@ impl Server { clients.remove(&id); } + /// Applies a configuration to a client pub async fn apply_configuration(&self, id: ClientId, config: RemoteConfigurationSnapshot) { if let Err(err) = self .channel @@ -168,6 +178,7 @@ impl Server { } } + /// Gets all the latest state snapshots pub async fn read_latest_snapshots(&self) -> RemoteStateSnapshotSet { self.latest_snapshots.read().await.clone() } diff --git a/netvr-rust/xr_layer/build.rs b/netvr-rust/xr_layer/build.rs index f8e5858..a6b4803 100644 --- a/netvr-rust/xr_layer/build.rs +++ b/netvr-rust/xr_layer/build.rs @@ -1,5 +1,7 @@ use std::{env, time::SystemTime}; +/// Called when xr_layer is built. This makes sure that stuff is rebuilt in some +/// cases where it otherwise wouldn't be. fn main() { let profile = env::var("PROFILE").unwrap(); diff --git a/netvr-rust/xr_layer/src/loader.rs b/netvr-rust/xr_layer/src/loader.rs index 905984b..2c43431 100644 --- a/netvr-rust/xr_layer/src/loader.rs +++ b/netvr-rust/xr_layer/src/loader.rs @@ -4,6 +4,8 @@ use openxr_sys::pfn; use crate::{log::LogWarn, sys, utils::ResultConvertible, xr_listings::FnPtr}; +/// Abstraction for creating OpenXR layers. Works, but is somewhat unfinished +/// in the API design department. pub struct Layer { map: HashMap<&'static str, pfn::VoidFunction>, func: pfn::GetInstanceProcAddr, diff --git a/netvr-rust/xr_layer/src/log.rs b/netvr-rust/xr_layer/src/log.rs index b808202..d38b0d8 100644 --- a/netvr-rust/xr_layer/src/log.rs +++ b/netvr-rust/xr_layer/src/log.rs @@ -64,6 +64,7 @@ fn _string(level: Level, text: String) { _cstr(level, cstr.as_ptr()); } +/// Creates a exported object for logging at a specific level. macro_rules! implement { ($id:ident, $level:expr) => { pub struct $id {} @@ -89,6 +90,7 @@ implement!(LogWarn, Level::Warn); implement!(LogError, Level::Error); implement!(LogPanic, Level::Panic); +/// Change the global logger used by the above functions. pub fn set_logger(func: LoggerFn) { println!("Hello world from Rust!"); { diff --git a/netvr-rust/xr_layer/src/utils.rs b/netvr-rust/xr_layer/src/utils.rs index 9c1ef5d..f2bc7c3 100644 --- a/netvr-rust/xr_layer/src/utils.rs +++ b/netvr-rust/xr_layer/src/utils.rs @@ -3,10 +3,12 @@ use std::os::raw::c_char; use crate::{log::LogWarn, XrResult}; pub type Cstr = *const c_char; +/// Mark that a thing can be converted into XrResult pub(crate) trait ResultConvertible { fn into_result(self) -> XrResult<()>; } +/// sys::Result can be converted into XrResult impl ResultConvertible for openxr_sys::Result { fn into_result(self) -> XrResult<()> { if self == openxr_sys::Result::SUCCESS { @@ -17,6 +19,7 @@ impl ResultConvertible for openxr_sys::Result { } } +/// Convert result to warning. Probably unused pub(crate) trait ResultToWarning { fn warn_on_err(self, function_name: &'static str); } diff --git a/netvr-rust/xr_layer/src/xr_debug.rs b/netvr-rust/xr_layer/src/xr_debug.rs index 0836969..d480a15 100644 --- a/netvr-rust/xr_layer/src/xr_debug.rs +++ b/netvr-rust/xr_layer/src/xr_debug.rs @@ -14,7 +14,7 @@ impl<'a, T: XrDebug> fmt::Debug for XrDebugValue<'a, T> { } /// Allows object to be debugged with extra information obtained from OpenXR -/// runtime. +/// runtime. Implemented for a bunch of OpenXR types. pub trait XrDebug { /// Acts similarly to std::fmt::Debug::fmt but may call OpenXR function to /// reveal further detail about given object. diff --git a/netvr-rust/xr_layer/src/xr_listings.rs b/netvr-rust/xr_layer/src/xr_listings.rs index eb259d4..0a668f2 100644 --- a/netvr-rust/xr_layer/src/xr_listings.rs +++ b/netvr-rust/xr_layer/src/xr_listings.rs @@ -42,6 +42,7 @@ macro_rules! implement { } } +/// Generate the wrappers for the functions implement!( //#[cfg(target_os = "android")] //SetAndroidApplicationThreadKHR, diff --git a/netvr-rust/xr_layer/src/xr_struct.rs b/netvr-rust/xr_layer/src/xr_struct.rs index fda3794..18dcce5 100644 --- a/netvr-rust/xr_layer/src/xr_struct.rs +++ b/netvr-rust/xr_layer/src/xr_struct.rs @@ -9,12 +9,14 @@ use thiserror::Error; use crate::{SizedArrayValueIterator, XrDebug}; +/// Utility struct for reading various OpenXR structs safely by checking the ty. #[derive(Clone)] pub struct XrStruct { pub ty: openxr_sys::StructureType, data: *const openxr_sys::BaseInStructure, } +/// All of it looks the same, so let's make a macro. macro_rules! implement_struct { ($($id: ident), *,) => { $( @@ -181,6 +183,7 @@ impl XrStruct { } } +/// Error in parsing a string from OpenXR. #[derive(Debug, Error)] pub enum StringParseError { #[error("String is not null terminated")] diff --git a/netvr-rust/xr_layer/src/xr_struct_chain.rs b/netvr-rust/xr_layer/src/xr_struct_chain.rs index 404f957..144a4a4 100644 --- a/netvr-rust/xr_layer/src/xr_struct_chain.rs +++ b/netvr-rust/xr_layer/src/xr_struct_chain.rs @@ -1,5 +1,6 @@ use crate::{xr_struct::XrStruct, XrDebug}; +/// Implements the algorithm for traversing OpenXR next chains. #[derive(Clone)] pub struct XrStructChain { ptr: *const openxr_sys::BaseInStructure,