From 00118892fa308bfcb858fdc5c17cf255c08b2f66 Mon Sep 17 00:00:00 2001 From: Carson M Date: Thu, 10 Aug 2023 21:51:29 -0500 Subject: [PATCH] vmc 0.1.0 --- .editorconfig | 10 + .github/workflows/ci.yml | 48 ++ .gitignore | 2 + .vscode/settings.json | 3 + Cargo.toml | 28 + LICENSE-APACHE | 190 +++++++ LICENSE-MIT | 21 + README.md | 54 ++ examples/marionette.rs | 50 ++ examples/performer.rs | 37 ++ rustfmt.toml | 34 ++ src/error.rs | 60 ++ src/lib.rs | 252 +++++++++ src/message.rs | 1142 ++++++++++++++++++++++++++++++++++++++ src/osc/decoder.rs | 226 ++++++++ src/osc/encoder.rs | 314 +++++++++++ src/osc/error.rs | 73 +++ src/osc/mod.rs | 517 +++++++++++++++++ src/udp.rs | 92 +++ 19 files changed, 3153 insertions(+) create mode 100644 .editorconfig create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 .vscode/settings.json create mode 100644 Cargo.toml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 examples/marionette.rs create mode 100644 examples/performer.rs create mode 100644 rustfmt.toml create mode 100644 src/error.rs create mode 100644 src/lib.rs create mode 100644 src/message.rs create mode 100644 src/osc/decoder.rs create mode 100644 src/osc/encoder.rs create mode 100644 src/osc/error.rs create mode 100644 src/osc/mod.rs create mode 100644 src/udp.rs diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..9485359 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,10 @@ +root = true + +[*] +indent_style = tab +trim_trailing_whitespace = true +insert_final_newline = true + +[*.yml] +indent_style = space +indent_size = 2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2a09511 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,48 @@ +name: CI +on: + pull_request: + push: +jobs: + build_and_test: + name: Build and test + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + rust: [stable] + steps: + - uses: actions/checkout@master + - name: Install ${{ matrix.rust }} + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust }} + override: true + - name: check + uses: actions-rs/cargo@v1 + with: + command: check + args: --all --bins --examples + - name: check unstable + uses: actions-rs/cargo@v1 + with: + command: check + args: --all --benches --bins --examples --tests + - name: tests + uses: actions-rs/cargo@v1 + with: + command: test + args: --all + check_fmt_and_docs: + name: Checking fmt and docs + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@master + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + components: rustfmt, clippy + override: true + - name: fmt + run: cargo fmt --all -- --check + - name: Docs + run: cargo doc diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4fffb2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/Cargo.lock diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..e931c34 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "rust-analyzer.showUnlinkedFileNotification": false +} \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..09e0ce3 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "vmc" +version = "0.1.0" +license = "MIT OR Apache-2.0" +description = "Implementation of Virtual Motion Capture protocol for virtual avatar tracking." +repository = "https://github.com/vitri-ent/vmc" +documentation = "https://docs.rs/vmc" +readme = "README.md" +edition = "2021" +keywords = [ "vmc", "virtual motion capture" ] +categories = [ "network-programming", "asynchronous" ] +authors = [ + "Carson M. " +] +rust-version = "1.70" + +[dependencies] +nalgebra = "0.32" +nom = { version = "7", default-features = false, features = [ "alloc" ] } +tokio = { version = "1.30", features = [ "net" ] } +tokio-stream = "0.1" +thiserror = "1.0" +once_cell = "1.15" + +[dev-dependencies] +tokio = { version = "1.30", features = [ "net", "macros", "rt-multi-thread" ] } +tokio-test = "0.4" +approx = "0.5" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..b7c665c --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2020 Franz Heinzmann + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..faf7bef --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Franz Heinzmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9af7c4a --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +# `vmc` +An asynchronous implementation of the [Virtual Motion Capture Protocol](https://protocol.vmc.info/) in Rust. + +While this crate is intended specifically for Virtual Motion Capture, it can also be used as an implementation of the [Open Sound Control](https://opensoundcontrol.stanford.edu/) protocol which VMC is based on. + +## Examples +See [`examples/`](https://github.com/vitri-ent/vmc/tree/main/examples/) for more detailed examples. + +### Performer +```rs +use vmc::{ + VMCApplyBlendShapes, VMCBlendShape, VMCModelState, VMCResult, VMCStandardVRMBlendShape, VMCState, VMCTime +}; + +#[tokio::main] +async fn main() -> VMCResult<()> { + let socket = vmc::performer!("127.0.0.1:39539").await?; + loop { + socket + .send(VMCBlendShape::new(VMCStandardVRMBlendShape::Joy, 1.0)) + .await?; + socket.send(VMCApplyBlendShapes).await?; + socket.send(VMCState::new(VMCModelState::Loaded)).await?; + socket.send(VMCTime::elapsed()).await?; + } +} +``` + +### Marionette +```rs +use tokio_stream::StreamExt; +use vmc::{VMCMessage, VMCResult}; + +#[tokio::main] +async fn main() -> VMCResult<()> { + let mut socket = vmc::marionette!("127.0.0.1:39539").await?; + while let Some(packet) = socket.next().await { + let (packet, _) = packet?; + for message in vmc::parse(packet)? { + match message { + VMCMessage::BoneTransform(transform) => { + println!("\tTransform bone: {} (pos {:?}; rot {:?})", transform.bone.as_ref(), transform.position, transform.rotation) + } + _ => {} + } + } + } + + Ok(()) +} +``` + +## License +❤️ This package is based on [`rosc`](https://github.com/klingtnet/rosc/blob/master/Cargo.toml) by Andreas Linz and [`async-osc`](https://github.com/Frando/async-osc) by Franz Heinzmann. Licensed under MIT License or Apache-2.0. diff --git a/examples/marionette.rs b/examples/marionette.rs new file mode 100644 index 0000000..0080de4 --- /dev/null +++ b/examples/marionette.rs @@ -0,0 +1,50 @@ +use std::collections::HashMap; + +use tokio_stream::StreamExt; +use vmc::{VMCMessage, VMCModelState, VMCResult}; + +#[tokio::main] +async fn main() -> VMCResult<()> { + let mut socket = vmc::marionette!("127.0.0.1:39539").await?; + let mut blendshapes = HashMap::new(); + while let Some(packet) = socket.next().await { + let (packet, _) = packet?; + for message in vmc::parse(packet)? { + match message { + VMCMessage::BoneTransform(transform) => { + println!("\tTransform bone: {} (pos {:?}; rot {:?})", transform.bone.as_ref(), transform.position, transform.rotation) + } + VMCMessage::DeviceTransform(transform) => { + println!("\tTransform device ({:?}): {} (pos {:?}; rot {:?})", transform.device, transform.joint, transform.position, transform.rotation) + } + VMCMessage::RootTransform(transform) => { + println!("\tTransform root: (pos {:?}; rot {:?})", transform.position, transform.rotation) + } + VMCMessage::State(t) => match t.model_state { + VMCModelState::Loaded => println!("\tModel is loaded."), + VMCModelState::NotLoaded => println!("\tModel is not yet loaded.") + }, + VMCMessage::BlendShape(blend) => { + blendshapes.insert(blend.key, blend.value); + } + VMCMessage::ApplyBlendShapes => { + if !blendshapes.is_empty() { + println!( + "\tBlend shape: {}", + blendshapes + .iter() + .filter(|b| b.1 > &0.) + .map(|b| format!("{} x{:.02}", b.0, b.1)) + .collect::>() + .join(", ") + ); + blendshapes.clear(); + } + } + VMCMessage::Time(t) => println!("Render all (time: {})", t.0) + } + } + } + + Ok(()) +} diff --git a/examples/performer.rs b/examples/performer.rs new file mode 100644 index 0000000..92c8ac3 --- /dev/null +++ b/examples/performer.rs @@ -0,0 +1,37 @@ +use std::time::Instant; + +use vmc::{ + UnitQuaternion, VMCApplyBlendShapes, VMCBlendShape, VMCBone, VMCBoneTransform, VMCModelState, VMCResult, VMCStandardVRMBlendShape, VMCState, VMCTime, + Vector3 +}; + +#[tokio::main] +async fn main() -> VMCResult<()> { + let start = Instant::now(); + let socket = vmc::performer!("127.0.0.1:39539").await?; + loop { + socket + .send(VMCBlendShape::new(VMCStandardVRMBlendShape::A, start.elapsed().as_secs_f32().sin() / 2. + 0.5)) + .await?; + socket + .send(VMCBlendShape::new(VMCStandardVRMBlendShape::Fun, (start.elapsed().as_secs_f32().sin() / 2. + 0.5) * 0.6)) + .await?; + socket + .send(VMCBoneTransform::new( + VMCBone::LeftEye, + Vector3::new(-0.016136881, 0.061875343, 0.02154272), + UnitQuaternion::from_euler_angles((start.elapsed().as_secs_f32().cos()) * 0.05, (start.elapsed().as_secs_f32().sin()) * 0.05, 0.) + )) + .await?; + socket + .send(VMCBoneTransform::new( + VMCBone::RightEye, + Vector3::new(0.016136864, 0.061875224, 0.02154272), + UnitQuaternion::from_euler_angles((start.elapsed().as_secs_f32().cos()) * 0.05, (start.elapsed().as_secs_f32().sin()) * 0.05, 0.) + )) + .await?; + socket.send(VMCApplyBlendShapes).await?; + socket.send(VMCState::new(VMCModelState::Loaded)).await?; + socket.send(VMCTime::elapsed()).await?; + } +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..b0dae71 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,34 @@ +edition = "2021" +version = "Two" +unstable_features = true + +max_width = 160 +hard_tabs = true +tab_spaces = 4 +newline_style = "Unix" + +wrap_comments = true +format_code_in_doc_comments = true +comment_width = 120 +doc_comment_code_block_width = 120 +normalize_comments = true + +use_small_heuristics = "Off" +fn_call_width = 140 +attr_fn_like_width = 112 +struct_lit_width = 36 +struct_variant_width = 60 +array_width = 120 +chain_width = 90 +single_line_if_else_max_width = 96 + +reorder_imports = true +group_imports = "StdExternalCrate" +reorder_modules = true +trailing_comma = "Never" +match_block_trailing_comma = false +format_macro_bodies = true +use_try_shorthand = true +use_field_init_shorthand = true +merge_derives = true +force_explicit_abi = true diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..5ff2e6b --- /dev/null +++ b/src/error.rs @@ -0,0 +1,60 @@ +use std::{ + error::Error, + fmt, + io::{self} +}; + +use crate::{osc, OSCType}; + +/// Represents errors returned by `decode` or `encode`. +#[derive(Debug)] +pub enum VMCError { + Io(io::Error), + Osc(osc::OSCError), + UnimplementedMessage(String, Vec), + UnknownBone(String), + UnknownBlendShape(String), + UnknownModelState(i32), + UnknownCalibrationState(i32), + UnknownCalibrationMode(i32), + UnknownTrackingState(i32) +} + +impl fmt::Display for VMCError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + VMCError::Io(err) => write!(f, "socket error: {err}"), + VMCError::Osc(err) => write!(f, "protocol error: {err}"), + VMCError::UnimplementedMessage(addr, args) => write!(f, "handling '{addr}' not implemented (args: {args:?})"), + VMCError::UnknownBone(bone) => write!(f, "unknown bone: {bone}"), + VMCError::UnknownBlendShape(blend_shape) => write!(f, "unknown blend shape: {blend_shape}"), + VMCError::UnknownModelState(state) => write!(f, "unknown model state: {state}"), + VMCError::UnknownCalibrationState(state) => write!(f, "unknown calibration state: {state}"), + VMCError::UnknownCalibrationMode(mode) => write!(f, "unknown calibration mode: {mode}"), + VMCError::UnknownTrackingState(state) => write!(f, "unknown tracking state: {state}") + } + } +} + +impl From for VMCError { + fn from(value: io::Error) -> Self { + Self::Io(value) + } +} +impl From for VMCError { + fn from(value: osc::OSCError) -> Self { + Self::Osc(value) + } +} + +impl Error for VMCError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + VMCError::Io(ref err) => Some(err), + VMCError::Osc(ref err) => err.source(), + _ => None + } + } +} + +pub type VMCResult = Result; diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..161dcb4 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,252 @@ +#![allow(clippy::tabs_in_doc_comments)] + +use std::{ + io, + net::SocketAddr, + pin::Pin, + sync::Arc, + task::{Context, Poll} +}; + +use tokio::net::{ToSocketAddrs, UdpSocket}; +use tokio_stream::Stream; + +mod error; +pub mod message; +pub mod osc; +mod udp; + +pub use nalgebra::{ + geometry::{Quaternion, UnitQuaternion}, + Scale3, Vector3 +}; + +use self::udp::UDPSocketStream; +pub use self::{ + error::{VMCError, VMCResult}, + message::{ + parse, ApplyBlendShapes as VMCApplyBlendShapes, BlendShape as VMCBlendShape, Bone as VMCBone, BoneTransform as VMCBoneTransform, + CalibrationMode as VMCCalibrationMode, CalibrationState as VMCCalibrationState, DeviceTransform as VMCDeviceTransform, DeviceType as VMCDeviceType, + ModelState as VMCModelState, RootTransform as VMCRootTransform, StandardVRMBlendShape as VMCStandardVRMBlendShape, State as VMCState, Time as VMCTime, + TrackingState as VMCTrackingState, VMCMessage + }, + osc::{IntoOSCArgs, IntoOSCMessage, IntoOSCPacket, OSCPacket, OSCType} +}; + +/// A UDP socket to send and receive VMC messages. +#[derive(Debug)] +pub struct VMCSocket { + socket: UDPSocketStream +} + +impl VMCSocket { + /// Creates a new OSC socket from a [`tokio::net::UdpSocket`]. + pub fn new(socket: UdpSocket) -> Self { + let socket = UDPSocketStream::new(socket); + Self { socket } + } + + /// Creates an VMC socket from the given address. + /// + /// Binding with a port number of 0 will request that the OS assigns a port to this socket. + /// The port allocated can be queried via [`local_addr`] method. + /// + /// [`local_addr`]: #method.local_addr + pub async fn bind(addr: A) -> VMCResult { + let socket = UdpSocket::bind(addr).await?; + Ok(Self::new(socket)) + } + + /// Connects the UDP socket to a remote address. + /// + /// When connected, only messages from this address will be received and the [`send`] method + /// will use the specified address for sending. + /// + /// [`send`]: #method.send + /// + /// # Examples + /// + /// ```no_run + /// # fn main() -> vmc::VMCResult<()> { tokio_test::block_on(async { + /// use vmc::VMCSocket; + /// + /// let socket = VMCSocket::bind("127.0.0.1:0").await?; + /// socket.connect("127.0.0.1:8080").await?; + /// # Ok(()) }) } + /// ``` + pub async fn connect(&self, addrs: A) -> VMCResult<()> { + self.socket().connect(addrs).await?; + Ok(()) + } + + /// Sends an OSC packet on the socket to the given address. + /// + /// # Examples + /// + /// ```no_run + /// # fn main() -> vmc::VMCResult<()> { tokio_test::block_on(async { + /// use vmc::{VMCBlendShape, VMCSocket, VMCStandardVRMBlendShape}; + /// + /// let socket = VMCSocket::bind("127.0.0.1:0").await?; + /// let addr = "127.0.0.1:39539"; + /// let message = VMCBlendShape::new(VMCStandardVRMBlendShape::Joy, 1.0); + /// socket.send_to(message, &addr).await?; + /// # Ok(()) }) } + /// ``` + pub async fn send_to(&self, packet: P, addrs: A) -> VMCResult<()> { + let buf = self::osc::encode(&packet.into_osc_packet())?; + let n = self.socket().send_to(&buf[..], addrs).await?; + check_len(&buf[..], n) + } + + /// Sends a packet on the socket to the remote address to which it is connected. + /// + /// The [`connect`] method will connect this socket to a remote address. + /// This method will fail if the socket is not connected. + /// + /// [`connect`]: #method.connect + /// + /// # Examples + /// + /// ```no_run + /// # fn main() -> vmc::VMCResult<()> { tokio_test::block_on(async { + /// use vmc::{VMCBlendShape, VMCSocket, VMCStandardVRMBlendShape}; + /// + /// let socket = VMCSocket::bind("127.0.0.1:2434").await?; + /// socket.connect("127.0.0.1:39539").await?; + /// socket.send(VMCBlendShape::new(VMCStandardVRMBlendShape::Joy, 1.0)).await?; + /// # + /// # Ok(()) }) } + /// ``` + pub async fn send(&self, packet: P) -> VMCResult<()> { + let buf = self::osc::encode(&packet.into_osc_packet())?; + let n = self.socket().send(&buf[..]).await?; + check_len(&buf[..], n) + } + + /// Create a standalone sender for this socket. + /// + /// The sender can be moved to other threads or tasks. + pub fn sender(&self) -> VMCSender { + VMCSender::new(self.socket.clone_inner()) + } + + /// Get a reference to the underling [`UdpSocket`]. + pub fn socket(&self) -> &UdpSocket { + self.socket.get_ref() + } + + /// Returns the local address that this socket is bound to. + /// + /// This can be useful, for example, when binding to port 0 to figure out which port was + /// actually bound. + pub fn local_addr(&self) -> VMCResult { + let addr = self.socket().local_addr()?; + Ok(addr) + } +} + +impl Stream for VMCSocket { + type Item = VMCResult<(OSCPacket, SocketAddr)>; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let packet = match Pin::new(&mut self.socket).poll_next(cx) { + Poll::Ready(packet) => packet, + Poll::Pending => return Poll::Pending + }; + let message = packet.map(|packet| match packet { + Err(err) => Err(err.into()), + Ok((buf, peer_addr)) => self::osc::decode_udp(&buf[..]).map_err(|e| e.into()).map(|p| (p.1, peer_addr)) + }); + Poll::Ready(message) + } +} + +/// A sender to send messages over a VMC socket. +/// +/// See [`VMCSocket::sender`]. +#[derive(Clone, Debug)] +pub struct VMCSender { + socket: Arc +} + +impl VMCSender { + fn new(socket: Arc) -> Self { + Self { socket } + } + + /// Sends a VMC packet on the socket to the given address. + /// + /// See [`VMCSocket::send_to`]. + pub async fn send_to(&self, packet: P, addrs: A) -> VMCResult<()> { + let buf = self::osc::encode(&packet.into_osc_packet())?; + let n = self.socket().send_to(&buf[..], addrs).await?; + check_len(&buf[..], n) + } + + /// Sends a VMC packet on the connected socket. + /// + /// See [`VMCSocket::send`]. + pub async fn send(&self, packet: P) -> VMCResult<()> { + let buf = self::osc::encode(&packet.into_osc_packet())?; + let n = self.socket().send(&buf[..]).await?; + check_len(&buf[..], n) + } + + /// Get a reference to the underling [`UdpSocket`]. + pub fn socket(&self) -> &UdpSocket { + &self.socket + } +} + +#[macro_export] +macro_rules! performer { + () => { + $crate::_create_performer("127.0.0.1:0", "127.0.0.1:39539") + }; + (bind = $bind:expr) => { + $crate::_create_performer($bind, "127.0.0.1:39539") + }; + (bind_port = $bind_port:expr) => { + $crate::_create_performer(format!("127.0.0.1:{}", $bind_port), "127.0.0.1:39539") + }; + ($addr:expr) => { + $crate::_create_performer("127.0.0.1:0", $addr) + }; + ($addr:expr, bind = $bind:expr) => { + $crate::_create_performer($bind, $addr) + }; + ($addr:expr, bind_port = $bind_port:expr) => { + $crate::_create_performer(format!("127.0.0.1:{}", $bind_port), $addr) + }; +} + +#[doc(hidden)] +pub async fn _create_performer(bind: impl ToSocketAddrs, addr: impl ToSocketAddrs) -> VMCResult { + let socket = VMCSocket::bind(bind).await?; + socket.connect(addr).await?; + Ok(socket) +} + +#[macro_export] +macro_rules! marionette { + () => { + $crate::_create_marionette("127.0.0.1:39539") + }; + ($addr:expr) => { + $crate::_create_marionette($addr) + }; +} + +#[doc(hidden)] +pub async fn _create_marionette(addr: impl ToSocketAddrs) -> VMCResult { + let socket = VMCSocket::bind(addr).await?; + Ok(socket) +} + +fn check_len(buf: &[u8], len: usize) -> VMCResult<()> { + if len != buf.len() { + Err(io::Error::new(io::ErrorKind::Interrupted, "UDP packet not fully sent").into()) + } else { + Ok(()) + } +} diff --git a/src/message.rs b/src/message.rs new file mode 100644 index 0000000..c5450a6 --- /dev/null +++ b/src/message.rs @@ -0,0 +1,1142 @@ +use std::{str::FromStr, time::Instant}; + +use nalgebra::{Quaternion, Scale3, UnitQuaternion, Vector3}; +use once_cell::sync::Lazy; + +use crate::{osc::OSCMessage, IntoOSCMessage, OSCPacket, OSCType, VMCError, VMCResult}; + +#[derive(Debug, Clone, PartialEq)] +pub struct RootTransform { + pub position: Vector3, + pub rotation: UnitQuaternion, + pub scale: Option>, + pub offset: Option> +} + +impl RootTransform { + pub fn new(position: impl Into>, rotation: UnitQuaternion) -> Self { + Self { + position: position.into(), + rotation, + scale: None, + offset: None + } + } + + pub fn new_mr(position: impl Into>, rotation: UnitQuaternion, scale: Scale3, offset: Vector3) -> Self { + let rotation = rotation.slerp(&rotation, 1.0); + Self { + position: position.into(), + rotation, + scale: Some(scale), + offset: Some(offset) + } + } +} + +impl IntoOSCMessage for RootTransform { + fn into_osc_message(self) -> crate::osc::OSCMessage { + let rotation = self.rotation.as_ref(); + let mut args: Vec = vec![ + "root".into(), + self.position.x.into(), + self.position.y.into(), + self.position.z.into(), + rotation.coords.x.into(), + rotation.coords.y.into(), + rotation.coords.z.into(), + rotation.coords.w.into(), + ]; + if let (Some(scale), Some(offset)) = (self.scale.as_ref(), self.offset.as_ref()) { + args.extend([scale.x.into(), scale.y.into(), scale.z.into()]); + args.extend([offset.x.into(), offset.y.into(), offset.z.into()]); + } + OSCMessage::new("/VMC/Ext/Root/Pos", args) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bone { + Hips, + LeftUpperLeg, + RightUpperLeg, + LeftLowerLeg, + RightLowerLeg, + LeftFoot, + RightFoot, + Pelvis, + Spine, + Chest, + UpperChest, + Neck, + Head, + LeftShoulder, + RightShoulder, + LeftUpperArm, + RightUpperArm, + LeftLowerArm, + RightLowerArm, + LeftHand, + RightHand, + LeftToes, + RightToes, + LeftEye, + RightEye, + Jaw, + LeftThumbProximal, + LeftThumbIntermediate, + LeftThumbDistal, + LeftIndexProximal, + LeftIndexIntermediate, + LeftIndexDistal, + LeftMiddleProximal, + LeftMiddleIntermediate, + LeftMiddleDistal, + LeftRingProximal, + LeftRingIntermediate, + LeftRingDistal, + LeftLittleProximal, + LeftLittleIntermediate, + LeftLittleDistal, + RightThumbProximal, + RightThumbIntermediate, + RightThumbDistal, + RightIndexProximal, + RightIndexIntermediate, + RightIndexDistal, + RightMiddleProximal, + RightMiddleIntermediate, + RightMiddleDistal, + RightRingProximal, + RightRingIntermediate, + RightRingDistal, + RightLittleProximal, + RightLittleIntermediate, + RightLittleDistal +} + +impl AsRef for Bone { + fn as_ref(&self) -> &'static str { + match self { + Bone::Hips => "Hips", + Bone::LeftUpperLeg => "LeftUpperLeg", + Bone::RightUpperLeg => "RightUpperLeg", + Bone::LeftLowerLeg => "LeftLowerLeg", + Bone::RightLowerLeg => "RightLowerLeg", + Bone::LeftFoot => "LeftFoot", + Bone::RightFoot => "RightFoot", + Bone::Pelvis => "Pelvis", + Bone::Spine => "Spine", + Bone::Chest => "Chest", + Bone::UpperChest => "UpperChest", + Bone::Neck => "Neck", + Bone::Head => "Head", + Bone::LeftShoulder => "LeftShoulder", + Bone::RightShoulder => "RightShoulder", + Bone::LeftUpperArm => "LeftUpperArm", + Bone::RightUpperArm => "RightUpperArm", + Bone::LeftLowerArm => "LeftLowerArm", + Bone::RightLowerArm => "RightLowerArm", + Bone::LeftHand => "LeftHand", + Bone::RightHand => "RightHand", + Bone::LeftToes => "LeftToes", + Bone::RightToes => "RightToes", + Bone::LeftEye => "LeftEye", + Bone::RightEye => "RightEye", + Bone::Jaw => "Jaw", + Bone::LeftThumbProximal => "LeftThumbProximal", + Bone::LeftThumbIntermediate => "LeftThumbIntermediate", + Bone::LeftThumbDistal => "LeftThumbDistal", + Bone::LeftIndexProximal => "LeftIndexProximal", + Bone::LeftIndexIntermediate => "LeftIndexIntermediate", + Bone::LeftIndexDistal => "LeftIndexDistal", + Bone::LeftMiddleProximal => "LeftMiddleProximal", + Bone::LeftMiddleIntermediate => "LeftMiddleIntermediate", + Bone::LeftMiddleDistal => "LeftMiddleDistal", + Bone::LeftRingProximal => "LeftRingProximal", + Bone::LeftRingIntermediate => "LeftRingIntermediate", + Bone::LeftRingDistal => "LeftRingDistal", + Bone::LeftLittleProximal => "LeftLittleProximal", + Bone::LeftLittleIntermediate => "LeftLittleIntermediate", + Bone::LeftLittleDistal => "LeftLittleDistal", + Bone::RightThumbProximal => "RightThumbProximal", + Bone::RightThumbIntermediate => "RightThumbIntermediate", + Bone::RightThumbDistal => "RightThumbDistal", + Bone::RightIndexProximal => "RightIndexProximal", + Bone::RightIndexIntermediate => "RightIndexIntermediate", + Bone::RightIndexDistal => "RightIndexDistal", + Bone::RightMiddleProximal => "RightMiddleProximal", + Bone::RightMiddleIntermediate => "RightMiddleIntermediate", + Bone::RightMiddleDistal => "RightMiddleDistal", + Bone::RightRingProximal => "RightRingProximal", + Bone::RightRingIntermediate => "RightRingIntermediate", + Bone::RightRingDistal => "RightRingDistal", + Bone::RightLittleProximal => "RightLittleProximal", + Bone::RightLittleIntermediate => "RightLittleIntermediate", + Bone::RightLittleDistal => "RightLittleDistal" + } + } +} + +impl ToString for Bone { + fn to_string(&self) -> String { + self.as_ref().to_owned() + } +} + +impl FromStr for Bone { + type Err = (); + + fn from_str(s: &str) -> Result { + match s { + "Hips" => Ok(Bone::Hips), + "LeftUpperLeg" => Ok(Bone::LeftUpperLeg), + "RightUpperLeg" => Ok(Bone::RightUpperLeg), + "LeftLowerLeg" => Ok(Bone::LeftLowerLeg), + "RightLowerLeg" => Ok(Bone::RightLowerLeg), + "LeftFoot" => Ok(Bone::LeftFoot), + "RightFoot" => Ok(Bone::RightFoot), + "Pelvis" => Ok(Bone::Pelvis), + "Spine" => Ok(Bone::Spine), + "Chest" => Ok(Bone::Chest), + "UpperChest" => Ok(Bone::UpperChest), + "Neck" => Ok(Bone::Neck), + "Head" => Ok(Bone::Head), + "LeftShoulder" => Ok(Bone::LeftShoulder), + "RightShoulder" => Ok(Bone::RightShoulder), + "LeftUpperArm" => Ok(Bone::LeftUpperArm), + "RightUpperArm" => Ok(Bone::RightUpperArm), + "LeftLowerArm" => Ok(Bone::LeftLowerArm), + "RightLowerArm" => Ok(Bone::RightLowerArm), + "LeftHand" => Ok(Bone::LeftHand), + "RightHand" => Ok(Bone::RightHand), + "LeftToes" => Ok(Bone::LeftToes), + "RightToes" => Ok(Bone::RightToes), + "LeftEye" => Ok(Bone::LeftEye), + "RightEye" => Ok(Bone::RightEye), + "Jaw" => Ok(Bone::Jaw), + "LeftThumbProximal" => Ok(Bone::LeftThumbProximal), + "LeftThumbIntermediate" => Ok(Bone::LeftThumbIntermediate), + "LeftThumbDistal" => Ok(Bone::LeftThumbDistal), + "LeftIndexProximal" => Ok(Bone::LeftIndexProximal), + "LeftIndexIntermediate" => Ok(Bone::LeftIndexIntermediate), + "LeftIndexDistal" => Ok(Bone::LeftIndexDistal), + "LeftMiddleProximal" => Ok(Bone::LeftMiddleProximal), + "LeftMiddleIntermediate" => Ok(Bone::LeftMiddleIntermediate), + "LeftMiddleDistal" => Ok(Bone::LeftMiddleDistal), + "LeftRingProximal" => Ok(Bone::LeftRingProximal), + "LeftRingIntermediate" => Ok(Bone::LeftRingIntermediate), + "LeftRingDistal" => Ok(Bone::LeftRingDistal), + "LeftLittleProximal" => Ok(Bone::LeftLittleProximal), + "LeftLittleIntermediate" => Ok(Bone::LeftLittleIntermediate), + "LeftLittleDistal" => Ok(Bone::LeftLittleDistal), + "RightThumbProximal" => Ok(Bone::RightThumbProximal), + "RightThumbIntermediate" => Ok(Bone::RightThumbIntermediate), + "RightThumbDistal" => Ok(Bone::RightThumbDistal), + "RightIndexProximal" => Ok(Bone::RightIndexProximal), + "RightIndexIntermediate" => Ok(Bone::RightIndexIntermediate), + "RightIndexDistal" => Ok(Bone::RightIndexDistal), + "RightMiddleProximal" => Ok(Bone::RightMiddleProximal), + "RightMiddleIntermediate" => Ok(Bone::RightMiddleIntermediate), + "RightMiddleDistal" => Ok(Bone::RightMiddleDistal), + "RightRingProximal" => Ok(Bone::RightRingProximal), + "RightRingIntermediate" => Ok(Bone::RightRingIntermediate), + "RightRingDistal" => Ok(Bone::RightRingDistal), + "RightLittleProximal" => Ok(Bone::RightLittleProximal), + "RightLittleIntermediate" => Ok(Bone::RightLittleIntermediate), + "RightLittleDistal" => Ok(Bone::RightLittleDistal), + _ => Err(()) + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BoneTransform { + pub bone: Bone, + pub position: Vector3, + pub rotation: UnitQuaternion, + pub scale: Option>, + pub offset: Option> +} + +impl BoneTransform { + pub fn new(bone: Bone, position: impl Into>, rotation: UnitQuaternion) -> Self { + Self { + bone, + position: position.into(), + rotation, + scale: None, + offset: None + } + } + + pub fn new_mr(bone: Bone, position: impl Into>, rotation: UnitQuaternion, scale: Scale3, offset: Vector3) -> Self { + let rotation = rotation.slerp(&rotation, 1.0); + Self { + bone, + position: position.into(), + rotation, + scale: Some(scale), + offset: Some(offset) + } + } +} + +impl IntoOSCMessage for BoneTransform { + fn into_osc_message(self) -> crate::osc::OSCMessage { + let rotation = self.rotation.as_ref(); + let mut args: Vec = vec![ + self.bone.as_ref().into(), + self.position.x.into(), + self.position.y.into(), + self.position.z.into(), + rotation.coords.x.into(), + rotation.coords.y.into(), + rotation.coords.z.into(), + rotation.coords.w.into(), + ]; + if let (Some(scale), Some(offset)) = (self.scale.as_ref(), self.offset.as_ref()) { + args.extend([scale.x.into(), scale.y.into(), scale.z.into()]); + args.extend([offset.x.into(), offset.y.into(), offset.z.into()]); + } + OSCMessage::new("/VMC/Ext/Bone/Pos", args) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DeviceType { + HMD, + Controller, + Tracker +} + +impl AsRef for DeviceType { + fn as_ref(&self) -> &str { + match self { + DeviceType::HMD => "Hmd", + DeviceType::Controller => "Con", + DeviceType::Tracker => "Tra" + } + } +} + +impl ToString for DeviceType { + fn to_string(&self) -> String { + self.as_ref().to_owned() + } +} + +impl FromStr for DeviceType { + type Err = (); + + fn from_str(s: &str) -> Result { + match s { + "Hmd" => Ok(DeviceType::HMD), + "Con" => Ok(DeviceType::Controller), + "Tra" => Ok(DeviceType::Tracker), + _ => Err(()) + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DeviceTransform { + pub device: DeviceType, + pub joint: String, + pub position: Vector3, + pub rotation: UnitQuaternion, + pub local: bool +} + +impl DeviceTransform { + pub fn new(device: DeviceType, joint: impl ToString, position: impl Into>, rotation: UnitQuaternion, local: bool) -> Self { + Self { + device, + joint: joint.to_string(), + position: position.into(), + rotation, + local + } + } +} + +impl IntoOSCMessage for DeviceTransform { + fn into_osc_message(self) -> crate::osc::OSCMessage { + let rotation = self.rotation.as_ref(); + OSCMessage::new( + format!("/VMC/Ext/{}/Pos{}", self.device.as_ref(), if self.local { "/Local" } else { "" }), + (self.joint, self.position.x, self.position.y, self.position.z, rotation.coords.x, rotation.coords.y, rotation.coords.z, rotation.coords.w) + ) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum StandardVRMBlendShape { + Neutral, + A, + I, + U, + E, + O, + Blink, + Joy, + Angry, + Sorrow, + Fun, + LookUp, + LookDown, + LookLeft, + LookRight, + BlinkL, + BlinkR +} + +impl AsRef for StandardVRMBlendShape { + fn as_ref(&self) -> &str { + match self { + StandardVRMBlendShape::Neutral => "Neutral", + StandardVRMBlendShape::A => "A", + StandardVRMBlendShape::I => "I", + StandardVRMBlendShape::U => "U", + StandardVRMBlendShape::E => "E", + StandardVRMBlendShape::O => "O", + StandardVRMBlendShape::Blink => "Blink", + StandardVRMBlendShape::Joy => "Joy", + StandardVRMBlendShape::Angry => "Angry", + StandardVRMBlendShape::Sorrow => "Sorrow", + StandardVRMBlendShape::Fun => "Fun", + StandardVRMBlendShape::LookUp => "LookUp", + StandardVRMBlendShape::LookDown => "LookDown", + StandardVRMBlendShape::LookLeft => "LookLeft", + StandardVRMBlendShape::LookRight => "LookRight", + StandardVRMBlendShape::BlinkL => "Blink_L", + StandardVRMBlendShape::BlinkR => "Blink_R" + } + } +} + +impl ToString for StandardVRMBlendShape { + fn to_string(&self) -> String { + self.as_ref().to_owned() + } +} + +impl FromStr for StandardVRMBlendShape { + type Err = (); + + fn from_str(s: &str) -> Result { + match s { + "Neutral" => Ok(StandardVRMBlendShape::Neutral), + "A" => Ok(StandardVRMBlendShape::A), + "I" => Ok(StandardVRMBlendShape::I), + "U" => Ok(StandardVRMBlendShape::U), + "E" => Ok(StandardVRMBlendShape::E), + "O" => Ok(StandardVRMBlendShape::O), + "Blink" => Ok(StandardVRMBlendShape::Blink), + "Joy" => Ok(StandardVRMBlendShape::Joy), + "Angry" => Ok(StandardVRMBlendShape::Angry), + "Sorrow" => Ok(StandardVRMBlendShape::Sorrow), + "Fun" => Ok(StandardVRMBlendShape::Fun), + "LookUp" => Ok(StandardVRMBlendShape::LookUp), + "LookDown" => Ok(StandardVRMBlendShape::LookDown), + "LookLeft" => Ok(StandardVRMBlendShape::LookLeft), + "LookRight" => Ok(StandardVRMBlendShape::LookRight), + "Blink_L" => Ok(StandardVRMBlendShape::BlinkL), + "Blink_R" => Ok(StandardVRMBlendShape::BlinkR), + _ => Err(()) + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct BlendShape { + pub key: String, + pub value: f32 +} + +impl BlendShape { + pub fn new(key: impl ToString, value: f32) -> Self { + Self { key: key.to_string(), value } + } +} + +impl IntoOSCMessage for BlendShape { + fn into_osc_message(self) -> OSCMessage { + OSCMessage::new("/VMC/Ext/Blend/Val", (self.key, self.value)) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ApplyBlendShapes; + +impl IntoOSCMessage for ApplyBlendShapes { + fn into_osc_message(self) -> OSCMessage { + OSCMessage::new("/VMC/Ext/Blend/Apply", ()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum ModelState { + NotLoaded = 0, + Loaded = 1 +} + +impl From for OSCType { + fn from(value: ModelState) -> Self { + OSCType::Int(value as i32) + } +} + +impl TryFrom for ModelState { + type Error = i32; + + fn try_from(value: i32) -> Result { + match value { + 0 => Ok(ModelState::NotLoaded), + 1 => Ok(ModelState::Loaded), + x => Err(x) + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum CalibrationState { + Uncalibrated = 0, + WaitingForCalibration = 1, + Calibrating = 2, + Calibrated = 3 +} + +impl From for OSCType { + fn from(value: CalibrationState) -> Self { + OSCType::Int(value as i32) + } +} + +impl TryFrom for CalibrationState { + type Error = i32; + + fn try_from(value: i32) -> Result { + match value { + 0 => Ok(CalibrationState::Uncalibrated), + 1 => Ok(CalibrationState::WaitingForCalibration), + 2 => Ok(CalibrationState::Calibrating), + 3 => Ok(CalibrationState::Calibrated), + x => Err(x) + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum CalibrationMode { + Normal = 0, + MixedRealityHand = 1, + MixedRealityFloor = 2 +} + +impl From for OSCType { + fn from(value: CalibrationMode) -> Self { + OSCType::Int(value as i32) + } +} + +impl TryFrom for CalibrationMode { + type Error = i32; + + fn try_from(value: i32) -> Result { + match value { + 0 => Ok(CalibrationMode::Normal), + 1 => Ok(CalibrationMode::MixedRealityHand), + 2 => Ok(CalibrationMode::MixedRealityFloor), + x => Err(x) + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum TrackingState { + Poor = 0, + Good = 1 +} + +impl From for OSCType { + fn from(value: TrackingState) -> Self { + OSCType::Int(value as i32) + } +} + +impl TryFrom for TrackingState { + type Error = i32; + + fn try_from(value: i32) -> Result { + match value { + 0 => Ok(TrackingState::Poor), + 1 => Ok(TrackingState::Good), + x => Err(x) + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct State { + pub model_state: ModelState, + pub calibration_state: Option<(CalibrationMode, CalibrationState)>, + pub tracking_state: Option +} + +impl State { + pub fn new(model_state: ModelState) -> State { + Self { + model_state, + calibration_state: None, + tracking_state: None + } + } + + pub fn new_calibration(model_state: ModelState, calibration_mode: CalibrationMode, calibration_state: CalibrationState) -> State { + Self { + model_state, + calibration_state: Some((calibration_mode, calibration_state)), + tracking_state: None + } + } + + pub fn new_tracking( + model_state: ModelState, + calibration_mode: CalibrationMode, + calibration_state: CalibrationState, + tracking_state: TrackingState + ) -> State { + Self { + model_state, + calibration_state: Some((calibration_mode, calibration_state)), + tracking_state: Some(tracking_state) + } + } +} + +impl IntoOSCMessage for State { + fn into_osc_message(self) -> OSCMessage { + let mut args: Vec = vec![self.model_state.into()]; + if let Some((calibration_mode, calibration_state)) = self.calibration_state { + args.extend([calibration_state.into(), calibration_mode.into()]); + if let Some(tracking_state) = self.tracking_state { + args.push(tracking_state.into()); + } + } + OSCMessage::new("/VMC/Ext/OK", args) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Time(pub f32); + +impl Time { + pub fn new(timestamp: f32) -> Self { + Self(timestamp) + } + + pub fn elapsed() -> Self { + static EPOCH: Lazy = Lazy::new(Instant::now); + Self(EPOCH.elapsed().as_secs_f32()) + } +} + +impl IntoOSCMessage for Time { + fn into_osc_message(self) -> OSCMessage { + OSCMessage::new("/VMC/Ext/T", (self.0,)) + } +} + +#[derive(Debug, Clone)] +pub enum VMCMessage { + RootTransform(RootTransform), + DeviceTransform(DeviceTransform), + BoneTransform(BoneTransform), + BlendShape(BlendShape), + ApplyBlendShapes, + State(State), + Time(Time) +} + +impl IntoOSCMessage for VMCMessage { + fn into_osc_message(self) -> OSCMessage { + match self { + Self::RootTransform(p) => p.into_osc_message(), + Self::DeviceTransform(p) => p.into_osc_message(), + Self::BoneTransform(p) => p.into_osc_message(), + Self::BlendShape(p) => p.into_osc_message(), + Self::ApplyBlendShapes => ApplyBlendShapes.into_osc_message(), + Self::State(p) => p.into_osc_message(), + Self::Time(p) => p.into_osc_message() + } + } +} + +impl From for VMCMessage { + fn from(value: RootTransform) -> Self { + Self::RootTransform(value) + } +} +impl From for VMCMessage { + fn from(value: DeviceTransform) -> Self { + Self::DeviceTransform(value) + } +} +impl From for VMCMessage { + fn from(value: BoneTransform) -> Self { + Self::BoneTransform(value) + } +} +impl From for VMCMessage { + fn from(value: BlendShape) -> Self { + Self::BlendShape(value) + } +} +impl From for VMCMessage { + fn from(_value: ApplyBlendShapes) -> Self { + Self::ApplyBlendShapes + } +} +impl From for VMCMessage { + fn from(value: State) -> Self { + Self::State(value) + } +} +impl From