Skip to main content

wavegraph_core/
polyphony.rs

1//! Four-voice keyboard modes shared by the organ and wavetable synths.
2
3use crate::midi::Note;
4
5const CHORD_COUNT: u8 = 16;
6const CHORDS: [(&str, &[u8]); CHORD_COUNT as usize] = [
7    ("Maj", &[0, 4, 7]),
8    ("Min", &[0, 3, 7]),
9    ("Maj7", &[0, 4, 7, 11]),
10    ("m7", &[0, 3, 7, 10]),
11    ("7", &[0, 4, 7, 10]),
12    ("Sus2", &[0, 2, 7]),
13    ("Sus4", &[0, 5, 7]),
14    ("Dim", &[0, 3, 6]),
15    ("Aug", &[0, 4, 8]),
16    ("6", &[0, 4, 7, 9]),
17    ("m6", &[0, 3, 7, 9]),
18    ("Dim7", &[0, 3, 6, 9]),
19    ("m7b5", &[0, 3, 6, 10]),
20    ("mMaj7", &[0, 3, 7, 11]),
21    ("Add9", &[0, 4, 7, 14]),
22    ("mAdd9", &[0, 3, 7, 14]),
23];
24
25/// A root-position chord of up to four notes.
26#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
27pub struct Chord(u8);
28
29impl Chord {
30    /// Major triad.
31    pub const MAJOR: Self = Self(0);
32
33    /// Short chord symbol for panel displays.
34    #[must_use]
35    pub fn name(self) -> &'static str {
36        CHORDS[usize::from(self.0)].0
37    }
38
39    /// Move through the chord catalog, wrapping at either end.
40    #[must_use]
41    pub fn turn(self, delta: i8) -> Self {
42        let i = i16::from(self.0).saturating_add(i16::from(delta));
43        Self(i.rem_euclid(i16::from(CHORD_COUNT)).to_le_bytes()[0])
44    }
45}
46
47/// Assignment of four oscillators to held notes.
48#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
49pub enum VoiceMode {
50    /// Each key takes one voice with the instrument's usual stealing policy.
51    #[default]
52    Poly,
53    /// Play a chord from the most recent held key.
54    Chord(Chord),
55    /// Stack four detuned oscillators on the most recent held key.
56    Unison,
57}
58
59/// Four most recently held roots, in priority order, with their strike velocities.
60#[derive(Clone, Copy, Debug)]
61pub struct Keyboard {
62    /// Current voice allocation mode.
63    pub mode: VoiceMode,
64    held: [Option<Note>; 4],
65}
66
67impl Keyboard {
68    /// Silent polyphonic keyboard.
69    pub const EMPTY: Self = Self {
70        mode: VoiceMode::Poly,
71        held: [None; 4],
72    };
73
74    /// Remember a playable nonzero-velocity strike, moving restrikes to the front.
75    pub fn press(&mut self, note: Note) {
76        let index = self
77            .held
78            .iter()
79            .position(|n| n.is_some_and(|n| n.number == note.number))
80            .unwrap_or(3);
81        self.held[..=index].rotate_right(1);
82        self.held[0] = Some(note);
83    }
84
85    /// Forget a root. Returns true if removing it changes the active chord or unison root.
86    pub fn release(&mut self, note: u8) -> bool {
87        let Some(index) = self
88            .held
89            .iter()
90            .position(|n| n.is_some_and(|n| n.number == note))
91        else {
92            return false;
93        };
94        self.held[index..].rotate_left(1);
95        self.held[3] = None;
96        index == 0
97    }
98
99    /// Drop all key ownership while retaining the selected mode.
100    pub fn clear(&mut self) {
101        self.held.fill(None);
102    }
103
104    /// Sounding pitch and velocity in a slot when rebuilding the four voices.
105    #[must_use]
106    pub fn voice(&self, slot: usize) -> Option<Note> {
107        let root = self.held[0]?;
108        match self.mode {
109            VoiceMode::Poly => self.held.get(slot).copied().flatten(),
110            VoiceMode::Unison => (slot < 4).then_some(root),
111            VoiceMode::Chord(chord) => {
112                let offset = *CHORDS[usize::from(chord.0)].1.get(slot)?;
113                let number = root.number.checked_add(offset)?;
114                (number < 128).then_some(Note { number, ..root })
115            }
116        }
117    }
118
119    /// Detune the four unison slots approximately −7, −2, +2 and +7 cents.
120    /// Return zero for increments reaching Nyquist.
121    #[must_use]
122    pub fn step(&self, slot: usize, base: u32) -> u32 {
123        if self.mode != VoiceMode::Unison {
124            return base;
125        }
126        let step = match slot {
127            0 => base.saturating_sub(base >> 8),
128            1 => base.saturating_sub(base >> 10),
129            2 => base.saturating_add(base >> 10),
130            _ => base.saturating_add(base >> 8),
131        };
132        if step < (1 << 31) { step } else { 0 }
133    }
134}