use crate::math;
use crate::param::ParamId;
use crate::program::{LfoShape, Program, PwmSource, VcfPoleMode};
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Scale {
Normalised,
Turns(f32),
Octaves(f32),
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Mark {
at: f32,
kind: MarkKind,
}
impl Mark {
#[must_use]
pub const fn at(&self) -> f32 {
self.at
}
#[must_use]
pub const fn kind(&self) -> MarkKind {
self.kind
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum MarkKind {
Segment(Segment),
Corner,
Cycle,
Tap,
Width,
Sweep,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Segment {
Attack,
Decay,
Sustain,
Release,
}
impl Segment {
pub const ALL: [Self; 4] = [Self::Attack, Self::Decay, Self::Sustain, Self::Release];
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Generator {
shape: Shape,
scale: Scale,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Shape {
Envelope(Envelope),
Fade {
end: f32,
},
Lfo(Lfo),
Taps {
taps: [(f32, f32); MAX_TAPS],
used: usize,
},
Filter(Filter),
Oscillator(Oscillator),
Noise {
level: f32,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Envelope {
ends: [f32; 3],
sustain: f32,
sustain_end: f32,
bends: [f32; 4],
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Lfo {
shape: LfoShape,
turns: f32,
slew: f32,
unipolar: bool,
synced: bool,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Filter {
slope: f32,
resonance: f32,
span: f32,
pass: Pass,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Pass {
Low,
High,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Oscillator {
saw: bool,
pulse: bool,
width: f32,
sweep: f32,
level: f32,
}
const MAX_MARKS: usize = 6;
impl Generator {
#[must_use]
pub fn at(&self, t: f32) -> f32 {
let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
let value = match self.shape {
Shape::Envelope(envelope) => envelope.at(t),
Shape::Fade { end } => {
if t < end {
t / end
} else {
1.0
}
}
Shape::Lfo(lfo) => lfo.at(t * lfo.turns),
Shape::Taps { taps, used } => taps_at(&taps, used, t),
Shape::Filter(filter) => filter.at(t),
Shape::Oscillator(oscillator) => oscillator.at(t),
Shape::Noise { level } => 0.5 + (noise_at(t) - 0.5) * level,
};
value.clamp(0.0, 1.0)
}
#[must_use]
pub const fn scale(&self) -> Scale {
self.scale
}
#[must_use]
pub const fn rest(&self) -> f32 {
match self.shape {
Shape::Envelope(_) | Shape::Fade { .. } | Shape::Taps { .. } => 0.0,
Shape::Lfo(lfo) => {
if lfo.unipolar {
0.0
} else {
0.5
}
}
Shape::Filter(_) => FILTER_UNITY,
Shape::Oscillator(_) | Shape::Noise { .. } => 0.5,
}
}
#[must_use]
pub const fn anchored(&self) -> bool {
match self.shape {
Shape::Envelope(_) | Shape::Fade { .. } | Shape::Taps { .. } | Shape::Filter(_) => true,
Shape::Lfo(lfo) => lfo.synced,
Shape::Oscillator(_) | Shape::Noise { .. } => false,
}
}
pub fn marks(&self) -> impl Iterator<Item = Mark> {
let mut marks = [None; MAX_MARKS];
let mut count = 0;
let mut push = |at: f32, kind: MarkKind| {
if let Some(slot) = marks.get_mut(count) {
*slot = Some(Mark { at, kind });
count += 1;
}
};
match self.shape {
Shape::Envelope(envelope) => {
let [first, second, third] = envelope.ends;
for (at, segment) in [0.0, first, second, third].into_iter().zip(Segment::ALL) {
push(at, MarkKind::Segment(segment));
}
}
Shape::Fade { end } => {
push(0.0, MarkKind::Segment(Segment::Attack));
push(end, MarkKind::Segment(Segment::Sustain));
}
Shape::Lfo(lfo) => cycles(lfo.turns, &mut push),
Shape::Taps { taps, used } => {
for &(at, _) in taps.iter().take(used) {
push(at, MarkKind::Tap);
}
}
Shape::Filter(_) => push(0.5, MarkKind::Corner),
Shape::Oscillator(oscillator) => {
if oscillator.pulse {
push(oscillator.width, MarkKind::Width);
if oscillator.sweep > 0.0 {
push(oscillator.width - oscillator.sweep, MarkKind::Sweep);
push(oscillator.width + oscillator.sweep, MarkKind::Sweep);
}
}
cycles(1.0, &mut push);
}
Shape::Noise { .. } => {}
}
marks.into_iter().flatten()
}
}
fn cycles(turns: f32, push: &mut impl FnMut(f32, MarkKind)) {
for cycle in 1..=u8::MAX {
let cycle = f32::from(cycle);
if cycle > turns {
break;
}
push(cycle / turns, MarkKind::Cycle);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EnvelopeId {
Vca,
Vcf,
Mod,
}
impl EnvelopeId {
pub const ALL: [Self; 3] = [Self::Vca, Self::Vcf, Self::Mod];
const fn parameters(self) -> [ParamId; 8] {
match self {
Self::Vca => [
ParamId::VcaEnvelopeAttackTime,
ParamId::VcaEnvelopeDecayTime,
ParamId::VcaEnvelopeSustainLevel,
ParamId::VcaEnvelopeReleaseTime,
ParamId::VcaEnvelopeAttackCurve,
ParamId::VcaEnvelopeDecayCurve,
ParamId::VcaEnvelopeSustainCurve,
ParamId::VcaEnvelopeReleaseCurve,
],
Self::Vcf => [
ParamId::VcfEnvelopeAttackTime,
ParamId::VcfEnvelopeDecayTime,
ParamId::VcfEnvelopeSustainLevel,
ParamId::VcfEnvelopeReleaseTime,
ParamId::VcfEnvelopeAttackCurve,
ParamId::VcfEnvelopeDecayCurve,
ParamId::VcfEnvelopeSustainCurve,
ParamId::VcfEnvelopeReleaseCurve,
],
Self::Mod => [
ParamId::ModEnvelopeAttackTime,
ParamId::ModEnvelopeDecayTime,
ParamId::ModEnvelopeSustainLevel,
ParamId::ModEnvelopeReleaseTime,
ParamId::ModEnvelopeAttackCurve,
ParamId::ModEnvelopeDecayCurve,
ParamId::ModEnvelopeSustainCurve,
ParamId::ModEnvelopeReleaseCurve,
],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LfoId {
One,
Two,
}
impl LfoId {
pub const ALL: [Self; 2] = [Self::One, Self::Two];
const fn parameters(self) -> [ParamId; 4] {
match self {
Self::One => [
ParamId::Lfo1Shape,
ParamId::Lfo1SlewRate,
ParamId::Lfo1KeySync,
ParamId::Lfo1DelayFade,
],
Self::Two => [
ParamId::Lfo2Shape,
ParamId::Lfo2SlewRate,
ParamId::Lfo2KeySync,
ParamId::Lfo2DelayFade,
],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum OscillatorId {
One,
Two,
}
impl OscillatorId {
pub const ALL: [Self; 2] = [Self::One, Self::Two];
}
const HOLD_WIDTH: f32 = 0.5;
#[must_use]
pub fn envelope(program: &Program, which: EnvelopeId) -> Generator {
let [
attack,
decay,
sustain,
release,
attack_curve,
decay_curve,
sustain_curve,
release_curve,
] = which.parameters().map(|parameter| program.get(parameter));
let attack = byte(attack);
let decay = byte(decay);
let release = byte(release);
let sustain = byte(sustain);
let total = attack + decay + HOLD_WIDTH + release;
let share = |of: f32| of / total;
let first = share(attack);
let second = first + share(decay);
let third = second + share(HOLD_WIDTH);
let slope = (byte(sustain_curve) - 0.5) * 2.0;
let sustain_end = if slope < 0.0 {
sustain * (1.0 + slope)
} else {
sustain + (1.0 - sustain) * slope
};
Generator {
shape: Shape::Envelope(Envelope {
ends: [first, second, third],
sustain,
sustain_end,
bends: [
bend(attack_curve),
bend(decay_curve),
1.0,
bend(release_curve),
],
}),
scale: Scale::Normalised,
}
}
#[must_use]
pub fn lfo(program: &Program, which: LfoId) -> Generator {
lfo_read(program, which, false)
}
#[must_use]
pub fn lfo_unipolar(program: &Program, which: LfoId) -> Generator {
lfo_read(program, which, true)
}
fn lfo_read(program: &Program, which: LfoId, unipolar: bool) -> Generator {
let [shape, slew, key_sync, _] = which.parameters().map(|parameter| program.get(parameter));
let shape = LfoShape::from_raw(shape).unwrap_or(LfoShape::Sine);
let turns = match shape {
LfoShape::SampleAndHold | LfoShape::SampleAndGlide => SAMPLED_TURNS,
_ => 1.0,
};
Generator {
shape: Shape::Lfo(Lfo {
shape,
turns,
slew: byte(slew),
unipolar,
synced: key_sync != 0,
}),
scale: Scale::Turns(turns),
}
}
#[must_use]
pub fn lfo_fade(program: &Program, which: LfoId) -> Generator {
let [_, _, _, fade] = which.parameters();
let fade = byte(program.get(fade));
Generator {
shape: Shape::Fade {
end: fade / (fade + HOLD_WIDTH),
},
scale: Scale::Normalised,
}
}
const FILTER_SPAN: f32 = 3.0;
pub const FILTER_CEILING_DB: f32 = 12.0;
pub const FILTER_FLOOR_DB: f32 = -48.0;
pub const FILTER_UNITY: f32 = -FILTER_FLOOR_DB / (FILTER_CEILING_DB - FILTER_FLOOR_DB);
#[must_use]
pub fn filter_response(program: &Program) -> Generator {
let slope = match program.vcf2_pole_mode() {
Some(VcfPoleMode::TwoPole) => 12.0,
Some(VcfPoleMode::FourPole) | None => 24.0,
};
filter(Filter {
slope,
resonance: byte(program.get(ParamId::VcfResonance)),
span: FILTER_SPAN,
pass: Pass::Low,
})
}
const HIGH_PASS_SLOPE: f32 = 6.0;
#[must_use]
pub const fn high_pass_response(program: &Program) -> Generator {
let _ = program;
filter(Filter {
slope: HIGH_PASS_SLOPE,
resonance: 0.0,
span: FILTER_SPAN,
pass: Pass::High,
})
}
const fn filter(filter: Filter) -> Generator {
Generator {
shape: Shape::Filter(filter),
scale: Scale::Octaves(filter.span * 2.0),
}
}
const PULSE_REACH: f32 = 0.49;
#[must_use]
pub fn oscillator(program: &Program, which: OscillatorId) -> Generator {
let oscillator = match which {
OscillatorId::One => {
let depth = byte(program.get(ParamId::Osc1PwmDepth)) * PULSE_REACH;
let manual = matches!(program.osc1_pwm_source(), Some(PwmSource::Manual) | None);
Oscillator {
saw: program.osc1_saw_enable(),
pulse: program.osc1_pulse_enable(),
width: if manual { 0.5 + depth } else { 0.5 },
sweep: if manual { 0.0 } else { depth },
level: 1.0,
}
}
OscillatorId::Two => Oscillator {
saw: false,
pulse: true,
width: 0.5,
sweep: 0.0,
level: byte(program.get(ParamId::Osc2Level)),
},
};
Generator {
shape: Shape::Oscillator(oscillator),
scale: Scale::Turns(1.0),
}
}
#[must_use]
pub fn noise(program: &Program) -> Generator {
Generator {
shape: Shape::Noise {
level: byte(program.get(ParamId::NoiseLevel)),
},
scale: Scale::Normalised,
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Gate {
start: f32,
end: f32,
}
impl Gate {
#[must_use]
pub const fn start(&self) -> f32 {
self.start
}
#[must_use]
pub const fn end(&self) -> f32 {
self.end
}
#[must_use]
pub fn length(&self) -> f32 {
self.end - self.start
}
}
pub const GATES_DRAWN: usize = 4;
pub fn arpeggiator_gates(program: &Program) -> impl Iterator<Item = Gate> {
let open = byte(program.get(ParamId::ArpGateTime));
(0..GATES_DRAWN).filter_map(move |step| {
if open <= 0.0 {
return None;
}
let start = step_start(step);
Some(Gate {
start,
end: start + open,
})
})
}
fn step_start(step: usize) -> f32 {
f32::from(u8::try_from(step).unwrap_or(u8::MAX))
}
pub(crate) const MAX_TAPS: usize = 4;
pub(crate) fn taps(taps: [(f32, f32); MAX_TAPS], used: usize) -> Generator {
Generator {
shape: Shape::Taps {
taps,
used: used.min(MAX_TAPS),
},
scale: Scale::Normalised,
}
}
fn taps_at(taps: &[(f32, f32); MAX_TAPS], used: usize, t: f32) -> f32 {
const WIDTH: f32 = 0.014;
let mut height = 0.0_f32;
for &(at, tall) in taps.iter().take(used) {
let distance = (t - at).abs();
if distance < WIDTH {
height = height.max(tall * (1.0 - distance / WIDTH));
}
}
height
}
fn byte(raw: u8) -> f32 {
f32::from(raw) / 255.0
}
fn bend(curve: u8) -> f32 {
math::exp2((f32::from(curve) - 128.0) / 64.0)
}
fn bent(u: f32, k: f32) -> f32 {
let u = u.clamp(0.0, 1.0);
let denominator = u + k * (1.0 - u);
if denominator <= 0.0 {
u
} else {
u / denominator
}
}
impl Envelope {
fn at(&self, t: f32) -> f32 {
let [first, second, third] = self.ends;
if t < first {
return bent(divide(t, 0.0, first), self.bends[0]);
}
if t < second {
let u = bent(divide(t, first, second), self.bends[1]);
return 1.0 + (self.sustain - 1.0) * u;
}
if t < third {
let u = divide(t, second, third);
return self.sustain + (self.sustain_end - self.sustain) * u;
}
let u = bent(divide(t, third, 1.0), self.bends[3]);
self.sustain_end * (1.0 - u)
}
}
fn divide(t: f32, from: f32, to: f32) -> f32 {
let width = to - from;
if width <= 0.0 {
0.0
} else {
((t - from) / width).clamp(0.0, 1.0)
}
}
pub const SAMPLED_TURNS: f32 = 6.0;
const SAMPLED: [f32; 8] = [0.72, 0.18, 0.95, 0.41, 0.08, 0.63, 0.31, 0.86];
const SLEW_STEPS: u8 = 96;
impl Lfo {
fn at(&self, phase: f32) -> f32 {
if self.slew <= 0.0 {
return shape_at(self.shape, phase);
}
let limit = 2.0 / self.slew;
let start = -1.0;
let step = 1.0 / f32::from(SLEW_STEPS);
let mut level = shape_at(self.shape, start);
let mut previous = start;
for count in 1..=u16::MAX {
let at = (start + f32::from(count) * step).min(phase);
let most = limit * (at - previous);
let target = shape_at(self.shape, at);
level += (target - level).clamp(-most, most);
if at >= phase {
break;
}
previous = at;
}
level
}
}
fn shape_at(shape: LfoShape, t: f32) -> f32 {
match shape {
LfoShape::Sine => 0.5 + 0.5 * math::sin_turns(t),
LfoShape::Triangle => {
let t = wrap(t);
if t < 0.5 { t * 2.0 } else { 2.0 - t * 2.0 }
}
LfoShape::Square => {
if wrap(t) < 0.5 {
1.0
} else {
0.0
}
}
LfoShape::RampUp => wrap(t),
LfoShape::RampDown => 1.0 - wrap(t),
LfoShape::SampleAndHold => sampled(t),
LfoShape::SampleAndGlide => {
let previous = sampled(t - 1.0);
previous + (sampled(t) - previous) * math::fract(t)
}
}
}
fn wrap(t: f32) -> f32 {
let within = math::fract(t);
if t > 0.0 && within <= 0.0 {
1.0
} else {
within
}
}
fn sampled(t: f32) -> f32 {
let cycle = math::floor(t);
let index = (cycle - math::floor(cycle / 8.0) * 8.0).clamp(0.0, 7.0);
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped to 0..=7 on the line above"
)]
let index = index as usize;
SAMPLED.get(index).copied().unwrap_or(0.5)
}
fn noise_at(t: f32) -> f32 {
math::fract((math::sin_turns(t * 89.0) + 1.5) * 1_013.0)
}
impl Filter {
fn at(&self, t: f32) -> f32 {
let octaves = (t - 0.5) * 2.0 * self.span;
let octaves = match self.pass {
Pass::Low => octaves,
Pass::High => -octaves,
};
let squared = 2.0 * (self.slope / 6.0) * octaves;
let log = if squared > 30.0 {
squared
} else {
math::log2(1.0 + math::exp2(squared))
};
let magnitude_db = -3.010_3 * log;
let distance = octaves * (2.0 + self.resonance * 6.0);
let peak_db = self.resonance * FILTER_CEILING_DB / (1.0 + distance * distance);
let db = magnitude_db + peak_db;
((db - FILTER_FLOOR_DB) / (FILTER_CEILING_DB - FILTER_FLOOR_DB)).clamp(0.0, 1.0)
}
}
impl Oscillator {
fn at(&self, t: f32) -> f32 {
let mut sum = 0.0;
let mut waves = 0_u8;
if self.saw {
sum += t * 2.0 - 1.0;
waves += 1;
}
if self.pulse {
sum += if t < self.width { 1.0 } else { -1.0 };
waves += 1;
}
if waves == 0 {
return 0.5;
}
0.5 + 0.5 * self.level * sum / f32::from(waves)
}
}
#[cfg(test)]
#[expect(
clippy::expect_used,
reason = "a failed expectation is the test failure"
)]
mod tests {
use super::{
EnvelopeId, FILTER_CEILING_DB, FILTER_FLOOR_DB, FILTER_SPAN, FILTER_UNITY, GATES_DRAWN,
Generator, HIGH_PASS_SLOPE, LfoId, MAX_MARKS, MarkKind, OscillatorId, SAMPLED_TURNS, Scale,
Segment, arpeggiator_gates, envelope, filter_response, high_pass_response, lfo, lfo_fade,
lfo_unipolar, noise, oscillator,
};
use crate::ids::ProtocolVersion;
use crate::program::{LfoShape, Program, PwmSource, VcfPoleMode};
fn program() -> Program {
let mut program = Program::new(ProtocolVersion::V6);
for envelope in EnvelopeId::ALL {
let [_, _, _, _, attack, decay, sustain, release] = envelope.parameters();
for curve in [attack, decay, sustain, release] {
program.set_clamped(curve, 128);
}
}
program
}
fn close(left: f32, right: f32, what: &str) {
assert!((left - right).abs() < 1e-6, "{what}: {left} is not {right}");
}
fn same(left: f32, right: f32, what: &str) {
close(left, right, what);
}
fn walk(generator: &Generator, steps: u8) -> impl Iterator<Item = f32> + '_ {
(0..=steps).map(move |step| generator.at(f32::from(step) / f32::from(steps)))
}
fn every(program: &Program) -> [Generator; 10] {
[
envelope(program, EnvelopeId::Vca),
lfo(program, LfoId::One),
lfo_unipolar(program, LfoId::Two),
lfo_fade(program, LfoId::One),
filter_response(program),
high_pass_response(program),
oscillator(program, OscillatorId::One),
oscillator(program, OscillatorId::Two),
noise(program),
crate::generator::taps([(0.5, 1.0), (1.0, 0.5), (0.0, 0.0), (0.0, 0.0)], 2),
]
}
#[test]
fn every_generator_stays_within_its_range() {
let mut program = program();
program.set_vca_envelope_attack_time(90);
program.set_vca_envelope_decay_time(40);
program.set_vca_envelope_sustain_level(180);
program.set_vca_envelope_release_time(200);
program.set_vcf_resonance(255);
program.set_lfo1_slew_rate(200);
program.set_lfo2_shape(LfoShape::SampleAndGlide);
program.set_lfo2_slew_rate(255);
program.set_osc1_saw_enable(true);
program.set_osc1_pulse_enable(true);
program.set_osc1_pwm_source(PwmSource::Lfo1);
program.set_osc1_pwm_depth(255);
program.set_osc2_level(255);
program.set_noise_level(255);
for generator in every(&program) {
for value in walk(&generator, 200) {
assert!((0.0..=1.0).contains(&value), "{value} is outside the box");
}
for odd in [-1.0, 1.5, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let value = generator.at(odd);
assert!((0.0..=1.0).contains(&value), "at({odd}) gave {value}");
}
assert!((0.0..=1.0).contains(&generator.rest()));
let mut marks = 0;
for mark in generator.marks() {
assert!((0.0..=1.0).contains(&mark.at()), "{mark:?} is off the axis");
marks += 1;
}
assert!(marks <= MAX_MARKS);
}
}
#[test]
fn an_envelope_gives_each_segment_its_own_share_of_the_width() {
let mut program = program();
program.set_vcf_envelope_attack_time(255);
program.set_vcf_envelope_decay_time(0);
program.set_vcf_envelope_sustain_level(255);
program.set_vcf_envelope_release_time(0);
let long = envelope(&program, EnvelopeId::Vcf);
assert!(long.at(0.33) < 0.6, "{}", long.at(0.33));
assert!(long.at(0.7) > 0.99, "{}", long.at(0.7));
program.set_vcf_envelope_attack_time(0);
let short = envelope(&program, EnvelopeId::Vcf);
assert!(short.at(0.01) > 0.99, "{}", short.at(0.01));
}
#[test]
fn an_envelope_marks_where_each_segment_begins() {
let mut program = program();
program.set_mod_envelope_attack_time(255);
program.set_mod_envelope_decay_time(255);
program.set_mod_envelope_sustain_level(128);
program.set_mod_envelope_release_time(255);
let shape = envelope(&program, EnvelopeId::Mod);
let mut marks = shape.marks();
let mut previous = 0.0;
for segment in Segment::ALL {
let mark = marks.next().expect("four segments");
assert_eq!(mark.kind(), MarkKind::Segment(segment));
assert!(mark.at() >= previous, "{segment:?} is out of order");
previous = mark.at();
match segment {
Segment::Attack => close(mark.at(), 0.0, "the attack begins at the start"),
Segment::Decay => close(shape.at(mark.at()), 1.0, "the decay begins at the top"),
Segment::Sustain => close(
shape.at(mark.at()),
128.0 / 255.0,
"the sustain begins at its level",
),
Segment::Release => assert!(mark.at() < 1.0),
}
}
assert!(marks.next().is_none(), "a fifth mark");
close(shape.rest(), 0.0, "an envelope rests on the floor");
assert!(shape.anchored());
}
#[test]
fn a_curve_byte_bends_a_segment_both_ways_about_the_centre() {
let mut program = program();
program.set_mod_envelope_attack_time(255);
program.set_mod_envelope_decay_time(0);
program.set_mod_envelope_sustain_level(255);
program.set_mod_envelope_release_time(0);
let rise_at = |curve: u8, program: &mut Program| {
program.set_mod_envelope_attack_curve(curve);
envelope(program, EnvelopeId::Mod).at(1.0 / 3.0)
};
let straight = rise_at(128, &mut program);
let fast = rise_at(0, &mut program);
let slow = rise_at(255, &mut program);
assert!((straight - 0.5).abs() < 0.02, "{straight}");
assert!(fast > straight + 0.2, "{fast} against {straight}");
assert!(slow < straight - 0.2, "{slow} against {straight}");
for curve in [0, 64, 128, 192, 255] {
program.set_mod_envelope_attack_curve(curve);
let bent = envelope(&program, EnvelopeId::Mod);
assert!(
bent.at(0.0) < 0.01,
"curve {curve} starts at {}",
bent.at(0.0)
);
}
}
#[test]
fn every_lfo_shape_is_drawn_and_says_how_many_cycles_it_covers() {
let mut program = program();
for shape in LfoShape::ALL.iter().copied() {
program.set_lfo1_shape(shape);
let generator = lfo(&program, LfoId::One);
let expected = match shape {
LfoShape::SampleAndHold | LfoShape::SampleAndGlide => SAMPLED_TURNS,
_ => 1.0,
};
assert_eq!(generator.scale(), Scale::Turns(expected), "{shape}");
let high = walk(&generator, 64).fold(f32::MIN, f32::max);
let low = walk(&generator, 64).fold(f32::MAX, f32::min);
assert!(high - low > 0.3, "{shape} spans {low} to {high}");
let mut cycles = 0.0;
for mark in generator.marks() {
assert_eq!(mark.kind(), MarkKind::Cycle);
cycles += 1.0;
close(mark.at(), cycles / expected, "a cycle boundary");
}
close(cycles, expected, "one mark per cycle");
}
program.set_lfo1_shape(LfoShape::Sine);
let sine = lfo(&program, LfoId::One);
close(sine.at(0.0), 0.5, "a sine starts at its rest");
close(
sine.at(0.25),
1.0,
"and reaches the top a quarter of the way round",
);
close(sine.at(0.5), 0.5, "back through the middle");
close(sine.at(0.75), 0.0, "and the bottom three quarters round");
close(sine.at(1.0), 0.5, "to end where it began");
program.set_lfo1_shape(LfoShape::RampUp);
let up = lfo(&program, LfoId::One);
assert!(up.at(0.0) < up.at(0.5) && up.at(0.5) < up.at(1.0));
program.set_lfo1_shape(LfoShape::RampDown);
let down = lfo(&program, LfoId::One);
assert!(down.at(0.0) > down.at(0.5) && down.at(0.5) > down.at(1.0));
program.set_lfo1_shape(LfoShape::Square);
let square = lfo(&program, LfoId::One);
close(square.at(0.25), 1.0, "the top of a square");
close(square.at(0.75), 0.0, "the bottom of a square");
}
#[test]
fn the_sampled_shapes_step_and_do_not_move_between_calls() {
let mut program = program();
program.set_lfo1_shape(LfoShape::SampleAndHold);
let held = lfo(&program, LfoId::One);
let cycle = 1.0 / SAMPLED_TURNS;
same(
held.at(cycle * 0.1),
held.at(cycle * 0.9),
"a cycle of the hold",
);
let steps: [f32; 6] = core::array::from_fn(|cycle| {
let cycle = f32::from(u8::try_from(cycle).unwrap_or(u8::MAX));
held.at((cycle + 0.5) / SAMPLED_TURNS)
});
assert!(
steps
.windows(2)
.any(|pair| matches!(pair, [left, right] if (left - right).abs() > 1e-6)),
"the held value never changes: {steps:?}"
);
assert!(walk(&held, 64).eq(walk(&lfo(&program, LfoId::One), 64)));
program.set_lfo1_shape(LfoShape::SampleAndGlide);
let glide = lfo(&program, LfoId::One);
assert!((glide.at(cycle * 0.1) - glide.at(cycle * 0.9)).abs() > 1e-6);
let late = cycle * 0.99;
assert!(
(glide.at(late) - held.at(late)).abs() < 0.01,
"{} against {}",
glide.at(late),
held.at(late)
);
}
#[test]
fn the_slew_rate_rounds_a_square_into_a_ramp() {
let mut program = program();
program.set_lfo1_shape(LfoShape::Square);
program.set_lfo1_slew_rate(0);
let sharp = lfo(&program, LfoId::One);
close(sharp.at(0.51), 0.0, "an unslewed edge has fallen at once");
program.set_lfo1_slew_rate(255);
let full = lfo(&program, LfoId::One);
assert!((full.at(0.75) - 0.5).abs() < 0.03, "{}", full.at(0.75));
assert!(full.at(1.0) < 0.03, "{}", full.at(1.0));
assert!((full.at(0.25) - 0.5).abs() < 0.03, "{}", full.at(0.25));
assert!(full.at(0.5) > 0.97, "{}", full.at(0.5));
program.set_lfo1_slew_rate(128);
let half = lfo(&program, LfoId::One);
for t in [0.55, 0.625, 0.7] {
assert!(half.at(t) > sharp.at(t), "at {t}");
assert!(half.at(t) < full.at(t), "at {t}");
}
program.set_lfo1_shape(LfoShape::Sine);
program.set_lfo1_slew_rate(64);
let slewed = lfo(&program, LfoId::One);
program.set_lfo1_slew_rate(0);
let plain = lfo(&program, LfoId::One);
for (left, right) in walk(&slewed, 32).zip(walk(&plain, 32)) {
assert!((left - right).abs() < 0.03, "{left} against {right}");
}
}
#[test]
fn key_sync_anchors_the_picture_and_changes_nothing_in_it() {
let mut program = program();
program.set_lfo1_key_sync(false);
let free = lfo(&program, LfoId::One);
program.set_lfo1_key_sync(true);
let synced = lfo(&program, LfoId::One);
assert!(!free.anchored());
assert!(synced.anchored());
assert!(walk(&free, 32).eq(walk(&synced, 32)));
assert!(!lfo(&program, LfoId::Two).anchored());
}
#[test]
fn the_fade_rises_to_full_depth_and_holds() {
let mut program = program();
program.set_lfo1_delay_fade(0);
let none = lfo_fade(&program, LfoId::One);
for value in walk(&none, 16) {
close(value, 1.0, "no fade is full depth");
}
program.set_lfo1_delay_fade(255);
let long = lfo_fade(&program, LfoId::One);
assert_eq!(long.scale(), Scale::Normalised);
close(long.rest(), 0.0, "a fade rests on the floor");
assert!(long.anchored());
let end = 1.0 / 1.5;
close(long.at(end / 2.0), 0.5, "halfway up the rise");
close(long.at(end), 1.0, "the top of the rise");
close(long.at(1.0), 1.0, "held");
let mut marks = long.marks();
let attack = marks.next().expect("the rise");
let hold = marks.next().expect("the hold");
assert_eq!(attack.kind(), MarkKind::Segment(Segment::Attack));
assert_eq!(hold.kind(), MarkKind::Segment(Segment::Sustain));
close(hold.at(), end, "where the hold begins");
assert!(marks.next().is_none());
program.set_lfo2_delay_fade(0);
close(lfo_fade(&program, LfoId::Two).at(0.0), 1.0, "LFO 2 at full");
}
#[test]
fn four_poles_roll_off_twice_as_fast_as_two() {
let mut program = program();
program.set_vcf_resonance(0);
program.set_vcf2_pole_mode(VcfPoleMode::FourPole);
let steep = filter_response(&program);
program.set_vcf2_pole_mode(VcfPoleMode::TwoPole);
let shallow = filter_response(&program);
assert!((steep.at(0.5) - shallow.at(0.5)).abs() < 0.01);
for step in 6_u8..=9 {
let t = f32::from(step) / 10.0;
assert!(steep.at(t) < shallow.at(t), "at {t}");
}
assert!((steep.at(0.1) - FILTER_UNITY).abs() < 0.01);
assert!((shallow.at(0.1) - FILTER_UNITY).abs() < 0.01);
close(steep.rest(), FILTER_UNITY, "a filter rests at unity");
let mut marks = steep.marks();
let corner = marks.next().expect("a corner");
assert_eq!(corner.kind(), MarkKind::Corner);
close(corner.at(), 0.5, "the corner");
assert!(marks.next().is_none());
}
#[test]
fn the_drawn_slope_is_the_published_decibels_per_octave() {
let mut program = program();
program.set_vcf_resonance(0);
let window = FILTER_CEILING_DB - FILTER_FLOOR_DB;
for (poles, per_octave) in [(VcfPoleMode::FourPole, 24.0), (VcfPoleMode::TwoPole, 12.0)] {
program.set_vcf2_pole_mode(poles);
let response = filter_response(&program);
let one = response.at(0.5 + 1.0 / (FILTER_SPAN * 2.0));
let two = response.at(0.5 + 2.0 / (FILTER_SPAN * 2.0));
let fallen = (one - two) * window;
assert!(
(fallen - per_octave).abs() < 0.5,
"{poles:?} fell {fallen} dB over the octave, not {per_octave}"
);
}
}
#[test]
fn the_high_pass_falls_to_the_left_at_six_decibels_an_octave() {
let mut program = program();
let high = high_pass_response(&program);
program.set_vcf2_pole_mode(VcfPoleMode::TwoPole);
program.set_vcf_resonance(0);
let low = filter_response(&program);
assert_eq!(high.scale(), low.scale());
close(high.rest(), FILTER_UNITY, "a filter rests at unity");
assert!(high.anchored());
assert!((high.at(0.9) - FILTER_UNITY).abs() < 0.01);
close(high.at(0.5), low.at(0.5), "both corners are 3 dB down");
assert!(high.at(0.3) < high.at(0.4) && high.at(0.4) < high.at(0.5));
let window = FILTER_CEILING_DB - FILTER_FLOOR_DB;
let one = high.at(0.5 - 2.0 / (FILTER_SPAN * 2.0));
let two = high.at(0.5 - 3.0 / (FILTER_SPAN * 2.0));
let fallen = (one - two) * window;
assert!(
(fallen - HIGH_PASS_SLOPE).abs() < 0.5,
"fell {fallen} dB over the octave, not {HIGH_PASS_SLOPE}"
);
let corner = high.marks().next().expect("a corner");
assert_eq!(corner.kind(), MarkKind::Corner);
program.set_vcf_bass_boost(true);
assert!(walk(&high, 16).eq(walk(&high_pass_response(&program), 16)));
}
#[test]
fn resonance_lifts_the_corner() {
let mut program = program();
program.set_vcf2_pole_mode(VcfPoleMode::FourPole);
program.set_vcf_resonance(0);
let dry = filter_response(&program);
program.set_vcf_resonance(255);
let wet = filter_response(&program);
let window = FILTER_CEILING_DB - FILTER_FLOOR_DB;
let lift = wet.at(0.5) - dry.at(0.5);
assert!(
(lift - FILTER_CEILING_DB / window).abs() < 0.02,
"lifted by {lift} of the height"
);
assert!(wet.at(0.5) > FILTER_UNITY, "{}", wet.at(0.5));
assert!((wet.at(0.05) - dry.at(0.05)).abs() < 0.05);
}
#[test]
fn the_first_oscillator_is_what_is_switched_on() {
let mut program = program();
program.set_osc1_pwm_source(PwmSource::Manual);
program.set_osc1_pwm_depth(0);
program.set_osc1_saw_enable(false);
program.set_osc1_pulse_enable(false);
let silent = oscillator(&program, OscillatorId::One);
assert_eq!(silent.scale(), Scale::Turns(1.0));
close(silent.rest(), 0.5, "an oscillator rests in the middle");
assert!(!silent.anchored());
for value in walk(&silent, 16) {
close(value, 0.5, "an oscillator making nothing");
}
assert!(silent.marks().all(|mark| mark.kind() == MarkKind::Cycle));
program.set_osc1_saw_enable(true);
let saw = oscillator(&program, OscillatorId::One);
close(saw.at(0.0), 0.0, "a saw starts at the bottom");
close(saw.at(0.5), 0.5, "and rises through the middle");
close(saw.at(1.0), 1.0, "to the top");
program.set_osc1_saw_enable(false);
program.set_osc1_pulse_enable(true);
program.set_osc1_pwm_depth(255);
let wide = oscillator(&program, OscillatorId::One);
close(wide.at(0.98), 1.0, "still high near the end");
close(wide.at(0.995), 0.0, "and down at the very end");
let width = wide
.marks()
.find(|mark| mark.kind() == MarkKind::Width)
.expect("a pulse has a width");
close(width.at(), 0.99, "the falling edge");
assert!(!wide.marks().any(|mark| mark.kind() == MarkKind::Sweep));
program.set_osc1_saw_enable(true);
program.set_osc1_pwm_depth(0);
let both = oscillator(&program, OscillatorId::One);
assert!((both.at(0.499) - 0.75).abs() < 0.01, "{}", both.at(0.499));
close(both.at(0.5), 0.25, "saw and pulse, pulse low");
}
#[test]
fn a_modulated_pulse_is_square_with_its_reach_marked() {
let mut program = program();
program.set_osc1_saw_enable(false);
program.set_osc1_pulse_enable(true);
program.set_osc1_pwm_source(PwmSource::Lfo1);
program.set_osc1_pwm_depth(255);
let swept = oscillator(&program, OscillatorId::One);
close(swept.at(0.25), 1.0, "square");
close(swept.at(0.75), 0.0, "square");
let mut sweeps = swept.marks().filter(|mark| mark.kind() == MarkKind::Sweep);
close(
sweeps.next().expect("one side").at(),
0.01,
"as far left as it goes",
);
close(
sweeps.next().expect("the other").at(),
0.99,
"as far right as it goes",
);
assert!(sweeps.next().is_none());
program.set_osc1_pwm_depth(0);
assert!(
!oscillator(&program, OscillatorId::One)
.marks()
.any(|mark| mark.kind() == MarkKind::Sweep)
);
}
#[test]
fn the_second_oscillator_is_a_square_at_its_level() {
let mut program = program();
program.set_osc2_level(0);
let off = oscillator(&program, OscillatorId::Two);
for value in walk(&off, 16) {
close(value, 0.5, "off");
}
program.set_osc2_level(255);
let full = oscillator(&program, OscillatorId::Two);
close(full.at(0.25), 1.0, "the top of a full square");
close(full.at(0.75), 0.0, "the bottom");
program.set_osc2_level(128);
let half = oscillator(&program, OscillatorId::Two);
let tall = half.at(0.25) - 0.5;
assert!(tall > 0.2 && tall < 0.3, "{tall}");
program.set_osc1_pwm_depth(255);
let width = oscillator(&program, OscillatorId::Two)
.marks()
.find(|mark| mark.kind() == MarkKind::Width)
.expect("a square has a width");
close(width.at(), 0.5, "a square");
}
#[test]
fn the_noise_scatters_to_its_level_and_holds_still() {
let mut program = program();
program.set_noise_level(0);
for value in walk(&noise(&program), 16) {
close(value, 0.5, "no noise");
}
program.set_noise_level(255);
let loud = noise(&program);
assert_eq!(loud.scale(), Scale::Normalised);
close(loud.rest(), 0.5, "the noise rests in the middle");
assert!(!loud.anchored());
assert_eq!(loud.marks().count(), 0);
let high = walk(&loud, 64).fold(f32::MIN, f32::max);
let low = walk(&loud, 64).fold(f32::MAX, f32::min);
assert!(high > 0.8 && low < 0.2, "{low} to {high}");
assert!(walk(&loud, 64).eq(walk(&noise(&program), 64)));
program.set_noise_level(128);
let quiet = noise(&program);
let high = walk(&quiet, 64).fold(f32::MIN, f32::max);
assert!(high < 0.8, "{high}");
}
#[test]
fn a_gate_is_the_fraction_of_a_step_the_manual_gives() {
let mut program = program();
program.set_arp_gate_time(0);
assert_eq!(arpeggiator_gates(&program).count(), 0);
program.set_arp_gate_time(255);
assert_eq!(arpeggiator_gates(&program).count(), GATES_DRAWN);
{
let mut full = arpeggiator_gates(&program);
let first = full.next().expect("four gates");
let second = full.next().expect("four gates");
close(first.length(), 1.0, "a full gate");
close(first.end(), second.start(), "the next step");
}
program.set_arp_gate_time(128);
let first = arpeggiator_gates(&program).next().expect("four gates");
close(first.length(), 128.0 / 255.0, "half a step");
for (step, gate) in arpeggiator_gates(&program).enumerate() {
let start = f32::from(u8::try_from(step).expect("four steps"));
close(gate.start(), start, "the step a gate opens on");
assert!(gate.end() <= start + 1.0);
}
}
#[test]
fn the_three_envelopes_read_their_own_parameters() {
let mut program = program();
for envelope in EnvelopeId::ALL {
let [_, _, sustain, ..] = envelope.parameters();
program.set_clamped(sustain, 255);
}
program.set_vca_envelope_attack_time(255);
program.set_vcf_envelope_attack_time(0);
program.set_mod_envelope_attack_time(0);
let vca = envelope(&program, EnvelopeId::Vca);
let vcf = envelope(&program, EnvelopeId::Vcf);
let modulation = envelope(&program, EnvelopeId::Mod);
assert!(vca.at(0.1) < 0.5);
assert!(vcf.at(0.1) > 0.9);
assert!(modulation.at(0.1) > 0.9);
program.set_lfo1_shape(LfoShape::RampUp);
program.set_lfo2_shape(LfoShape::RampDown);
assert!(lfo(&program, LfoId::One).at(0.9) > 0.8);
assert!(lfo(&program, LfoId::Two).at(0.9) < 0.2);
}
}