diff --git a/Cargo.lock b/Cargo.lock index 53b5f09e..4efbabba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2873,6 +2873,12 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "derive_more" version = "2.1.1" @@ -5344,6 +5350,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-derive" version = "0.4.2" @@ -6144,6 +6156,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "pp-rs" version = "0.2.1" @@ -6233,6 +6251,7 @@ dependencies = [ "processing_glfw", "processing_input", "processing_midi", + "processing_osc", "processing_render", "processing_webcam", "rand 0.10.2", @@ -6324,6 +6343,15 @@ dependencies = [ "processing_glfw", ] +[[package]] +name = "processing_osc" +version = "0.4.0" +dependencies = [ + "bevy", + "processing_core", + "rosc", +] + [[package]] name = "processing_pyo3" version = "0.4.0" @@ -6875,6 +6903,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "rosc" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd37602e1513794e952274082d074e8d31aa7f64d047e3acb746c91db40600a5" +dependencies = [ + "byteorder", + "nom 7.1.3", + "time", +] + [[package]] name = "roxmltree" version = "0.21.1" @@ -7650,6 +7689,36 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-skia" version = "0.11.4" diff --git a/Cargo.toml b/Cargo.toml index 5ef3f465..cc7618cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,6 +71,7 @@ processing_cuda = { path = "crates/processing_cuda" } processing_pyo3 = { path = "crates/processing_pyo3" } processing_render = { path = "crates/processing_render" } processing_midi = { path = "crates/processing_midi" } +processing_osc = { path = "crates/processing_osc" } processing_audio = { path = "crates/processing_audio" } processing_input = { path = "crates/processing_input" } processing_glfw = { path = "crates/processing_glfw" } @@ -83,6 +84,7 @@ bevy = { workspace = true } processing_core = { workspace = true } processing_render = { workspace = true } processing_midi = { workspace = true } +processing_osc = { workspace = true } processing_audio = { workspace = true } processing_input = { workspace = true } processing_webcam = { workspace = true, optional = true } @@ -165,6 +167,10 @@ path = "examples/pbr.rs" name = "midi" path = "examples/midi.rs" +[[example]] +name = "osc" +path = "examples/osc.rs" + [[example]] name = "gltf_load" path = "examples/gltf_load.rs" diff --git a/crates/processing_core/src/error.rs b/crates/processing_core/src/error.rs index 95567476..7dbb585b 100644 --- a/crates/processing_core/src/error.rs +++ b/crates/processing_core/src/error.rs @@ -56,6 +56,14 @@ pub enum ProcessingError { MidiInputNotConnected, #[error("MIDI connection failed: {0}")] MidiConnectionFailed(String), + #[error("Could not listen for OSC on port {0}: {1}")] + OscListenFailed(u16, String), + #[error("Not listening for OSC; call osc_listen() first")] + OscNotListening, + #[error("OSC receive failed: {0}")] + OscReceiveFailed(String), + #[error("OSC send failed: {0}")] + OscSendFailed(String), #[error("CUDA error: {0}")] CudaError(String), #[error("Compute shader not found")] diff --git a/crates/processing_osc/Cargo.toml b/crates/processing_osc/Cargo.toml new file mode 100644 index 00000000..cf21aba0 --- /dev/null +++ b/crates/processing_osc/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "processing_osc" +version = "0.4.0" +edition = "2024" +rust-version.workspace = true + +[dependencies] +bevy = { workspace = true } +processing_core = { workspace = true } +rosc = "0.11" + +[lints] +workspace = true diff --git a/crates/processing_osc/src/lib.rs b/crates/processing_osc/src/lib.rs new file mode 100644 index 00000000..3c396d81 --- /dev/null +++ b/crates/processing_osc/src/lib.rs @@ -0,0 +1,322 @@ +//! OSC (Open Sound Control) over UDP +//! +//! `std::net::UdpSocket` sends and receives raw bytes; +//! rosc translates between a message and its raw bytes. +//! The sockets are stored in one Bevy resource [`OscState`]. +//! Each `osc_*` function briefly accesses that resource while the sketch runs. + +use std::io::ErrorKind; +use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket}; + +use bevy::prelude::*; +use rosc::{OscPacket, decoder, encoder}; + +use processing_core::app_mut; +use processing_core::error::{ProcessingError, Result}; + +pub use rosc::{OscArray, OscMessage, OscType}; + +pub struct OscPlugin; + +impl Plugin for OscPlugin { + fn build(&self, app: &mut App) { + app.init_resource::(); + } +} + +/// A message received on the listening port, with the sender's address. +#[derive(Clone, Debug, PartialEq)] +pub struct ReceivedOscMessage { + pub message: OscMessage, + pub from: SocketAddr, +} + +#[derive(Resource, Default)] +struct OscState { + receiver: Option, + /// Created on first send + sender: Option, +} + +/// Add the messages in `packet` to `out`, flattening nested bundles. +fn unfold(packet: OscPacket, from: SocketAddr, out: &mut Vec) { + match packet { + OscPacket::Message(message) => out.push(ReceivedOscMessage { message, from }), + OscPacket::Bundle(bundle) => { + for packet in bundle.content { + unfold(packet, from, out); + } + } + } +} + +impl OscState { + /// Bind the receive socket on all interfaces, replacing any previous one. + /// Port 0 picks a free port. Returns the port actually bound. + fn listen(&mut self, port: u16) -> Result { + self.receiver = None; + let failed = |e: std::io::Error| ProcessingError::OscListenFailed(port, e.to_string()); + let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, port)).map_err(failed)?; + // Reads happen once per frame and must never stall the sketch. + socket.set_nonblocking(true).map_err(failed)?; + let bound = socket.local_addr().map_err(failed)?.port(); + self.receiver = Some(socket); + Ok(bound) + } + + fn stop(&mut self) { + self.receiver = None; + } + + /// Drain every pending packet, unfolding bundles into their messages. + fn read(&mut self) -> Result> { + let socket = self + .receiver + .as_ref() + .ok_or(ProcessingError::OscNotListening)?; + let mut buf = [0u8; decoder::MTU]; + let mut received = Vec::new(); + loop { + let (len, from) = match socket.recv_from(&mut buf) { + Ok(r) => r, + Err(e) if e.kind() == ErrorKind::WouldBlock => break, + Err(e) => return Err(ProcessingError::OscReceiveFailed(e.to_string())), + }; + match decoder::decode_udp(&buf[..len]) { + Ok((_, packet)) => unfold(packet, from, &mut received), + // One bad packet shouldn't hide the ones queued behind it. + Err(e) => warn!("Ignoring malformed OSC packet from {from}: {e:?}"), + } + } + Ok(received) + } + + /// Return receiver address + fn send(&mut self, host: &str, port: u16, message: OscMessage) -> Result { + let failed = |e: String| ProcessingError::OscSendFailed(e); + let bytes = + encoder::encode(&OscPacket::Message(message)).map_err(|e| failed(format!("{e:?}")))?; + if self.sender.is_none() { + let socket = + UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).map_err(|e| failed(e.to_string()))?; + self.sender = Some(socket); + } + let to = resolve_ipv4(host, port).map_err(failed)?; + let socket = self.sender.as_ref().expect("sender was just created"); + socket + .send_to(&bytes, to) + .map_err(|e| failed(e.to_string()))?; + Ok(to) + } +} + +/// Look up `host` and pick its IPv4 address +fn resolve_ipv4(host: &str, port: u16) -> std::result::Result { + (host, port) + .to_socket_addrs() + .map_err(|e| format!("could not find host {host:?}: {e}"))? + .find(SocketAddr::is_ipv4) + .ok_or_else(|| format!("host {host:?} has no IPv4 address; IPv6 isn't supported yet")) +} + +/// A message as short readable text +pub fn osc_message_text(message: &OscMessage) -> String { + let mut out = message.addr.clone(); + for arg in &message.args { + out.push(' '); + arg_text(arg, &mut out); + } + out +} + +fn arg_text(value: &OscType, out: &mut String) { + use std::fmt::Write; + let _ = match value { + OscType::Int(i) => write!(out, "{i}"), + OscType::Long(i) => write!(out, "{i}"), + OscType::Float(f) => write!(out, "{f}"), + OscType::Double(d) => write!(out, "{d}"), + OscType::String(s) => write!(out, "{s:?}"), + OscType::Char(c) => write!(out, "{c:?}"), + OscType::Blob(b) => write!(out, "<{} bytes>", b.len()), + OscType::Bool(b) => write!(out, "{b}"), + OscType::Nil => write!(out, "nil"), + OscType::Inf => write!(out, "inf"), + OscType::Time(t) => write!(out, "time({}, {})", t.seconds, t.fractional), + OscType::Color(c) => write!(out, "rgba({}, {}, {}, {})", c.red, c.green, c.blue, c.alpha), + OscType::Midi(m) => write!( + out, + "midi({}, {}, {}, {})", + m.port, m.status, m.data1, m.data2 + ), + OscType::Array(a) => { + out.push('['); + for (i, v) in a.content.iter().enumerate() { + if i > 0 { + out.push(' '); + } + arg_text(v, out); + } + out.push(']'); + Ok(()) + } + }; +} + +fn with_state(f: impl FnOnce(&mut OscState) -> Result) -> Result { + app_mut(|app| f(&mut app.world_mut().resource_mut::())) +} + +/// Start listening for OSC messages on `port` (all network interfaces). +/// Calling it again switches to the new port. Returns the bound port, which +/// is useful when passing 0 to let the system choose. +#[cfg(not(target_arch = "wasm32"))] +pub fn osc_listen(port: u16) -> Result { + with_state(|state| state.listen(port)) +} + +/// Stop listening and close the receive socket. +#[cfg(not(target_arch = "wasm32"))] +pub fn osc_stop() -> Result<()> { + with_state(|state| { + state.stop(); + Ok(()) + }) +} + +/// Every message received since the last call, oldest first. +/// Messages inside bundles are returned individually. +#[cfg(not(target_arch = "wasm32"))] +pub fn osc_read() -> Result> { + with_state(|state| state.read()) +} + +/// Send one message, e.g. `osc_send("127.0.0.1", 9000, "/xy", vec![OscType::Float(0.5)])`. +/// Returns the receiver address, with `host` looked up (e.g. `127.0.0.1:9000`). +#[cfg(not(target_arch = "wasm32"))] +pub fn osc_send(host: &str, port: u16, address: &str, args: Vec) -> Result { + let message = OscMessage { + addr: address.to_string(), + args, + }; + with_state(|state| state.send(host, port, message)) +} + +#[cfg(test)] +mod tests { + use super::*; + use rosc::{OscBundle, OscTime}; + use std::time::{Duration, Instant}; + + /// Loopback delivery is fast but not instant, so poll briefly. + fn read_until(state: &mut OscState, count: usize) -> Vec { + let deadline = Instant::now() + Duration::from_secs(2); + let mut got = Vec::new(); + while got.len() < count && Instant::now() < deadline { + got.extend(state.read().unwrap()); + std::thread::sleep(Duration::from_millis(5)); + } + got + } + + fn msg(addr: &str, args: Vec) -> OscMessage { + OscMessage { + addr: addr.into(), + args, + } + } + + #[test] + fn formats_messages_as_text() { + let args = vec![ + OscType::Int(1), + OscType::Float(0.52), + OscType::String("hi".into()), + OscType::Bool(true), + OscType::Nil, + OscType::Blob(vec![1, 2]), + OscType::Array(OscArray { + content: vec![OscType::Int(1), OscType::Double(2.5)], + }), + ]; + assert_eq!( + osc_message_text(&msg("/mix", args)), + r#"/mix 1 0.52 "hi" true nil <2 bytes> [1 2.5]"# + ); + assert_eq!(osc_message_text(&msg("/empty", vec![])), "/empty"); + } + + #[test] + fn localhost_resolves_to_ipv4() { + let addr = resolve_ipv4("localhost", 9000).unwrap(); + assert_eq!(addr, "127.0.0.1:9000".parse().unwrap()); + assert!(resolve_ipv4("::1", 9000).is_err()); + } + + #[test] + fn sends_and_receives_over_loopback() { + let mut state = OscState::default(); + let port = state.listen(0).unwrap(); + + let args = vec![ + OscType::Int(1), + OscType::Float(0.5), + OscType::String("hi".into()), + ]; + state + .send("127.0.0.1", port, msg("/test", args.clone())) + .unwrap(); + + let got = read_until(&mut state, 1); + assert_eq!(got.len(), 1); + assert_eq!(got[0].message.addr, "/test"); + assert_eq!(got[0].message.args, args); + assert!(got[0].from.ip().is_loopback()); + } + + #[test] + fn read_with_nothing_pending_returns_immediately() { + let mut state = OscState::default(); + state.listen(0).unwrap(); + assert!(state.read().unwrap().is_empty()); + } + + #[test] + fn bundles_are_flattened() { + let from: SocketAddr = "127.0.0.1:9000".parse().unwrap(); + let bundle = OscPacket::Bundle(OscBundle { + timetag: OscTime::from((0, 1)), + content: vec![ + OscPacket::Message(msg("/a", vec![])), + OscPacket::Bundle(OscBundle { + timetag: OscTime::from((0, 1)), + content: vec![OscPacket::Message(msg("/b", vec![]))], + }), + ], + }); + let mut out = Vec::new(); + unfold(bundle, from, &mut out); + let addrs: Vec<_> = out.iter().map(|r| r.message.addr.as_str()).collect(); + assert_eq!(addrs, ["/a", "/b"]); + } + + #[test] + fn read_without_listening_is_an_error() { + let mut state = OscState::default(); + assert!(matches!( + state.read(), + Err(ProcessingError::OscNotListening) + )); + } + + #[test] + fn stop_closes_the_receiver() { + let mut state = OscState::default(); + state.listen(0).unwrap(); + state.stop(); + assert!(matches!( + state.read(), + Err(ProcessingError::OscNotListening) + )); + } +} diff --git a/crates/processing_pyo3/examples/osc.py b/crates/processing_pyo3/examples/osc.py new file mode 100644 index 00000000..226629cc --- /dev/null +++ b/crates/processing_pyo3/examples/osc.py @@ -0,0 +1,62 @@ +from processing_py import * + +# OSC out and in example +# OSC OUT: moving the mouse sends /mouse x y (0-1). Pressing and releasing the mouse sends /click 1 and 0. +# OSC IN: latest message is shown at the bottom. +# +# To try it with another program: +# - receive on port 12000 +# - send to localhost (127.0.0.1) on port 10000 + +LISTEN_PORT = 10000 +SEND_HOST = "127.0.0.1" # this computer +SEND_PORT = 12000 + +latest_in = f"nothing received on port {LISTEN_PORT}" +latest_out = "nothing sent" +was_pressed = False + + +def setup(): + size(640, 480) + no_stroke() + port = osc_listen(LISTEN_PORT) + print(f"listening on port {port}, sending to {SEND_HOST}:{SEND_PORT}") + + +def draw(): + global latest_in, latest_out, was_pressed + + # OSC IN + for msg in osc_read(): + latest_in = f"{msg} from {msg.host}:{msg.port}" + + # OSC OUT + if mouse_x != pmouse_x or mouse_y != pmouse_y: + sent = osc_send(SEND_HOST, SEND_PORT, "/mouse", mouse_x / width, mouse_y / height) + latest_out = f"{sent} to {sent.host}:{sent.port}" + if mouse_is_pressed != was_pressed: + sent = osc_send(SEND_HOST, SEND_PORT, "/click", 1 if mouse_is_pressed else 0) + latest_out = f"{sent} to {sent.host}:{sent.port}" + was_pressed = mouse_is_pressed + + background(0) + + # OSC OUT visualizer + stroke(0.5) + if mouse_is_pressed: + fill(1.0,1.0,0.0) + else: + no_fill() + circle(mouse_x, mouse_y, 16) + no_stroke() + + # OSC IN/OUT DISPLAY + fill(1.0) + text_size(14) + text(f"OSC OUT: {SEND_HOST}:{SEND_PORT}", 12, 22) + text(f"OSC IN: port {LISTEN_PORT}", 12, 42) + text("OSC OUT: " + latest_out, 12, height - 22) + text("OSC IN: " + latest_in, 12, height - 42) + +run() \ No newline at end of file diff --git a/crates/processing_pyo3/src/lib.rs b/crates/processing_pyo3/src/lib.rs index 4fad8883..d438be07 100644 --- a/crates/processing_pyo3/src/lib.rs +++ b/crates/processing_pyo3/src/lib.rs @@ -23,6 +23,7 @@ pub(crate) mod material; pub(crate) mod math; mod midi; mod monitor; +mod osc; pub(crate) mod particles; pub(crate) mod shader; mod surface; @@ -568,6 +569,8 @@ pub mod processing_py { #[pymodule_export] use super::monitor::Monitor; #[pymodule_export] + use super::osc::PyOscMessage; + #[pymodule_export] use super::particles::Attribute; #[pymodule_export] use super::particles::AttributeFormat; @@ -2932,6 +2935,36 @@ pub mod processing_py { midi::read() } + /// Listen for OSC messages on `port` and return the port. Pass 0 to let + /// the system pick a free one. Calling it again switches ports. + #[pyfunction] + fn osc_listen(port: u16) -> PyResult { + osc::listen(port) + } + /// Stop listening for OSC messages. + #[pyfunction] + fn osc_stop() -> PyResult<()> { + osc::stop() + } + /// Send an OSC message, e.g. `osc_send("127.0.0.1", 9000, "/xy", 0.5, 0.25)`. + /// Arguments can be int, float, str, bool, bytes, None or lists of those. + /// Returns the sent `OscMessage`, with `host`/`port` set to where it went. + #[pyfunction] + #[pyo3(signature = (host, port, address, *args))] + fn osc_send( + host: &str, + port: u16, + address: &str, + args: &Bound<'_, pyo3::types::PyTuple>, + ) -> PyResult { + osc::send(host, port, address, args) + } + /// Every OSC message received since the last call, oldest first. + #[pyfunction] + fn osc_read() -> PyResult> { + osc::read() + } + #[pyfunction] fn key_is_down(key_code: u32) -> PyResult { input::key_is_down(key_code) diff --git a/crates/processing_pyo3/src/osc.rs b/crates/processing_pyo3/src/osc.rs new file mode 100644 index 00000000..d4025301 --- /dev/null +++ b/crates/processing_pyo3/src/osc.rs @@ -0,0 +1,199 @@ +use processing::prelude::*; +use pyo3::{ + exceptions::{PyRuntimeError, PyTypeError}, + prelude::*, + types::{PyBool, PyBytes, PyFloat, PyInt, PyList, PyString, PyTuple}, +}; +use std::net::SocketAddr; + +fn runtime_err(e: impl std::fmt::Display) -> PyErr { + PyRuntimeError::new_err(format!("{e}")) +} + +pub fn listen(port: u16) -> PyResult { + osc_listen(port).map_err(runtime_err) +} +pub fn stop() -> PyResult<()> { + osc_stop().map_err(runtime_err) +} +pub fn send( + host: &str, + port: u16, + address: &str, + args: &Bound<'_, PyTuple>, +) -> PyResult { + let args = args + .iter() + .map(|a| to_osc(&a)) + .collect::>>()?; + let peer = osc_send(host, port, address, args.clone()).map_err(runtime_err)?; + Ok(PyOscMessage { + message: OscMessage { + addr: address.to_string(), + args, + }, + peer, + }) +} +pub fn read() -> PyResult> { + osc_read() + .map(|msgs| msgs.into_iter().map(PyOscMessage::from).collect()) + .map_err(runtime_err) +} + +/// Python value -> OSC argument. `bool` is checked before `int` because +/// Python's `True`/`False` are ints too. +fn to_osc(value: &Bound<'_, PyAny>) -> PyResult { + Ok(if value.is_none() { + OscType::Nil + } else if value.is_instance_of::() { + OscType::Bool(value.extract()?) + } else if value.is_instance_of::() { + let i: i64 = value.extract()?; + i32::try_from(i).map_or(OscType::Long(i), OscType::Int) + } else if value.is_instance_of::() { + // 32-bit floats ("f") are what most OSC software expects. + OscType::Float(value.extract::()? as f32) + } else if let Ok(s) = value.cast::() { + OscType::String(s.to_str()?.to_owned()) + } else if let Ok(b) = value.cast::() { + OscType::Blob(b.as_bytes().to_vec()) + } else if value.is_instance_of::() || value.is_instance_of::() { + let content = value + .try_iter()? + .map(|item| to_osc(&item?)) + .collect::>>()?; + OscType::Array(OscArray { content }) + } else { + return Err(PyTypeError::new_err(format!( + "can't send {} over OSC; use int, float, str, bool, bytes, None or a list of those", + value.get_type().name()? + ))); + }) +} + +/// OSC argument -> Python value. +fn to_py<'py>(py: Python<'py>, value: &OscType) -> PyResult> { + Ok(match value { + OscType::Int(i) => i.into_pyobject(py)?.into_any(), + OscType::Long(i) => i.into_pyobject(py)?.into_any(), + OscType::Float(f) => f.into_pyobject(py)?.into_any(), + OscType::Double(d) => d.into_pyobject(py)?.into_any(), + OscType::String(s) => s.into_pyobject(py)?.into_any(), + OscType::Char(c) => c.into_pyobject(py)?.into_any(), + OscType::Blob(b) => PyBytes::new(py, b).into_any(), + OscType::Bool(b) => b.into_pyobject(py)?.to_owned().into_any(), + OscType::Nil | OscType::Inf => py.None().into_bound(py), + OscType::Time(t) => (t.seconds, t.fractional).into_pyobject(py)?.into_any(), + OscType::Color(c) => (c.red, c.green, c.blue, c.alpha) + .into_pyobject(py)? + .into_any(), + OscType::Midi(m) => (m.port, m.status, m.data1, m.data2) + .into_pyobject(py)? + .into_any(), + OscType::Array(a) => { + let items = a + .content + .iter() + .map(|v| to_py(py, v)) + .collect::>>()?; + PyList::new(py, items)?.into_any() + } + }) +} + +/// The OSC type tag character for an argument, e.g. `i` for int. +fn type_tag(value: &OscType, out: &mut String) { + match value { + OscType::Int(_) => out.push('i'), + OscType::Long(_) => out.push('h'), + OscType::Float(_) => out.push('f'), + OscType::Double(_) => out.push('d'), + OscType::String(_) => out.push('s'), + OscType::Char(_) => out.push('c'), + OscType::Blob(_) => out.push('b'), + OscType::Bool(true) => out.push('T'), + OscType::Bool(false) => out.push('F'), + OscType::Nil => out.push('N'), + OscType::Inf => out.push('I'), + OscType::Time(_) => out.push('t'), + OscType::Color(_) => out.push('r'), + OscType::Midi(_) => out.push('m'), + OscType::Array(a) => { + out.push('['); + a.content.iter().for_each(|v| type_tag(v, out)); + out.push(']'); + } + } +} + +/// An OSC message: one returned by `osc_read()`, or the one `osc_send()` just sent. +/// +/// `address` is the message's address pattern, like `"/mouse"`. `args` are +/// its arguments as Python values, and `typetag` spells out their OSC types, +/// one letter each (`"ffs"` is two floats and a string). `host` and `port` +/// are the other side: who sent it for received messages, where it went for +/// sent ones. `str(msg)` gives a short readable form like `/mouse 0.5 0.25`. +#[pyclass(name = "OscMessage", frozen)] +pub struct PyOscMessage { + message: OscMessage, + peer: SocketAddr, +} + +impl From for PyOscMessage { + fn from(r: ReceivedOscMessage) -> Self { + Self { + message: r.message, + peer: r.from, + } + } +} + +#[pymethods] +impl PyOscMessage { + #[getter] + fn address(&self) -> &str { + &self.message.addr + } + + #[getter] + fn args<'py>(&self, py: Python<'py>) -> PyResult> { + let items = self + .message + .args + .iter() + .map(|v| to_py(py, v)) + .collect::>>()?; + PyList::new(py, items) + } + + #[getter] + fn typetag(&self) -> String { + let mut tag = String::new(); + self.message.args.iter().for_each(|v| type_tag(v, &mut tag)); + tag + } + + #[getter] + fn host(&self) -> String { + self.peer.ip().to_string() + } + + #[getter] + fn port(&self) -> u16 { + self.peer.port() + } + + fn __str__(&self) -> String { + osc_message_text(&self.message) + } + + fn __repr__(&self, py: Python<'_>) -> PyResult { + Ok(format!( + "OscMessage(address={:?}, args={}, peer={})", + self.message.addr, + self.args(py)?.repr()?, + self.peer + )) + } +} diff --git a/examples/osc.rs b/examples/osc.rs new file mode 100644 index 00000000..2bae1e1e --- /dev/null +++ b/examples/osc.rs @@ -0,0 +1,129 @@ +// OSC out and in example +// OSC OUT: moving the mouse sends /mouse x y (0-1). Pressing and releasing the mouse sends /click 1 and 0. +// OSC IN: latest message is shown at the bottom. +// +// To try it with another program: +// - receive on port 12000 +// - send to localhost (127.0.0.1) on port 10000 + +use bevy::color::Color; +use processing::prelude::*; +use processing_glfw::GlfwContext; +use processing_render::render::command::DrawCommand; + +const WIDTH: u32 = 640; +const HEIGHT: u32 = 480; + +const LISTEN_PORT: u16 = 10000; +const SEND_HOST: &str = "127.0.0.1"; // this computer +const SEND_PORT: u16 = 12000; + +fn main() { + if let Err(e) = sketch() { + eprintln!("Sketch error: {e:?}"); + exit(1).unwrap(); + } + exit(0).unwrap(); +} + +fn sketch() -> error::Result<()> { + let mut glfw_ctx = GlfwContext::new(WIDTH, HEIGHT, false)?; + init(Config::default())?; + let surface = glfw_ctx.create_surface(WIDTH, HEIGHT, false)?; + let graphics = graphics_create(surface, WIDTH, HEIGHT, TextureFormat::Rgba16Float)?; + + let port = osc_listen(LISTEN_PORT)?; + println!("listening on port {port}, sending to {SEND_HOST}:{SEND_PORT}"); + let out_label = format!("OSC OUT: {SEND_HOST}:{SEND_PORT}"); + let in_label = format!("OSC IN: port {LISTEN_PORT}"); + + let mut latest_in = format!("nothing received on port {LISTEN_PORT}"); + let mut latest_out = "nothing sent".to_string(); + let mut was_pressed = false; + + let draw = |command| graphics_record_command(graphics, command); + let text = |content: &str, y| { + draw(DrawCommand::Text { + content: content.to_string(), + x: 12.0, + y, + z: 0.0, + max_w: None, + max_h: None, + }) + }; + + while glfw_ctx.poll_events() { + let mx = input_mouse_x(surface)?; + let my = input_mouse_y(surface)?; + let pressed = input_mouse_is_pressed()?; + + // OSC IN + for received in osc_read()? { + latest_in = format!( + "{} from {}", + osc_message_text(&received.message), + received.from + ); + } + + // OSC OUT + if mx != input_pmouse_x(surface)? || my != input_pmouse_y(surface)? { + let args = vec![ + OscType::Float(mx / WIDTH as f32), + OscType::Float(my / HEIGHT as f32), + ]; + let to = osc_send(SEND_HOST, SEND_PORT, "/mouse", args.clone())?; + latest_out = format!( + "{} to {to}", + osc_message_text(&OscMessage { + addr: "/mouse".into(), + args + }) + ); + } + if pressed != was_pressed { + let args = vec![OscType::Int(pressed as i32)]; + let to = osc_send(SEND_HOST, SEND_PORT, "/click", args.clone())?; + latest_out = format!( + "{} to {to}", + osc_message_text(&OscMessage { + addr: "/click".into(), + args + }) + ); + was_pressed = pressed; + } + + graphics_begin_draw(graphics)?; + draw(DrawCommand::BackgroundColor(Color::BLACK))?; + + // OSC OUT visualizer + draw(DrawCommand::StrokeColor(Color::srgb(0.5, 0.5, 0.5)))?; + if pressed { + draw(DrawCommand::Fill(Color::srgb(1.0, 1.0, 0.0)))?; + } else { + draw(DrawCommand::NoFill)?; + } + draw(DrawCommand::Ellipse { + cx: mx, + cy: my, + w: 16.0, + h: 16.0, + })?; + draw(DrawCommand::NoStroke)?; + + // OSC IN/OUT DISPLAY + draw(DrawCommand::Fill(Color::WHITE))?; + draw(DrawCommand::TextSize(14.0))?; + text(&out_label, 22.0)?; + text(&in_label, 42.0)?; + text(&format!("OSC OUT: {latest_out}"), HEIGHT as f32 - 22.0)?; + text(&format!("OSC IN: {latest_in}"), HEIGHT as f32 - 42.0)?; + + graphics_end_draw(graphics)?; + } + + osc_stop()?; + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs index 717a24ca..17f22e42 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,6 +51,7 @@ fn create_app(config: Config) -> App { app.add_plugins(plugins); app.add_plugins(processing_midi::MidiPlugin); + app.add_plugins(processing_osc::OscPlugin); app.add_plugins(processing_input::InputPlugin); app.add_plugins(processing_render::ProcessingRenderPlugin); diff --git a/src/prelude.rs b/src/prelude.rs index 3275728d..4a371040 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -10,6 +10,11 @@ pub use processing_midi::{ midi_disconnect, midi_disconnect_input, midi_list_input_ports, midi_list_ports, midi_message_kind, midi_note_off, midi_note_on, midi_play_notes, midi_read, midi_refresh_ports, }; +#[cfg(not(target_arch = "wasm32"))] +pub use processing_osc::{ + OscArray, OscMessage, OscType, ReceivedOscMessage, osc_listen, osc_message_text, osc_read, + osc_send, osc_stop, +}; pub use processing_render::{ render::command::{ ArcMode, BlendMode, DrawCommand, LightKind, ShapeKind, ShapeMode, StrokeCapMode,