Skip to main content

lactea_render/
frame.rs

1// SPDX-FileCopyrightText: 2026 Gianluca Boiano
2// SPDX-FileCopyrightText: 2005-2013 Nullsoft, Inc.
3// SPDX-License-Identifier: (MIT OR Apache-2.0) AND BSD-3-Clause
4
5//! Everything the engine hands to [`crate::Renderer::render_frame`]: per-frame values *after*
6//! per-frame equations, per-vertex results, evaluated custom waves / shapes, and the main
7//! waveform. Field docs name the MD2 variable they correspond to (state.cpp `var_pf_*`,
8//! `mysound.*`, `CShape`, `CWave`).
9
10use crate::wavegen::{NUM_FREQ_SAMPLES, NUM_WAVE_INPUT};
11
12/// Per-frame values after per-frame equations.
13#[derive(Clone, Debug)]
14pub struct FrameInput {
15    // ---- timing -------------------------------------------------------------------------
16    /// `GetTime()` (== `time` var, `_c2.x`). Frame n is exactly `n / fps`.
17    pub time: f64,
18    /// `GetFps()` (`fps`, `_c2.y`).
19    pub fps: f32,
20    /// `GetFrame()` (`frame`, `_c2.z`).
21    pub frame: u32,
22    /// `progress` (`_c2.w`): `(time - preset_start) / (next_preset_time - preset_start)`.
23    pub progress: f32,
24
25    // ---- audio levels -------------------------------------------------------------------
26    /// `mysound.imm_rel[0..3]` = `bass, mid, treb` (`_c3.xyz`).
27    pub bass: f32,
28    /// `mysound.imm_rel[1]` = `mid`.
29    pub mid: f32,
30    /// `mysound.imm_rel[2]` = `treb`.
31    pub treb: f32,
32    /// `mysound.avg_rel[0..3]` = `bass_att, mid_att, treb_att` (`_c4.xyz`).
33    pub bass_att: f32,
34    /// `mysound.avg_rel[1]` = `mid_att`.
35    pub mid_att: f32,
36    /// `mysound.avg_rel[2]` = `treb_att`.
37    pub treb_att: f32,
38    /// `mysound.imm[0..3]` (absolute, un-normalised). Only used by main-wave mode 3
39    /// (`alpha *= pow(treble_rel, 2)` where MD2 reads `mysound.imm[2]`).
40    pub imm_abs: [f32; 3],
41
42    // ---- per-frame equation outputs -------------------------------------------------------
43    /// `q1..q32` after per-frame code (`_qa.._qh`).
44    pub q: [f32; 32],
45    /// `m_rand_frame` (`rand_frame`): four `FRAND`s drawn once per frame.
46    pub rand_frame: [f32; 4],
47    /// `m_pState->m_rand_preset` (`rand_preset`): four `FRAND`s drawn once per preset.
48    pub rand_preset: [f32; 4],
49
50    /// Final UV of every warp-mesh vertex, `(gx+1)*(gy+1)` entries, row 0 first (clip y = -1); a different length
51    /// is rejected by [`Renderer::render_frame`](crate::Renderer::render_frame). Build with [`crate::warp_mesh`].
52    /// `None` = no motion (zoom 1, no warp). The UVs are also what the next frame's motion vectors read, and what
53    /// the MilkDrop 2 compat paths draw.
54    pub warp_uv: Option<Vec<[f32; 2]>>,
55    /// Per-vertex inputs of projectM's warp *vertex shader*: with `Compat::ProjectM` the renderer lets the
56    /// GPU evaluate the warp UV formula (`pow`/`sin`/`cos` are GPU approximations, not libm, so the
57    /// result is only reproducible on the GPU) from these instead of using `warp_uv`. `None` = use `warp_uv`.
58    pub warp_gpu: Option<WarpGpu>,
59
60    /// Decay and composite-pass controls.
61    pub post: PostParams,
62    /// Blur-chain parameters.
63    pub blur: BlurParams,
64    /// Outer / inner borders.
65    pub borders: Borders,
66    /// Motion-vector field.
67    pub mv: MotionVectors,
68    /// Main waveform.
69    pub main_wave: MainWave,
70    /// Custom shapes in draw order (`m_shape[0..16]`, each instance already evaluated).
71    pub shapes: Vec<ShapeInstance>,
72    /// Custom waves in draw order (`m_wave[0..16]`, per-point equations already evaluated).
73    pub waves: Vec<CustomWave>,
74    /// `var_pf_darken_center`.
75    pub darken_center: bool,
76    /// Random state of the warp / composite shader pass (override of `rand_frame` / `rand_preset`
77    /// above and of the renderer's rotation matrices); `None` = use the fields above.
78    pub warp_random: Option<PassRandom>,
79    /// Random state of the composite shader pass, see `warp_random`.
80    pub comp_random: Option<PassRandom>,
81    /// Phases of the four hue-shader corner colours (`m_fRandStart` / projectM `hueRandomOffsets`);
82    /// `None` = the renderer's per-preset values.
83    pub hue_offsets: Option<[f32; 4]>,
84    /// MilkDrop 2's preset blend (`m_bBlending`) in progress (`CompatRules::md2_preset_blend`): the fields above are
85    /// then the new state's blended values and this carries the rest, see [`Md2Blend`](crate::Md2Blend). `None` = no blend.
86    pub md2_blend: Option<crate::blend::Md2Blend>,
87}
88
89/// Decay, composite-pass controls.
90#[derive(Clone, Debug)]
91pub struct PostParams {
92    /// `var_pf_decay` (no-shader warp: multiplies the sampled image; quantised to 8 bit as MD2 does).
93    pub decay: f32,
94    /// `var_pf_gamma` (already clamped to 0..8 by the engine as MD2 does).
95    pub gamma: f32,
96    /// `var_pf_echo_zoom` (clamped to 0.001..1000).
97    pub echo_zoom: f32,
98    /// `var_pf_echo_alpha`.
99    pub echo_alpha: f32,
100    /// `(int)var_pf_echo_orient % 4`.
101    pub echo_orient: i32,
102    /// `var_pf_brighten` (non-zero == true).
103    pub brighten: bool,
104    /// `var_pf_darken`.
105    pub darken: bool,
106    /// `var_pf_solarize`.
107    pub solarize: bool,
108    /// `var_pf_invert`.
109    pub invert: bool,
110    /// `var_pf_wrap > 0.5` (`m_fSnapPoint`): address mode of the no-shader warp sampler.
111    pub wrap: bool,
112    /// Preset field `fShader` (`m_fShader.eval()`): hue-shader amount for the no-shader composite.
113    pub fshader: f32,
114}
115
116/// Blur-chain parameters (`var_pf_blur*`).
117#[derive(Clone, Debug)]
118pub struct BlurParams {
119    /// `var_pf_blur1min..blur3min`, `blur1max..blur3max` (raw; the renderer applies the "push apart" clamping).
120    pub min: [f32; 3],
121    /// `var_pf_blur1max..blur3max`.
122    pub max: [f32; 3],
123    /// `var_pf_blur1_edge_darken`.
124    pub edge_darken: f32,
125}
126
127/// Outer/inner border: `var_pf_ob_*` / `var_pf_ib_*`.
128#[derive(Clone, Debug)]
129pub struct Borders {
130    /// `var_pf_ob_size`.
131    pub ob_size: f32,
132    /// `var_pf_ob_r/g/b/a`.
133    pub ob_rgba: [f32; 4],
134    /// `var_pf_ib_size`.
135    pub ib_size: f32,
136    /// `var_pf_ib_r/g/b/a`.
137    pub ib_rgba: [f32; 4],
138}
139
140/// Motion vector field: `var_pf_mv_x/y/dx/dy/l/r/g/b/a`.
141#[derive(Clone, Debug)]
142pub struct MotionVectors {
143    /// `var_pf_mv_x`: number of columns.
144    pub x: f32,
145    /// `var_pf_mv_y`: number of rows.
146    pub y: f32,
147    /// `var_pf_mv_dx`: horizontal offset.
148    pub dx: f32,
149    /// `var_pf_mv_dy`: vertical offset.
150    pub dy: f32,
151    /// `var_pf_mv_l`: length scale.
152    pub l: f32,
153    /// `var_pf_mv_r/g/b/a`.
154    pub rgba: [f32; 4],
155}
156
157/// Main waveform (`DrawWave` inputs).
158#[derive(Clone, Debug)]
159pub struct MainWave {
160    /// `var_pf_wave_mode` (`% NUM_WAVES` is applied by the engine; modes 0..=8 are drawn).
161    pub mode: i32,
162    /// `var_pf_wave_r/g/b` and `var_pf_wave_a`.
163    pub rgba: [f32; 4],
164    /// `var_pf_wave_x` (0..1).
165    pub x: f32,
166    /// `var_pf_wave_y` (0..1; y=1 is the top of the screen).
167    pub y: f32,
168    /// `var_pf_wave_mystery`.
169    pub mystery: f32,
170    /// `var_pf_wave_usedots`.
171    pub usedots: bool,
172    /// `var_pf_wave_thick`.
173    pub thick: bool,
174    /// `var_pf_wave_additive`.
175    pub additive: bool,
176    /// `var_pf_wave_brighten` (maximize colour).
177    pub brighten: bool,
178    /// `m_fWaveScale.eval()` (applied to the waveform at the top of `RenderFrame`: `scale = fWaveScale/128`).
179    pub scale: f32,
180    /// `m_fWaveSmoothing.eval()` (IIR smoothing with `mix2 = smoothing`).
181    pub smoothing: f32,
182    /// `m_bModWaveAlphaByVolume`.
183    pub mod_alpha_by_volume: bool,
184    /// `m_fModWaveAlphaStart`.
185    pub mod_alpha_start: f32,
186    /// `m_fModWaveAlphaEnd`.
187    pub mod_alpha_end: f32,
188    /// Raw `mysound.fWave[0]` / `[1]` (left, right): 576 samples, **MD2 units** (signed, full scale
189    /// about ±128; the renderer multiplies by `scale/128` and smooths exactly like `RenderFrame`).
190    /// Same layout as `lactea_audio::AudioFrame::wave` (only the first 480 are valid but the
191    /// main-wave modes peek at up to index 511 like MD2).
192    pub wave: [[f32; NUM_WAVE_INPUT]; 2],
193    /// `mysound.fSpecLeft` / `fSpecRight` (512 bins), only read by wave mode 8
194    /// (same layout as `AudioFrame::spectrum`).
195    pub spectrum: [[f32; NUM_FREQ_SAMPLES]; 2],
196}
197
198/// One evaluated custom-shape instance (`CShape` after per-frame code for that instance).
199#[derive(Clone, Debug)]
200pub struct ShapeInstance {
201    /// `var_pf_sides` (clamped to 3..=100 by the renderer).
202    pub sides: i32,
203    /// `var_pf_x`, projectM / MD2 compute the fan centre `x * 2.0 - 1.0` in double and round to `f32` once, so
204    /// `x` / `y` stay in the equation VM's `f64` (0..1, y=1 top).
205    pub x: f64,
206    /// `var_pf_y`, see `x`.
207    pub y: f64,
208    /// `var_pf_rad`.
209    pub rad: f32,
210    /// `var_pf_ang`.
211    pub ang: f32,
212    /// Inner colour `var_pf_r/g/b/a`.
213    pub rgba: [f32; 4],
214    /// Outer colour `var_pf_r2/g2/b2/a2`.
215    pub rgba2: [f32; 4],
216    /// Border colour `var_pf_border_*`.
217    pub border_rgba: [f32; 4],
218    /// `var_pf_additive`.
219    pub additive: bool,
220    /// `var_pf_thick` (thick outline).
221    pub thick: bool,
222    /// `var_pf_textured`.
223    pub textured: bool,
224    /// `var_pf_tex_zoom`.
225    pub tex_zoom: f32,
226    /// `var_pf_tex_ang`.
227    pub tex_ang: f32,
228    /// projectM's `shapecode_N_image`: a textured shape samples this user texture (see
229    /// [`Renderer::set_user_texture`](crate::Renderer::set_user_texture)) instead of the main image.
230    /// `None` (the default, and every MilkDrop 2 shape) keeps the main-image behaviour.
231    pub image: Option<ShapeImage>,
232}
233
234/// The texture of a shape's `image=` key, already split like projectM's `ExtractTextureSettings`
235/// (`fw_` / `fc_` / `pw_` / `pc_` prefixes pick filter and wrapping; no prefix = linear + repeat).
236#[derive(Clone, Debug, PartialEq, Eq)]
237pub struct ShapeImage {
238    /// Lower-case texture name without prefix and extension (the key of `set_user_texture`).
239    pub name: String,
240    /// Bilinear (`true`) or nearest (`false`) filtering.
241    pub linear: bool,
242    /// Repeat (`true`) or clamp-to-edge (`false`) addressing.
243    pub wrap: bool,
244}
245
246impl Default for ShapeInstance {
247    /// state.cpp defaults (`m_shape[i]`).
248    fn default() -> Self {
249        Self {
250            sides: 4,
251            x: 0.5,
252            y: 0.5,
253            rad: 0.1,
254            ang: 0.0,
255            rgba: [1.0, 0.0, 0.0, 1.0],
256            rgba2: [0.0, 1.0, 0.0, 0.0],
257            border_rgba: [1.0, 1.0, 1.0, 0.1],
258            additive: false,
259            thick: false,
260            textured: false,
261            tex_zoom: 1.0,
262            tex_ang: 0.0,
263            image: None,
264        }
265    }
266}
267
268/// One evaluated custom-wave point (`var_pp_x/y/r/g/b/a` after per-point code). `x` / `y` are the VM's `f64`:
269/// projectM turns them into clip space as `static_cast<float>((x * 2.0 - 1.0) * invAspectX)`, i.e. the product is also
270/// taken in double (MD2: `(float)(x * 2 - 1) * invAspectX`, see `CompatRules::wave_point_f64_aspect`).
271#[derive(Clone, Copy, Debug)]
272pub struct WavePoint {
273    /// `var_pp_x` (0..1).
274    pub x: f64,
275    /// `var_pp_y` (0..1, y=1 top).
276    pub y: f64,
277    /// `var_pp_r/g/b/a`.
278    pub rgba: [f32; 4],
279}
280
281/// One evaluated custom wave (`CWave`). `points.len()` is the `samples` actually produced
282/// (<= 512). Spectrum / `sep` / smoothing / scaling are the engine's job (see
283/// [`crate::wavegen::custom_wave_values`]).
284#[derive(Clone, Debug, Default)]
285pub struct CustomWave {
286    /// The evaluated points.
287    pub points: Vec<WavePoint>,
288    /// `bUseDots`: draw points instead of a line.
289    pub use_dots: bool,
290    /// `bDrawThick`.
291    pub thick: bool,
292    /// `bAdditive`.
293    pub additive: bool,
294}
295
296impl Default for BlurParams {
297    fn default() -> Self {
298        Self {
299            min: [0.0; 3],
300            max: [1.0; 3],
301            edge_darken: 0.25,
302        }
303    }
304}
305
306impl Default for PostParams {
307    fn default() -> Self {
308        Self {
309            decay: 0.98,
310            gamma: 2.0,
311            echo_zoom: 2.0,
312            echo_alpha: 0.0,
313            echo_orient: 0,
314            brighten: false,
315            darken: false,
316            solarize: false,
317            invert: false,
318            wrap: true,
319            fshader: 0.0,
320        }
321    }
322}
323
324impl Default for Borders {
325    fn default() -> Self {
326        // state.cpp: ob_size 0.01, ib_size 0.01, colours ob (0,0,0,0), ib (0.25,0.25,0.25,0)
327        Self {
328            ob_size: 0.01,
329            ob_rgba: [0.0; 4],
330            ib_size: 0.01,
331            ib_rgba: [0.25, 0.25, 0.25, 0.0],
332        }
333    }
334}
335
336impl Default for MotionVectors {
337    fn default() -> Self {
338        // state.cpp defaults: mv_x 12, mv_y 9, mv_l 0.9, colour (1,1,1,1). Presets that want no
339        // field set mv_a = 0 (.milk files always carry `mv_a`).
340        Self {
341            x: 12.0,
342            y: 9.0,
343            dx: 0.0,
344            dy: 0.0,
345            l: 0.9,
346            rgba: [1.0, 1.0, 1.0, 1.0],
347        }
348    }
349}
350
351impl Default for MainWave {
352    fn default() -> Self {
353        Self {
354            mode: 0,
355            rgba: [1.0, 1.0, 1.0, 0.8],
356            x: 0.5,
357            y: 0.5,
358            mystery: 0.0,
359            usedots: false,
360            thick: false,
361            additive: false,
362            brighten: true,
363            scale: 1.0,
364            smoothing: 0.75,
365            mod_alpha_by_volume: false,
366            mod_alpha_start: 0.75,
367            mod_alpha_end: 0.95,
368            wave: [[0.0; NUM_WAVE_INPUT]; 2],
369            spectrum: [[0.0; NUM_FREQ_SAMPLES]; 2],
370        }
371    }
372}
373
374/// See [`FrameInput::warp_gpu`].
375#[derive(Clone, Debug)]
376pub struct WarpGpu {
377    /// `(gx+1)*(gy+1)` entries in the same order as `warp_uv`: the ten motion variables of each vertex
378    /// after per-pixel code.
379    pub vars: Vec<crate::warp_mesh::VertexVars>,
380    /// Per-frame warp animation terms (`WarpAnim::projectm`).
381    pub anim: crate::warp_mesh::WarpAnim,
382}
383
384/// Per-shader-pass random state. projectM gives the warp and the composite shader independent
385/// `rand_preset` / `rand_frame` / `rot_*` streams (MD2 shares one set per preset); the engine
386/// supplies them here. Any `None` falls back to the renderer's own state.
387#[derive(Clone, Debug)]
388pub struct PassRandom {
389    /// `rand_frame`: four values drawn once per frame.
390    pub rand_frame: [f32; 4],
391    /// `rand_preset`: four values drawn once per preset.
392    pub rand_preset: [f32; 4],
393    /// The 24 `rot_*` matrices exactly as uploaded (ABI layout, see [`lactea_abi::MilkUniforms::rot`]).
394    pub rot: Option<Box<[[[f32; 4]; 3]; lactea_abi::NUM_ROT]>>,
395}
396
397impl Default for FrameInput {
398    /// A default MilkDrop state at frame 0 with silent audio (decay .98, gamma 2, white wave 0).
399    fn default() -> Self {
400        Self {
401            time: 0.0,
402            fps: 60.0,
403            frame: 0,
404            progress: 0.0,
405            bass: 1.0,
406            mid: 1.0,
407            treb: 1.0,
408            bass_att: 1.0,
409            mid_att: 1.0,
410            treb_att: 1.0,
411            imm_abs: [0.0; 3],
412            q: [0.0; 32],
413            rand_frame: [0.0; 4],
414            rand_preset: [0.0; 4],
415            warp_uv: None,
416            warp_gpu: None,
417            post: PostParams::default(),
418            blur: BlurParams::default(),
419            borders: Borders::default(),
420            mv: MotionVectors::default(),
421            main_wave: MainWave::default(),
422            shapes: Vec::new(),
423            waves: Vec::new(),
424            darken_center: false,
425            warp_random: None,
426            comp_random: None,
427            hue_offsets: None,
428            md2_blend: None,
429        }
430    }
431}