Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,14 @@ path = "examples/pbr.rs"
name = "midi"
path = "examples/midi.rs"

[[example]]
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"
Expand Down
175 changes: 175 additions & 0 deletions examples/audio_cube.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
Loading
Loading