lactea 0.2.1

MilkDrop engine: preset + expressions + audio + shaders driving lactea-render. Embeddable into any wgpu host.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! BeatDrop's host inputs under `Compat::MilkDrop2` (`CompatRules::md2_input_vars` / `md2_shader_inputs`): the mouse
//! and the arrow-key flags, the wall clock and the shader FFT, as the expressions (`mousex .. totalseconds`) and the
//! shaders (`_c14` / `_c15` / `_c16`, `sampler_fft` / `sampler_wave`) see them.
//!
//! Like the MilkDrop 3 inputs ([`crate::md3_inputs`]) they are sampled **once per rendered frame** at the top of
//! [`crate::Engine::render`] and shared by every state drawn that frame. The engine does no I/O: the host sets the
//! mouse ([`crate::Engine::set_mouse`]), the arrow keys ([`crate::Engine::set_ctrl_keys`]) and the wall clock
//! ([`crate::Engine::set_date_time`]).

use crate::md3_inputs::MouseState;
use lactea_audio::{AudioFrame, BeatDropShaderFft, SHADER_FFT_BINS, SHADER_WAVE_SAMPLES};
use lactea_render::BeatDropTexture;
use std::sync::Arc;

/// The wall clock BeatDrop reads with `GetLocalTime`. The engine never looks at the system clock (a library must be
/// deterministic); until the host calls [`crate::Engine::set_date_time`] it derives the time of day from the frame
/// clock instead (see [`crate::Engine::set_date_time`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DateTime {
    /// Four-digit year (`year`).
    pub year: u16,
    /// 1 ..= 12 (`month`).
    pub month: u8,
    /// 1 ..= 31 (`day`).
    pub day: u8,
    /// 1 = Monday .. 7 = Sunday (`weekday`; BeatDrop maps Windows' Sunday = 0 to 7).
    pub weekday: u8,
    /// 0 ..= 23 (`hour`).
    pub hour: u8,
    /// 0 ..= 59 (`minute`).
    pub minute: u8,
    /// 0 ..= 59 (`second`).
    pub second: u8,
    /// 0 ..= 999 (`milliseconds`).
    pub millisecond: u16,
}

impl DateTime {
    /// Whether every field is in the range it has on a real clock.
    pub fn is_valid(&self) -> bool {
        (1..=12).contains(&self.month)
            && (1..=31).contains(&self.day)
            && (1..=7).contains(&self.weekday)
            && self.hour < 24
            && self.minute < 60
            && self.second < 60
            && self.millisecond < 1000
    }

    /// `totalSeconds`: `hour * 3600 + minute * 60 + second + millisecond * .001`, in `f32` like BeatDrop.
    fn total_seconds(&self) -> f32 {
        f32::from(self.hour) * 3600.0
            + f32::from(self.minute) * 60.0
            + f32::from(self.second)
            + f32::from(self.millisecond) * 0.001
    }

    /// The time of day of a frame clock reading (`seconds` since the start of an unspecified day), with a zero
    /// date: what the engine shows until the host supplies the real clock.
    fn from_frame_time(seconds: f64) -> Self {
        let day = seconds.rem_euclid(86_400.0);
        let whole = day.floor();
        let n = whole as u32;
        DateTime {
            hour: (n / 3600) as u8,
            minute: (n / 60 % 60) as u8,
            second: (n % 60) as u8,
            millisecond: (((day - whole) * 1000.0) as u16).min(999),
            ..DateTime::default()
        }
    }
}

/// The arrow keys held together with Ctrl (`ctrllt ctrlrt ctrldn ctrlup`): BeatDrop sets them from Ctrl + arrow key
/// events. The host reports the current state; the engine samples it once per rendered frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CtrlKeys {
    /// Ctrl + Left (`ctrllt`).
    pub left: bool,
    /// Ctrl + Right (`ctrlrt`).
    pub right: bool,
    /// Ctrl + Down (`ctrldn`).
    pub down: bool,
    /// Ctrl + Up (`ctrlup`).
    pub up: bool,
}

/// The values the expression contexts get for one frame (`milkdropfs.cpp:688-705`).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Md2Vars {
    /// `mousex`, `mousey` (bottom-origin, `-1` outside the window), `mousedown`, `mouseclick`.
    pub mouse: [f64; 4],
    /// `ctrllt`, `ctrlrt`, `ctrldn`, `ctrlup`.
    pub ctrl: [f64; 4],
    /// `year month day weekday hour minute second milliseconds totalseconds`.
    pub date: [f64; 9],
}

