Skip to content

Commit

Permalink
rust docs
Browse files Browse the repository at this point in the history
  • Loading branch information
CodeWitchBella committed May 25, 2023
1 parent b507aba commit 1faa238
Show file tree
Hide file tree
Showing 40 changed files with 262 additions and 3 deletions.
7 changes: 7 additions & 0 deletions netvr-rust/analyse/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = std::env::args().collect();
Expand Down
24 changes: 24 additions & 0 deletions netvr-rust/analyse/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Input<'a>, 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<u32> {
map_res(decimal, |r| r.parse::<u32>())(input)
}

/// parse a float which uses a comma as decimal separator
fn float_comma(input: Input) -> Result<f64> {
map_res(
recognize(tuple((
Expand All @@ -36,6 +41,7 @@ fn float_comma(input: Input) -> Result<f64> {
)(input)
}

/// parse a float which uses a dot as decimal separator
fn float_dot(input: Input) -> Result<f64> {
map_res(
recognize(tuple((
Expand All @@ -51,6 +57,7 @@ fn float_dot(input: Input) -> Result<f64> {
)(input)
}

/// parse a 3d vector in the form of (0, 0, 0)
fn vec3(input: Input) -> Result<(f64, f64, f64)> {
map(
tuple((
Expand All @@ -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((
Expand All @@ -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),
Expand All @@ -107,13 +117,16 @@ 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,
pub characteristics: String,
pub sample: Sample,
}

/// parse characteristics string representation
fn characteristics(input: Input) -> Result<&str> {
recognize(many1(one_of(
"abcdefghijklmnopqrstuvwxyz,ABCDEFGHIJKLMNOPQRSTUVWXYZ",
Expand Down Expand Up @@ -147,6 +160,7 @@ impl From<LocalSample> 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,
Expand All @@ -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)
}
Expand Down Expand Up @@ -189,6 +205,8 @@ impl From<RemoteSample> 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,
Expand All @@ -215,26 +233,30 @@ impl Line {
}
}

/// the log file itself as parsed by the parser
#[derive(Debug, Serialize, Clone)]
pub struct LogFile {
pub lines: Vec<Line>,
}

impl LogFile {
/// parses the log file
pub fn parse(input: Input) -> Result<Self> {
map(
many0(map(tuple((Line::parse, multispace0)), |r| r.0)),
|lines| Self { lines },
)(input)
}

/// utility for getting all ids of all local devices that are recorded in the log
pub fn local_ids(&self) -> Vec<u32> {
self.lines
.iter()
.flat_map(|l| l.local.keys().copied())
.collect()
}

/// utility for getting all samples for a specific local device
pub fn local(&self, id: u32) -> Vec<Sample> {
self.lines
.iter()
Expand All @@ -243,13 +265,15 @@ impl LogFile {
.collect()
}

/// utility for getting all ids of all remote devices that are recorded in the log
pub fn remote_ids(&self) -> Vec<u32> {
self.lines
.iter()
.flat_map(|l| l.remote.keys().copied())
.collect()
}

/// utility for getting all samples for a specific remote device
pub fn remote(&self, id: u32) -> Vec<Sample> {
self.lines
.iter()
Expand Down
1 change: 1 addition & 0 deletions netvr-rust/analyse/src/plot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
1 change: 1 addition & 0 deletions netvr-rust/analyse/src/plot_positions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ fn expand_range(range: &std::ops::Range<f64>, 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();

Expand Down
1 change: 1 addition & 0 deletions netvr-rust/codegen/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn std::error::Error>> {
let out_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let dest_path = Path::new(&out_dir)
Expand Down
1 change: 1 addition & 0 deletions netvr-rust/codegen/src/main.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/// does not do anything
fn main() {}
5 changes: 5 additions & 0 deletions netvr-rust/netvr_calibrate/src/calibrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,8 @@ fn match_samples(input: &CalibrationInput) -> Vec<SamplePairF64> {
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<CalibrationResult> {
// Notes from original code:
// - it applies rotation right when it determines it
Expand Down Expand Up @@ -333,6 +335,7 @@ pub fn calibrate(samples: &CalibrationInput) -> Result<CalibrationResult> {
})
}

/// 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();
Expand All @@ -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();
Expand All @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions netvr-rust/netvr_calibrate/src/input.rs
Original file line number Diff line number Diff line change
@@ -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<CalibrationSample>,
Expand Down
2 changes: 2 additions & 0 deletions netvr-rust/netvr_calibrate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions netvr-rust/netvr_client/src/error.rs
Original file line number Diff line number Diff line change
@@ -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")]
Expand Down
1 change: 1 addition & 0 deletions netvr-rust/netvr_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub async fn connect(log: fn(String) -> ()) -> Result<NetVRConnection, Error> {
}
}

/// Sets up a connection to the server.
async fn setup_connection(
log: fn(String) -> (),
addr: SocketAddr,
Expand Down
1 change: 1 addition & 0 deletions netvr-rust/netvr_client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn std::error::Error>> {
println!("Hello there! I'm looking for NetVR devices...");
Expand Down
2 changes: 2 additions & 0 deletions netvr-rust/netvr_client/src/quinn_connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down
4 changes: 4 additions & 0 deletions netvr-rust/netvr_data/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Pose>,
}

/// 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),
Expand Down
3 changes: 3 additions & 0 deletions netvr-rust/netvr_data/src/framing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand All @@ -19,6 +20,7 @@ pub enum FramingError {
ConnectionError(#[from] quinn::ConnectionError),
}

/// Converts a stream to Frames. You can read from this.
pub struct RecvFrames<T: serde::de::DeserializeOwned> {
__marker: std::marker::PhantomData<T>,
inner: quinn::RecvStream,
Expand Down Expand Up @@ -58,6 +60,7 @@ impl<T: serde::de::DeserializeOwned> RecvFrames<T> {
}
}

/// Converts a stream to Frames. You can write into this.
pub struct SendFrames<T: serde::ser::Serialize> {
__marker: std::marker::PhantomData<T>,
inner: quinn::SendStream,
Expand Down
2 changes: 2 additions & 0 deletions netvr-rust/netvr_data/src/handle_serializer.rs
Original file line number Diff line number Diff line change
@@ -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"))]
Expand Down
Loading

0 comments on commit 1faa238

Please sign in to comment.