From 01db8af82324ad0ab8dabb1a0db77ce167f3b424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?moon=20dav=C3=A9?= Date: Tue, 1 Dec 2026 00:05:36 -0500 Subject: [PATCH 1/2] examples: audio_cube A spinning cube that plays a filtered sample on space and wobbles to it, with mouse X setting the cutoff. --- Cargo.toml | 4 + examples/audio_cube.rs | 175 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+) create mode 100644 examples/audio_cube.rs diff --git a/Cargo.toml b/Cargo.toml index 3daf23f7..93a867ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -175,6 +175,10 @@ path = "examples/pbr.rs" name = "midi" path = "examples/midi.rs" +[[example]] +name = "audio_cube" +path = "examples/audio_cube.rs" + [[example]] name = "gltf_load" path = "examples/gltf_load.rs" diff --git a/examples/audio_cube.rs b/examples/audio_cube.rs new file mode 100644 index 00000000..9fde2708 --- /dev/null +++ b/examples/audio_cube.rs @@ -0,0 +1,175 @@ +// A spinning cube that plays a sample and wobbles to it. +// +// Space plays the sample through a lowpass filter. Every trigger kicks a +// damped spring: the cube squashes and stretches, spins faster for a moment, +// flashes warmer, then settles. Quick taps pile up. +// +// Mouse X sets the filter cutoff (100 Hz at the left edge, 18 kHz at the +// right) and the cube's color with it: dim violet when the filter is closed, +// bright aqua when it is open. The filter starts open. +// +// cargo run --example audio_cube + +use bevy::color::Color; +use bevy::math::Vec3; +use processing::prelude::*; +use processing_glfw::GlfwContext; +use processing_render::render::command::DrawCommand; + +const WIDTH: u32 = 500; +const HEIGHT: u32 = 500; + +fn main() { + if let Err(e) = sketch() { + eprintln!("Sketch error: {e:?}"); + exit(1).unwrap(); + } + exit(0).unwrap(); +} + +/// A damped spring around 0. `kick` adds velocity; `step` integrates one frame. +#[derive(Default)] +struct Spring { + pos: f32, + vel: f32, +} + +impl Spring { + fn kick(&mut self, amount: f32) { + self.vel += amount; + } + + fn step(&mut self, stiffness: f32, damping: f32) -> f32 { + self.vel += -stiffness * self.pos - damping * self.vel; + self.pos += self.vel; + self.pos + } +} + +fn sketch() -> error::Result<()> { + let mut config = Config::default(); + // Default output only; no input is opened unless asked for. + config.set(ConfigKey::AudioEnabled, "true".into()); + + let mut glfw_ctx = GlfwContext::new(WIDTH, HEIGHT, false)?; + init(config)?; + let surface = glfw_ctx.create_surface(WIDTH, HEIGHT, false)?; + let graphics = graphics_create(surface, WIDTH, HEIGHT, TextureFormat::Rgba16Float)?; + + let pluck = audio_sample_load("audio/pluck.wav")?; + let sampler = audio_sampler_create(2, 8)?; + let filter = audio_node_create(AudioNodeKind::Svf, 2)?; + audio_node_set_variant(filter, "filter_type", "Lowpass")?; + audio_node_set(filter, "q_factor", 4.0)?; + audio_connect(sampler, filter, &[(0, 0), (1, 1)])?; + audio_connect(filter, audio_output()?, &[(0, 0), (1, 1)])?; + + let cube = geometry_box(120.0, 120.0, 120.0)?; + let material = material_create_pbr()?; + material_set( + material, + "roughness", + shader_value::ShaderValue::Float(0.35), + )?; + let key = light_create_directional(graphics, Color::srgb(1.0, 0.95, 0.9), 900.0)?; + transform_set_position(key, Vec3::new(150.0, -200.0, 250.0))?; + transform_look_at(key, Vec3::ZERO)?; + let fill = light_create_directional(graphics, Color::srgb(0.4, 0.5, 1.0), 300.0)?; + transform_set_position(fill, Vec3::new(-200.0, 100.0, 100.0))?; + transform_look_at(fill, Vec3::ZERO)?; + + // The default 3D camera: the z = 0 plane lines up with the window's + // pixels (origin at the center, +y down), so the label can be drawn + // there in window coordinates. + graphics_mode_3d(graphics)?; + + // `squash` is bouncy and drives the scale; `twist` is slower and drives + // the extra spin and the tilt. + let mut squash = Spring::default(); + let mut twist = Spring::default(); + // Decays from 1 after each trigger: extra spin speed and the color flash. + let mut energy: f32 = 0.0; + let mut angle: f32 = 0.0; + let mut mouse_moved = false; + + let draw = |command| graphics_record_command(graphics, command); + + while glfw_ctx.poll_events() { + // 0 at the left edge, 1 at the right; open until the mouse moves. + mouse_moved |= input_mouse_moved()?; + let open = if mouse_moved { + (input_mouse_x(surface)? / WIDTH as f32).clamp(0.0, 1.0) + } else { + 1.0 + }; + let cutoff = 100.0 * (18_000.0f32 / 100.0).powf(open); + audio_node_set(filter, "cutoff_hz", cutoff)?; + + if input_key_just_pressed(KeyCode::Space)? { + audio_sample_play(sampler, pluck, 0.8)?; + squash.kick(0.12); + twist.kick(0.05); + energy = (energy + 1.0).min(2.0); + } + + let s = squash.step(0.18, 0.12); + let t = twist.step(0.06, 0.08); + energy *= 0.94; + angle += 0.012 + 0.05 * energy; + + // Stretch on one axis, squash the other two, so the volume looks + // preserved. + let scale = Vec3::new(1.0 - 0.5 * s, 1.0 + s, 1.0 - 0.5 * s); + let warm = (energy * 0.5).min(1.0); + // The filter picks the base color; a trigger flashes it warmer. + let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t; + let base = [ + lerp(0.22, 0.45, open), + lerp(0.10, 0.90, open), + lerp(0.45, 1.00, open), + ]; + let flash = [1.0, 0.6, 0.3]; + let color = Color::srgb( + lerp(base[0], flash[0], warm), + lerp(base[1], flash[1], warm), + lerp(base[2], flash[2], warm), + ); + + graphics_begin_draw(graphics)?; + graphics_light(graphics, key)?; + graphics_light(graphics, fill)?; + draw(DrawCommand::BackgroundColor(Color::srgb(0.06, 0.06, 0.09)))?; + draw(DrawCommand::PushStyle)?; + draw(DrawCommand::Fill(color))?; + draw(DrawCommand::Material(material))?; + + draw(DrawCommand::PushMatrix)?; + draw(DrawCommand::Rotate { + angle, + axis: Vec3::Y, + })?; + draw(DrawCommand::Rotate { + angle: 0.4 + 2.0 * t, + axis: Vec3::new(1.0, 0.0, 1.0).normalize(), + })?; + draw(DrawCommand::Scale(scale))?; + draw(DrawCommand::Geometry(cube))?; + draw(DrawCommand::PopMatrix)?; + draw(DrawCommand::PopStyle)?; + + draw(DrawCommand::Unlit)?; + draw(DrawCommand::Fill(Color::srgb(0.9, 0.9, 0.95)))?; + draw(DrawCommand::TextSize(16.0))?; + draw(DrawCommand::Text { + content: format!("space: play mouse x: filter ({cutoff:.0} Hz)"), + x: 16.0 - WIDTH as f32 / 2.0, + y: HEIGHT as f32 / 2.0 - 20.0, + z: 0.0, + max_w: None, + max_h: None, + stroke_weight: None, + })?; + graphics_end_draw(graphics)?; + } + Ok(()) +} From f245ecf258fdfd94d26697dbde859106207cabe8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?moon=20dav=C3=A9?= Date: Tue, 1 Dec 2026 00:05:38 -0500 Subject: [PATCH 2/2] examples: audio_modular Routing sized to the output device, with patch-bay level meters. AUDIO_DEVICE / AUDIO_INPUT pick the interface; B restarts the stream at a new block size; unplugging the interface stops the stream until it returns. --- Cargo.toml | 4 + examples/audio_modular.rs | 327 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 331 insertions(+) create mode 100644 examples/audio_modular.rs diff --git a/Cargo.toml b/Cargo.toml index 93a867ff..bc63d2ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -179,6 +179,10 @@ path = "examples/midi.rs" name = "audio_cube" path = "examples/audio_cube.rs" +[[example]] +name = "audio_modular" +path = "examples/audio_modular.rs" + [[example]] name = "gltf_load" path = "examples/gltf_load.rs" diff --git a/examples/audio_modular.rs b/examples/audio_modular.rs new file mode 100644 index 00000000..4e0e4627 --- /dev/null +++ b/examples/audio_modular.rs @@ -0,0 +1,327 @@ +// Audio routing, sized to the output device. +// +// On an interface with 8 or more outputs (e.g. a modular synth's 8x8 card): +// +// in 1 -> SVF lowpass -> out 1 (mouse X sets the cutoff) +// in 2 -> reverb -> outs 3+4 +// in 5 -> out 5 untouched (CV passthrough: no gain, no filtering) +// space -> sample -> outs 7+8 +// +// On a stereo device (e.g. laptop speakers), inputs are not used, to avoid +// feedback through the speakers: +// +// space -> sample -> SVF lowpass -> outs 1+2 (mouse X sets the cutoff) +// +// Pick the interface with AUDIO_DEVICE (part of its name), e.g. +// AUDIO_DEVICE="ES-9" cargo run --example audio_modular +// It is used for both input and output. Without it, the default output is +// used with no input. AUDIO_INPUT overrides the input ("none", "default", +// or part of a name). +// +// Routing goes through the patch bay's jacks, so the window can show a level +// meter for every input and output channel. +// +// Keys: space plays the sample. [ and ] move it to the previous/next output +// pair (1+2 ... 15+16), to find which channels reach your speakers or +// headphones. B toggles block size 256/128 (restarts the stream, keeps the +// patch). +// Unplug the interface while running: the stream stops (nothing plays on +// other outputs), and resumes on the same patch when it is plugged back in. + +use bevy::color::Color; +use bevy::prelude::Entity; +use processing::prelude::*; +use processing_glfw::GlfwContext; +use processing_render::render::command::DrawCommand; + +const WIDTH: u32 = 640; +const HEIGHT: u32 = 470; + +fn main() { + if let Err(e) = sketch() { + eprintln!("Sketch error: {e:?}"); + exit(1).unwrap(); + } + exit(0).unwrap(); +} + +/// Port numbers are zero-based; jacks are usually labelled from 1. +fn jack(n: u32) -> u32 { + n - 1 +} + +fn sketch() -> error::Result<()> { + let mut config = Config::default(); + config.set(ConfigKey::AudioEnabled, "true".into()); + // Without AUDIO_DEVICE: default output, and no input (no microphone). + if let Ok(device) = std::env::var("AUDIO_DEVICE") { + config.set(ConfigKey::AudioOutputDevice, device.clone()); + config.set(ConfigKey::AudioInputDevice, device); + } + if let Ok(input) = std::env::var("AUDIO_INPUT") { + config.set(ConfigKey::AudioInputDevice, input); + } + config.set(ConfigKey::AudioBlockFrames, "256".into()); + // Room for every channel of a 16-channel interface like the ES-9, even if + // it is plugged in after the sketch starts. + config.set(ConfigKey::AudioGraphChannels, "16".into()); + + let mut glfw_ctx = GlfwContext::new(WIDTH, HEIGHT, false)?; + init(config)?; + let surface = glfw_ctx.create_surface(WIDTH, HEIGHT, false)?; + let graphics = graphics_create(surface, WIDTH, HEIGHT, TextureFormat::Rgba16Float)?; + + println!("outputs: {:#?}", audio_list_output_devices()?); + println!("inputs: {:#?}", audio_list_input_devices()?); + println!("{:#?}", audio_info()?); + + let pluck = audio_sample_load("audio/pluck.wav")?; + // Built once the output device is running, so the layout fits it. + let mut patch: Option = None; + let mut block_frames = 256; + let mut mouse_moved = false; + let mut log: Vec = Vec::new(); + + let draw = |command| graphics_record_command(graphics, command); + let text = |content: String, x: f32, y: f32| { + draw(DrawCommand::Text { + content, + x, + y, + z: 0.0, + max_w: None, + max_h: None, + stroke_weight: None, + }) + }; + + while glfw_ctx.poll_events() { + for event in audio_events()? { + println!("audio: {event:?}"); + log.push(format!("{event:?}")); + } + if log.len() > 6 { + log.drain(..log.len() - 6); + } + + let info = audio_info()?; + if patch.is_none() && info.status == AudioStatus::Running { + let p = build_patch(&info)?; + println!("patched: {}", p.layout); + patch = Some(p); + } + + // The filter starts fully open; moving the mouse over the window takes + // over: 100 Hz at the left edge to 18 kHz at the right. + mouse_moved |= input_mouse_moved()?; + let mx = if mouse_moved { + input_mouse_x(surface)?.clamp(0.0, WIDTH as f32) + } else { + WIDTH as f32 + }; + let cutoff = 100.0 * (18_000.0f32 / 100.0).powf(mx / WIDTH as f32); + if let Some(p) = &mut patch { + audio_node_set(p.filter, "cutoff_hz", cutoff)?; + if input_key_just_pressed(KeyCode::Space)? { + audio_sample_play(p.sampler, pluck, 0.8)?; + } + if input_key_just_pressed(KeyCode::BracketRight)? { + p.move_sample(2)?; + } + if input_key_just_pressed(KeyCode::BracketLeft)? { + p.move_sample(-2)?; + } + } + if input_key_just_pressed(KeyCode::KeyB)? { + block_frames = if block_frames == 256 { 128 } else { 256 }; + audio_set_block_frames(block_frames)?; + } + + let mut lines = vec![ + format!( + "{:?} out: {} in: {}", + info.status, + info.output_device.as_deref().unwrap_or("-"), + info.input_device.as_deref().unwrap_or("-"), + ), + format!( + "{} Hz, {} frames, device {} in / {} out, graph {} / {}", + info.sample_rate, + info.block_frames, + info.device_inputs, + info.device_outputs, + info.graph_inputs, + info.graph_outputs, + ), + match &patch { + Some(p) => p.layout.to_string(), + None => "waiting for the output device...".to_string(), + }, + match &patch { + Some(p) => format!( + "space: sample > out {}+{} [ ]: move it B: block size cutoff {cutoff:.0} Hz", + p.sample_out, + p.sample_out + 1 + ), + None => String::new(), + }, + ]; + lines.extend(log.iter().cloned()); + + graphics_begin_draw(graphics)?; + draw(DrawCommand::BackgroundColor(Color::srgb(0.08, 0.08, 0.1)))?; + draw(DrawCommand::NoStroke)?; + draw(DrawCommand::Fill(Color::srgb(0.2, 0.5, 0.9)))?; + draw(DrawCommand::Rect { + x: 0.0, + y: HEIGHT as f32 - 6.0, + w: mx, + h: 6.0, + radii: [0.0; 4], + })?; + draw(DrawCommand::Fill(Color::WHITE))?; + draw(DrawCommand::TextSize(14.0))?; + for (i, line) in lines.iter().enumerate() { + text(line.clone(), 12.0, 24.0 + i as f32 * 20.0)?; + } + + // one bar per device channel; height is the peak level (sqrt so quiet + // signals show) + let levels = audio_jack_levels()?; + let rows = [ + ( + "in", + &levels.inputs[..(info.device_inputs as usize).min(levels.inputs.len())], + ), + ( + "out", + &levels.outputs[..(info.device_outputs as usize).min(levels.outputs.len())], + ), + ]; + for (row, (label, levels)) in rows.into_iter().enumerate() { + let base = 300.0 + row as f32 * 110.0; + draw(DrawCommand::Fill(Color::WHITE))?; + text(label.to_string(), 12.0, base - 30.0)?; + for (i, level) in levels.iter().enumerate() { + let level = level.min(1.0).sqrt(); + let x = 60.0 + i as f32 * 36.0; + draw(DrawCommand::Fill(Color::srgb(0.2, 0.2, 0.25)))?; + draw(DrawCommand::Rect { + x, + y: base - 80.0, + w: 28.0, + h: 80.0, + radii: [0.0; 4], + })?; + draw(DrawCommand::Fill(Color::srgb(0.3, 0.9, 0.4)))?; + draw(DrawCommand::Rect { + x, + y: base - 80.0 * level, + w: 28.0, + h: 80.0 * level, + radii: [0.0; 4], + })?; + draw(DrawCommand::Fill(Color::WHITE))?; + text(format!("{}", i + 1), x + 6.0, base + 16.0)?; + } + } + graphics_end_draw(graphics)?; + } + Ok(()) +} + +/// This example's routing, built on the patch bay's jacks (`audio_jack_input` +/// / `audio_jack_output`), so every channel shows on the meters. +struct Patch { + layout: &'static str, + filter: Entity, + sampler: Entity, + /// What feeds the sample's output pair: the sampler, or the filter after it. + sample_src: Entity, + /// First jack of the sample's output pair (1-based). + sample_out: u32, + /// Output channels on the device when the patch was built. + outputs: u32, +} + +fn input(n: u32) -> error::Result { + audio_jack_input(jack(n)) +} + +fn output(n: u32) -> error::Result { + audio_jack_output(jack(n)) +} + +fn build_patch(info: &AudioInfo) -> error::Result { + let outputs = info.device_outputs.min(info.graph_outputs); + let sampler = audio_sampler_create(2, 8)?; + if outputs >= 8 { + let filter = audio_node_create(AudioNodeKind::Svf, 1)?; + setup_filter(filter)?; + audio_connect_channel(input(1)?, 0, filter, 0)?; + audio_connect_channel(filter, 0, output(1)?, 0)?; + + let reverb = audio_node_create(AudioNodeKind::Freeverb, 2)?; + audio_node_set(reverb, "room_size", 0.85)?; + audio_connect(input(2)?, reverb, &[(0, 0), (0, 1)])?; + audio_connect_channel(reverb, 0, output(3)?, 0)?; + audio_connect_channel(reverb, 1, output(4)?, 0)?; + + audio_connect_channel(input(5)?, 0, output(5)?, 0)?; + + audio_connect_channel(sampler, 0, output(7)?, 0)?; + audio_connect_channel(sampler, 1, output(8)?, 0)?; + Ok(Patch { + layout: "multichannel: in1>filter>out1, in2>reverb>out3+4, in5>out5 (CV)", + filter, + sampler, + sample_src: sampler, + sample_out: 7, + outputs, + }) + } else { + let filter = audio_node_create(AudioNodeKind::Svf, 2)?; + setup_filter(filter)?; + audio_connect(sampler, filter, &[(0, 0), (1, 1)])?; + audio_connect_channel(filter, 0, output(1)?, 0)?; + // a mono device gets both sides on its one output + audio_connect_channel(filter, 1, output(2.min(outputs.max(1)))?, 0)?; + Ok(Patch { + layout: "stereo: sample > filter > out1+2", + filter, + sampler, + sample_src: filter, + sample_out: 1, + outputs, + }) + } +} + +impl Patch { + /// Move the sample to another output pair, `by` jacks along (wrapping), + /// e.g. to find which channels reach your headphones. + fn move_sample(&mut self, by: i32) -> error::Result<()> { + let pairs = (self.outputs as i32 / 2).max(1); + let pair = ((self.sample_out as i32 - 1) / 2 + by / 2).rem_euclid(pairs); + let to = pair as u32 * 2 + 1; + let [old_l, old_r] = self.pair(self.sample_out)?; + audio_disconnect(self.sample_src, old_l, &[(0, 0)])?; + audio_disconnect(self.sample_src, old_r, &[(1, 0)])?; + let [l, r] = self.pair(to)?; + audio_connect_channel(self.sample_src, 0, l, 0)?; + audio_connect_channel(self.sample_src, 1, r, 0)?; + self.sample_out = to; + Ok(()) + } + + /// Output jacks `first` and `first + 1` (the same one on a mono device). + fn pair(&self, first: u32) -> error::Result<[Entity; 2]> { + let last = self.outputs.max(1); + Ok([output(first.min(last))?, output((first + 1).min(last))?]) + } +} + +fn setup_filter(filter: Entity) -> error::Result<()> { + audio_node_set_variant(filter, "filter_type", "Lowpass")?; + audio_node_set(filter, "q_factor", 2.0) +}