/// What [`Md2Inputs::begin_frame`] samples for one frame.
pub(crate) struct Md2Frame {
    pub vars: Md2Vars,
    /// `_c14` of BeatDrop's shaders (`milkdropfs.cpp:5317`): `(x, y, ±lastX, ±lastY)`.
    pub mouse: [f32; 4],
    /// `_c15` (`hour, minute, second, totalSeconds`) and `_c16` (`year, month, day, weekday`).
    pub time_date: [[f32; 4]; 2],
    /// The spectrum / waveform texture (`CompatRules::md2_shader_inputs`).
    pub texture: Option<Arc<BeatDropTexture>>,
}

/// Engine-wide BeatDrop input state; lives as long as the engine and is never reset by a preset change.
pub(crate) struct Md2Inputs {
    mouse: MouseState,
    ctrl: CtrlKeys,
    date: Option<DateTime>,
    /// The button level of the previous frame's sample (initially up).
    prev_down: bool,
    /// `m_lastMouseX` / `m_lastMouseY`: where the last press happened (`y` top-origin).
    last_click: [f32; 2],
    fft: Option<Box<BeatDropShaderFft>>,
}

impl Md2Inputs {
    pub fn new() -> Self {
        Self {
            mouse: MouseState::default(),
            ctrl: CtrlKeys::default(),
            date: None,
            prev_down: false,
            last_click: [0.0, 0.0],
            fft: None,
        }
    }

    pub fn set_mouse(&mut self, m: MouseState) {
        self.mouse = m;
    }

    pub fn set_ctrl_keys(&mut self, k: CtrlKeys) {
        self.ctrl = k;
    }

    pub fn set_date_time(&mut self, d: Option<DateTime>) {
        self.date = d;
    }

    /// Feed the shader FFT's PCM history (created on first use: other modes never pay for it).
    pub fn push_pcm(&mut self, interleaved: &[f32], channels: usize) {
        self.fft
            .get_or_insert_with(|| Box::new(BeatDropShaderFft::new()))
            .push_pcm_f32(interleaved, channels);
    }

    /// `m_mouseX` / `m_mouseY`: `((2 x / w - 1) / 2) + .5` and `((1 - 2 y / h) / 2) + .5` inside the window (the
    /// vertical axis starts at the bottom), `-1` outside.
    fn cursor(&self) -> (f32, f32) {
        match self.mouse.position {
            Some([u, v]) => (((2.0 * u - 1.0) / 2.0) + 0.5, ((1.0 - 2.0 * v) / 2.0) + 0.5),
            None => (-1.0, -1.0),
        }
    }

    /// The expression variables of one sample (`milkdropfs.cpp:688-705`).
    fn vars(&self, (x, y): (f32, f32), down: bool, click: bool, date: &DateTime) -> Md2Vars {
        let flag = |b: bool| if b { 1.0 } else { 0.0 };
        Md2Vars {
            mouse: [f64::from(x), f64::from(y), flag(down), flag(click)],
            ctrl: [
                flag(self.ctrl.left),
                flag(self.ctrl.right),
                flag(self.ctrl.down),
                flag(self.ctrl.up),
            ],
            date: [
                f64::from(date.year),
                f64::from(date.month),
                f64::from(date.day),
                f64::from(date.weekday),
                f64::from(date.hour),
                f64::from(date.minute),
                f64::from(date.second),
                f64::from(date.millisecond),
                f64::from(date.total_seconds()),
            ],
        }
    }

    /// The variables `LoadPerFrameEvallibVars` sets before a preset's init code runs (`state.cpp:1794`): the inputs as
    /// they are now, no click edge (it exists only in a rendered frame) and the clock of `time`.
    pub fn vars_now(&self, time: f64) -> Md2Vars {
        let date = self.date.unwrap_or_else(|| DateTime::from_frame_time(time));
        self.vars(self.cursor(), self.mouse.left_down, false, &date)
    }

    /// Sample the frame: mouse and keys, the clock, and (`shader_fft`) one step of the shader FFT with the state's
    /// `FFTAttack` / `FFTDecay`.
    pub fn begin_frame(
        &mut self,
        audio: &AudioFrame,
        fps: f32,
        time: f64,
        (attack, decay): (f32, f32),
        shader_fft: bool,
    ) -> Md2Frame {
        let (x, y) = self.cursor();
        let down = self.mouse.left_down;
        let click = down && !self.prev_down;
        self.prev_down = down;
        if click {
            // the press is recorded where the cursor was: `m_lastMouseY = -m_mouseY + 1`
            self.last_click = [x, -y + 1.0];
        }
        let [lx, ly] = self.last_click;
        let mouse = [
            x,
            if y != -1.0 { -y + 1.0 } else { -1.0 },
            if down { lx } else { -lx },
            if click { ly } else { -ly },
        ];

        let date = self.date.unwrap_or_else(|| DateTime::from_frame_time(time));
        let total = date.total_seconds();
        let vars = self.vars((x, y), down, click, &date);
        let time_date = [
            [
                f32::from(date.hour),
                f32::from(date.minute),
                f32::from(date.second),
                total,
            ],
            [
                f32::from(date.year),
                f32::from(date.month),
                f32::from(date.day),
                f32::from(date.weekday),
            ],
        ];

        let texture = shader_fft.then(|| {
            let fft = self
                .fft
                .get_or_insert_with(|| Box::new(BeatDropShaderFft::new()));
            fft.update(fps, attack, decay);
            let mut wave = [[0.0f32; SHADER_WAVE_SAMPLES]; 2];
            for (row, src) in wave.iter_mut().zip(&audio.wave) {
                for (d, s) in row.iter_mut().zip(src) {
                    *d = s / 128.0;
                }
            }
            let mut tex = BeatDropTexture {
                spectrum: [0.0; SHADER_FFT_BINS],
                peak: [0.0; SHADER_FFT_BINS],
                wave,
            };
            tex.spectrum.copy_from_slice(fft.smoothed());
            tex.peak.copy_from_slice(fft.peak());
            Arc::new(tex)
        });

        Md2Frame {
            vars,
            mouse,
            time_date,
            texture,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn frame(i: &mut Md2Inputs, pos: Option<[f32; 2]>, down: bool) -> Md2Frame {
        i.set_mouse(MouseState {
            position: pos,
            left_down: down,
        });
        i.begin_frame(&AudioFrame::default(), 60.0, 0.0, (0.5, 0.7), false)
    }

    /// The texture layout is spelled out in two crates (the analyser and the renderer's textures); they must agree
    /// or `get_fft` / `get_wave` read the wrong texels.
    #[test]
    fn the_beatdrop_texture_layout_agrees_across_crates() {
        assert_eq!(lactea_render::BEATDROP_FFT_BINS, SHADER_FFT_BINS);
        assert_eq!(lactea_render::BEATDROP_WAVE_SAMPLES, SHADER_WAVE_SAMPLES);
    }

    /// `mousex` / `mousey` are bottom-origin, `mouseclick` lasts one frame, `_c14` carries the press position with
    /// the sign of "still held" / "clicked this frame".
    #[test]
    fn mouse_vars_and_c14() {
        let mut i = Md2Inputs::new();
        let f = frame(&mut i, None, false);
        assert_eq!(f.vars.mouse, [-1.0, -1.0, 0.0, 0.0]);
        assert_eq!(f.mouse, [-1.0, -1.0, 0.0, 0.0]);

        let f = frame(&mut i, Some([0.25, 0.25]), true);
        // the cursor is 1/4 from the left and 1/4 from the top: y is 3/4 bottom-origin
        assert_eq!(f.vars.mouse, [0.25, 0.75, 1.0, 1.0]);
        assert_eq!(f.mouse, [0.25, 0.25, 0.25, 0.25]);

        let f = frame(&mut i, Some([0.5, 0.5]), true);
        assert_eq!(
            f.vars.mouse,
            [0.5, 0.5, 1.0, 0.0],
            "no second click while held"
        );
        assert_eq!(
            f.mouse,
            [0.5, 0.5, 0.25, -0.25],
            "held: +lastX; no click: -lastY"
        );

        let f = frame(&mut i, Some([0.5, 0.5]), false);
        assert_eq!(f.vars.mouse[2], 0.0);
        assert_eq!(f.mouse[2], -0.25, "released: -lastX");
    }

    /// Unset: the time of day follows the frame clock; set: the host's values, with `totalseconds` derived.
    #[test]
    fn clock_follows_the_host_or_the_frame_time() {
        let mut i = Md2Inputs::new();
        let f = i.begin_frame(&AudioFrame::default(), 60.0, 3723.5, (0.5, 0.7), false);
        assert_eq!(f.time_date[0], [1.0, 2.0, 3.0, 3723.5]);
        assert_eq!(f.time_date[1], [0.0; 4]);

        i.set_date_time(Some(DateTime {
            year: 2026,
            month: 10,
            day: 13,
            weekday: 2,
            hour: 23,
            minute: 59,
            second: 58,
            millisecond: 250,
        }));
        let f = i.begin_frame(&AudioFrame::default(), 60.0, 0.0, (0.5, 0.7), false);
        assert_eq!(f.time_date[1], [2026.0, 10.0, 13.0, 2.0]);
        assert_eq!(
            f.vars.date[4..],
            [23.0, 59.0, 58.0, 250.0, f64::from(86_398.25f32)]
        );
    }

    /// `plugin.cpp:11731-11748`: `sampler_wave` holds `fWaveform[ch][i] / 128` for the first `NUM_WAVEFORM_SAMPLES`
    /// samples of the 576-sample capture, left in row 0 and right in row 1; the upload order is the two rows of
    /// `sampler_fft` and then the two of `sampler_wave`.
    #[test]
    fn the_wave_rows_are_the_first_480_samples_over_128() {
        let mut audio = AudioFrame::default();
        for k in 0..audio.wave[0].len() {
            audio.wave[0][k] = k as f32;
            audio.wave[1][k] = -(k as f32) / 2.0;
        }
        let mut i = Md2Inputs::new();
        let f = i.begin_frame(&audio, 60.0, 0.0, (0.5, 0.7), true);
        let t = f.texture.expect("the shader FFT is on");
        for k in 0..SHADER_WAVE_SAMPLES {
            assert_eq!(t.wave[0][k], k as f32 / 128.0, "left {k}");
            assert_eq!(t.wave[1][k], -(k as f32) / 2.0 / 128.0, "right {k}");
        }
        let texels = t.texels();
        assert_eq!(texels.len(), 2 * (SHADER_FFT_BINS + SHADER_WAVE_SAMPLES));
        let wave_at = 2 * SHADER_FFT_BINS;
        assert_eq!(texels[wave_at + 479], 479.0 / 128.0);
        assert_eq!(
            texels[wave_at + SHADER_WAVE_SAMPLES + 479],
            -479.0 / 2.0 / 128.0
        );
        // without the shader FFT there is no texture (and the analyser is not stepped)
        assert!(
            i.begin_frame(&audio, 60.0, 0.0, (0.5, 0.7), false)
                .texture
                .is_none()
        );
    }

    /// `state.cpp:1794`: the init code of a preset being loaded sees the current inputs, but the click edge belongs to
    /// the next rendered frame.
    #[test]
    fn init_code_sees_the_current_inputs_and_leaves_the_click_edge_alone() {
        let mut i = Md2Inputs::new();
        i.set_mouse(MouseState {
            position: Some([0.25, 0.25]),
            left_down: true,
        });
        i.set_ctrl_keys(CtrlKeys {
            up: true,
            ..CtrlKeys::default()
        });
        i.set_date_time(Some(DateTime {
            year: 2026,
            month: 10,
            day: 13,
            weekday: 2,
            hour: 1,
            minute: 2,
            second: 3,
            millisecond: 500,
        }));
        let v = i.vars_now(0.0);
        assert_eq!(v.mouse, [0.25, 0.75, 1.0, 0.0]);
        assert_eq!(v.ctrl, [0.0, 0.0, 0.0, 1.0]);
        assert_eq!(v.date[0], 2026.0);
        assert_eq!(v.date[7], 500.0);
        assert_eq!(v.date[8], f64::from(3723.5f32));
        let f = i.begin_frame(&AudioFrame::default(), 60.0, 0.0, (0.5, 0.7), false);
        assert_eq!(f.vars.mouse[3], 1.0, "the peek did not eat the press");
        assert_eq!(f.vars.date, v.date);
    }
}