Skip to main content

lactea_render/
blend.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//! MilkDrop 2's preset blend (`CState::m_bBlending`), renderer side.
6//!
7//! MD2 has no image-space cross-fade. While a blend runs the old preset's `CState` (`m_pOldState`) lives
8//! next to the new one (`m_pState`) inside **one** frame pipeline: the engine evaluates both states' equations,
9//! blends the per-frame variables and the per-vertex warp UVs, and the renderer draws
10//!
11//! * the warp pass twice (`WarpedBlit_Shaders` / `WarpedBlit_NoShaders` pass 0 = old shader, pass 1 = new shader) on
12//!   the *blended* mesh, culling mesh tiles by the per-vertex alpha `(DWORD)(mix2*255)` and alpha-blending pass 1,
13//! * custom shapes / waves of both states with `alpha_mult` (`progress` for the new state, `1 - progress` for the old),
14//! * the main waveform twice when the wave mode changed (`its = 2`) and blends the two polylines,
15//! * the composite twice with the old and the new composite shader (`ShowToUser_Shaders` / `ShowToUser_NoShaders`).
16//!
17//! This module holds the data the engine hands over ([`Md2Blend`]) and the pure logic of those passes (tile culling,
18//! the pass tables of `RenderFrame`, the composite alpha lookup, the two-wave blend). Everything is unit tested; the
19//! GPU drawing lives in `renderer.rs`.
20
21use crate::frame::{BlurParams, PassRandom};
22use crate::geom::{FCGSX, FCGSY};
23
24/// `CosineInterp` (vis_milk2 `utility.h`, not part of `third_party/md2`): `0.5 - 0.5 cos(pi x)`. Used for the blend of
25/// the per-frame variables, the wave blend and the video-echo flip.
26pub fn cosine_interp(x: f32) -> f32 {
27    0.5 - 0.5 * (x * std::f32::consts::PI).cos()
28}
29
30/// What the old state contributes to the shader passes of a blend frame (its `ApplyShaderParams(.., m_pOldState)`
31/// inputs that differ from the new state's: `q1..q32`, blur range, `rand_preset` / `rot_*`).
32#[derive(Clone, Debug)]
33pub struct Md2OldPass {
34    /// `m_pOldState->var_pf_q[0..32]` after its per-frame code.
35    pub q: [f32; 32],
36    /// The old state's own (unblended) `var_pf_blur*` (`GetSafeBlurMinMax(m_pOldState)`).
37    pub blur: BlurParams,
38    /// MilkDrop 3: the old state's `_c14` / `_qi.._qp` / shader time (`ShaderExt::fft` is ignored here).
39    pub ext: crate::ShaderExt,
40    /// Random state of the old warp / composite pass (`m_pOldState->m_rand_preset`, `m_rot_*`; `rand_frame` is the
41    /// frame's one `m_rand_frame`).
42    pub warp_random: Option<PassRandom>,
43    /// Random state of the old composite pass.
44    pub comp_random: Option<PassRandom>,
45}
46
47/// Everything the renderer needs to draw a blend frame, on top of the new state's [`crate::FrameInput`] (whose
48/// per-frame values are already the blended `m_pState->var_pf_*`).
49#[derive(Clone, Debug)]
50pub struct Md2Blend {
51    /// `m_pState->m_fBlendProgress`: linear, `0..=1` (a blend ends once it exceeds 1).
52    pub progress: f32,
53    /// `m_verts[n].Diffuse >> 24` for every warp-mesh vertex (lactea mesh order): `(DWORD)(mix2 * 255)`, `mix2` being
54    /// the clamped per-vertex blend factor (255 = new preset only).
55    pub vert_alpha: Vec<u8>,
56    /// The old state's shader-pass inputs.
57    pub old: Md2OldPass,
58    /// `Some(m_nOldWaveMode)` when the main wave is drawn twice (`its == 2`: blending and the wave mode changed).
59    pub old_wave_mode: Option<i32>,
60    /// `alpha_mult` of every entry of `FrameInput::shapes` / `FrameInput::waves` (`progress` for the new state's,
61    /// `1 - progress` for the old one's). Missing entries mean 1.
62    pub shape_alpha_mult: Vec<f32>,
63    /// Same for `FrameInput::waves`.
64    pub wave_alpha_mult: Vec<f32>,
65}
66
67/// `bIsNeeded` of the tile culling in `WarpedBlit_*` / `ShowToUser_Shaders`: with `flip_culling == false` a
68/// triangle is drawn when any vertex alpha is > 0, with `true` when any is < 255 (`nAlphaTestValue`).
69pub fn tile_needed(d: [u8; 3], flip_culling: bool) -> bool {
70    if flip_culling {
71        (d[0] & d[1] & d[2]) < 255
72    } else {
73        (d[0] | d[1] | d[2]) > 0
74    }
75}
76
77/// Which state's shader / state parameters a pass uses (`nPass`: 0 = old, 1 = new).
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum Which {
80    Old,
81    New,
82}
83
84/// One call of `WarpedBlit_*(nPass, bAlphaBlend, bFlipAlpha, bCullTiles, bFlipCulling)` /
85/// `ShowToUser_*`.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct DrawPass {
88    pub which: Which,
89    /// `*_Shaders` (user / default pixel shader) rather than `*_NoShaders` (fixed function).
90    pub shaders: bool,
91    pub alpha_blend: bool,
92    pub flip_alpha: bool,
93    pub cull_tiles: bool,
94    pub flip_culling: bool,
95}
96
97const fn pass(which: Which, shaders: bool, a: bool, fa: bool, c: bool, fc: bool) -> DrawPass {
98    DrawPass {
99        which,
100        shaders,
101        alpha_blend: a,
102        flip_alpha: fa,
103        cull_tiles: c,
104        flip_culling: fc,
105    }
106}
107
108/// The warp passes of `RenderFrame` while blending (`bOldPresetUsesWarpShader`, `bNewPresetUsesWarpShader`).
109pub fn warp_passes(old_shader: bool, new_shader: bool) -> &'static [DrawPass] {
110    use Which::{New, Old};
111    const BOTH: [DrawPass; 2] = [
112        pass(Old, true, false, false, true, true),
113        pass(New, true, true, false, true, false),
114    ];
115    const NEW_ONLY: [DrawPass; 2] = [
116        pass(Old, false, false, false, true, true),
117        pass(New, true, true, false, true, false),
118    ];
119    const OLD_ONLY: [DrawPass; 2] = [
120        pass(Old, true, false, false, true, true),
121        pass(New, false, true, false, true, false),
122    ];
123    // "all the blending just happens in the vertex UV's, so just pretend there's no blend"
124    const NONE: [DrawPass; 1] = [pass(New, false, false, false, false, false)];
125    match (old_shader, new_shader) {
126        (true, true) => &BOTH,
127        (false, true) => &NEW_ONLY,
128        (true, false) => &OLD_ONLY,
129        (false, false) => &NONE,
130    }
131}
132
133/// The composite passes of `RenderFrame` while blending (`bOldPresetUsesCompShader`, `bNewPresetUsesCompShader`);
134/// `ShowToUser_NoShaders()` always draws the whole quad and comes first.
135pub fn comp_passes(old_shader: bool, new_shader: bool) -> &'static [DrawPass] {
136    use Which::{New, Old};
137    const BOTH: [DrawPass; 2] = [
138        pass(Old, true, false, false, true, true),
139        pass(New, true, true, false, true, false),
140    ];
141    const NEW_ONLY: [DrawPass; 2] = [
142        pass(New, false, false, false, false, false),
143        pass(New, true, true, false, true, false),
144    ];
145    // "THA FUNKY REVERSAL"
146    const OLD_ONLY: [DrawPass; 2] = [
147        pass(New, false, false, false, false, false),
148        pass(Old, true, true, true, true, true),
149    ];
150    const NONE: [DrawPass; 1] = [pass(New, false, false, false, false, false)];
151    match (old_shader, new_shader) {
152        (true, true) => &BOTH,
153        (false, true) => &NEW_ONLY,
154        (true, false) => &OLD_ONLY,
155        (false, false) => &NONE,
156    }
157}
158
159/// Texture coordinates of composite-mesh vertex `(i, j)` before the half-texel shift (`SquishToCenter` of the 32x24
160/// grid, `plugin.cpp` ~2420), and the `x, y` (0..1, y up) `ShowToUser_Shaders` derives from `m_comp_verts[].x/y`
161/// (`(u - 0.5/W)*2-1`, `-((v - 0.5/H)*2-1)`, then `*0.5+0.5`).
162pub fn comp_vertex_xy01(i: usize, j: usize, w: u32, h: u32) -> (f32, f32) {
163    let div_x = 1.0 / (FCGSX - 2) as f32;
164    let div_y = 1.0 / (FCGSY - 2) as f32;
165    let j2 = j - j / (FCGSY / 2);
166    let i2 = i - i / (FCGSX / 2);
167    let v = squish_to_center(j2 as f32 * div_y, 3.0);
168    let u = squish_to_center(i2 as f32 * div_x, 3.0);
169    let half_w = 0.5 / w as f32;
170    let half_h = 0.5 / h as f32;
171    let sy = -((v - half_h) * 2.0 - 1.0);
172    let sx = (u - half_w) * 2.0 - 1.0;
173    (sx * 0.5 + 0.5, sy * 0.5 + 0.5)
174}
175
176fn squish_to_center(x: f32, exp: f32) -> f32 {
177    if x > 0.5 {
178        return (x * 2.0 - 1.0).powf(exp) * 0.5 + 0.5;
179    }
180    (1.0 - (1.0 - x * 2.0).powf(exp)) * 0.5
181}
182
183/// The alpha byte of a composite vertex while blending (`ShowToUser_Shaders`): bilinear lookup of the warp mesh's
184/// vertex alphas at `(x, y)` (0..1 over the mesh, the lookup point clamped to cells `0..grid-1`), then
185/// `D3DCOLOR_RGBA_01`'s `(int)(alpha * 255)` of the double result.
186pub fn comp_vertex_alpha(vert_alpha: &[u8], grid: [u32; 2], x01: f32, y01: f32) -> u8 {
187    let (gx, gy) = (grid[0] as i32, grid[1] as i32);
188    let mut x = x01 * (gx + 1) as f32;
189    let mut y = y01 * (gy + 1) as f32;
190    x = x.min((gx - 1) as f32).max(0.0);
191    y = y.min((gy - 1) as f32).max(0.0);
192    let nx = x as i32;
193    let ny = y as i32;
194    let dx = f64::from(x - nx as f32);
195    let dy = f64::from(y - ny as f32);
196    let at = |yy: i32, xx: i32| f64::from(vert_alpha[(yy * (gx + 1) + xx) as usize]);
197    let mut alpha = at(ny, nx) * (1.0 - dx) * (1.0 - dy)
198        + at(ny, nx + 1) * dx * (1.0 - dy)
199        + at(ny + 1, nx) * (1.0 - dx) * dy
200        + at(ny + 1, nx + 1) * dx * dy;
201    alpha /= f64::from(255.0f32);
202    ((alpha * 255.0) as i32 & 0xFF) as u8
203}
204
205/// A polyline of `DrawWave`: vertices before `SmoothWave`, and `nBreak` (`None` = -1).
206#[derive(Clone, Debug, PartialEq)]
207pub struct WaveLine {
208    pub verts: Vec<[f32; 2]>,
209    pub brk: Option<usize>,
210}
211
212/// The "blend 2 waveforms" block at the end of `DrawWave`: `new` is `v1[]` (the current wave), `old` is `v2[]`
213/// (`m_nOldWaveMode`'s wave). Returns the blended line with `nVerts1 = new.verts.len()` vertices and the (possibly
214/// moved) break. `mix` is `CosineInterp(progress)` (1 = new only).
215pub fn blend_waves(new: &WaveLine, old: &WaveLine, mix: f32) -> WaveLine {
216    let mix2 = 1.0 - mix;
217    let n1 = new.verts.len();
218    let n2 = old.verts.len();
219    // nothing to interpolate with (or into)
220    if n1 == 0 || n2 == 0 {
221        return new.clone();
222    }
223    let mut out = new.clone();
224    // "this won't yet handle the case where (nBreak1 > 0 && nBreak2 > 0)"
225    let m = (n2 as f32 - 1.0) / n1 as f32;
226    let nbreak2 = old.brk.map_or(-1, |b| b as i64);
227    for i in 0..n1 {
228        let f_idx = i as f32 * m;
229        let n_idx = f_idx as usize;
230        let t = f_idx - n_idx as f32;
231        let (x, y);
232        if n_idx as i64 == nbreak2 - 1 {
233            x = old.verts[n_idx][0];
234            y = old.verts[n_idx][1];
235            out.brk = Some(i + 1);
236        } else {
237            // MD2 reads one vertex past the end for the very last index; its `v2` array is zero-filled there
238            let b = old.verts.get(n_idx + 1).copied().unwrap_or([0.0, 0.0]);
239            x = old.verts[n_idx][0] * (1.0 - t) + b[0] * t;
240            y = old.verts[n_idx][1] * (1.0 - t) + b[1] * t;
241        }
242        out.verts[i][0] = new.verts[i][0] * mix + x * mix2;
243        out.verts[i][1] = new.verts[i][1] * mix + y * mix2;
244    }
245    out
246}
247
248/// `alpha1 = alpha1*mix + alpha2*(1-mix)` of `DrawWave`.
249pub fn blend_wave_alpha(alpha_new: f32, alpha_old: f32, mix: f32) -> f32 {
250    alpha_new * mix + alpha_old * (1.0 - mix)
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn blending_with_an_empty_wave_keeps_the_new_one() {
259        let some = WaveLine {
260            verts: vec![[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]],
261            brk: Some(1),
262        };
263        let none = WaveLine {
264            verts: vec![],
265            brk: None,
266        };
267        assert_eq!(blend_waves(&some, &none, 0.5), some);
268        assert_eq!(blend_waves(&none, &some, 0.5), none);
269        assert_eq!(blend_waves(&none, &none, 0.5), none);
270    }
271
272    #[test]
273    fn cosine_interp_endpoints_and_midpoint() {
274        assert_eq!(cosine_interp(0.0), 0.0);
275        assert!((cosine_interp(1.0) - 1.0).abs() < 1e-7);
276        assert!((cosine_interp(0.5) - 0.5).abs() < 1e-7);
277        // 0.5 - 0.5 cos(pi/4)
278        assert!(
279            (cosine_interp(0.25) - (0.5 - 0.5 * (std::f32::consts::FRAC_PI_4).cos())).abs() < 1e-6
280        );
281    }
282
283    #[test]
284    fn tile_culling_rules() {
285        // normal culling: needed when any alpha > 0
286        assert!(!tile_needed([0, 0, 0], false));
287        assert!(tile_needed([0, 0, 1], false));
288        assert!(tile_needed([255, 255, 255], false));
289        // flipped culling: needed unless every alpha is 255
290        assert!(!tile_needed([255, 255, 255], true));
291        assert!(tile_needed([255, 255, 254], true));
292        assert!(tile_needed([0, 0, 0], true));
293        // `d1 & d2 & d3 < 255` (bitwise AND): 254 & 255 & 255 = 254
294        assert!(tile_needed([254, 255, 255], true));
295    }
296
297    #[test]
298    fn warp_pass_table() {
299        use Which::{New, Old};
300        let p = warp_passes(true, true);
301        assert_eq!(p.len(), 2);
302        assert_eq!(p[0], pass(Old, true, false, false, true, true));
303        assert_eq!(p[1], pass(New, true, true, false, true, false));
304        let p = warp_passes(false, true);
305        assert_eq!(
306            (
307                p[0].shaders,
308                p[0].flip_culling,
309                p[1].shaders,
310                p[1].alpha_blend
311            ),
312            (false, true, true, true)
313        );
314        let p = warp_passes(true, false);
315        assert_eq!(
316            (
317                p[0].shaders,
318                p[1].shaders,
319                p[1].alpha_blend,
320                p[1].cull_tiles
321            ),
322            (true, false, true, true)
323        );
324        // neither: a single un-culled, un-blended fixed-function pass
325        assert_eq!(
326            warp_passes(false, false),
327            vec![pass(New, false, false, false, false, false)]
328        );
329    }
330
331    #[test]
332    fn comp_pass_table_incl_funky_reversal() {
333        use Which::{New, Old};
334        assert_eq!(
335            comp_passes(false, false),
336            vec![pass(New, false, false, false, false, false)]
337        );
338        let p = comp_passes(false, true);
339        assert_eq!(p[0], pass(New, false, false, false, false, false));
340        assert_eq!(p[1], pass(New, true, true, false, true, false));
341        // the old preset had a comp shader, the new one has not: fixed function first, then the OLD shader with flipped
342        // alpha blending (src * (1 - a) + dst * a) and flipped culling
343        let p = comp_passes(true, false);
344        assert_eq!(p[0], pass(New, false, false, false, false, false));
345        assert_eq!(p[1], pass(Old, true, true, true, true, true));
346        let p = comp_passes(true, true);
347        assert_eq!(p[0], pass(Old, true, false, false, true, true));
348        assert_eq!(p[1], pass(New, true, true, false, true, false));
349    }
350
351    #[test]
352    fn comp_vertices_cover_the_unit_square() {
353        let (x, y) = comp_vertex_xy01(0, 0, 640, 360);
354        // corner (0, 0): u = v = 0, so x01 = -0.5/W (the `-fHalfTexelW` shift of `m_comp_verts`), y01 = 1 + 0.5/H
355        assert!(
356            (x + 0.5 / 640.0).abs() < 1e-6 && (y - (1.0 + 0.5 / 360.0)).abs() < 1e-6,
357            "top-left {x} {y}"
358        );
359        let (x, y) = comp_vertex_xy01(FCGSX - 1, FCGSY - 1, 640, 360);
360        assert!(
361            (x - (1.0 - 0.5 / 640.0)).abs() < 1e-6 && (y - 0.5 / 360.0).abs() < 1e-6,
362            "bottom-right {x} {y}"
363        );
364        // symmetric about the centre (the two middle columns/rows are the duplicated centre seam)
365        let (xa, ya) = comp_vertex_xy01(FCGSX / 2 - 1, FCGSY / 2 - 1, 640, 360);
366        let (xb, yb) = comp_vertex_xy01(FCGSX / 2, FCGSY / 2, 640, 360);
367        assert!((xa - 0.5).abs() < 2e-3 && (xb - 0.5).abs() < 2e-3);
368        assert!((ya - 0.5).abs() < 2e-3 && (yb - 0.5).abs() < 2e-3);
369    }
370
371    #[test]
372    fn comp_alpha_lookup_is_a_clamped_bilinear_fetch() {
373        let grid = [4u32, 4];
374        let n = ((grid[0] + 1) * (grid[1] + 1)) as usize;
375        // constant alpha
376        let a = vec![128u8; n];
377        let v = comp_vertex_alpha(&a, grid, 0.37, 0.61);
378        assert!(v == 127 || v == 128, "{v}");
379        let full = vec![255u8; n];
380        assert!(comp_vertex_alpha(&full, grid, 0.9, 0.1) >= 254);
381        // alpha rises with the column index: reading further right gives a larger value
382        let mut ramp = vec![0u8; n];
383        for y in 0..5 {
384            for x in 0..5 {
385                ramp[y * 5 + x] = (x * 60) as u8;
386            }
387        }
388        let l = comp_vertex_alpha(&ramp, grid, 0.05, 0.5);
389        let r = comp_vertex_alpha(&ramp, grid, 0.6, 0.5);
390        assert!(l < r, "{l} {r}");
391        // hand check: (x01 = 0.4) * 5 = 2.0 -> cell 2 exactly: alpha00 = 120 (dx = 0) -> (int)(120/255*255) <= 120
392        let h = comp_vertex_alpha(&ramp, grid, 0.4, 0.5);
393        assert!(h == 119 || h == 120, "{h}");
394        // the lookup point is clamped to the cells (x01 = 1 -> cell grid-1, dx = 0 -> alpha at column 3)
395        let c = comp_vertex_alpha(&ramp, grid, 1.0, 0.5);
396        assert!(c == 179 || c == 180, "{c}");
397    }
398
399    #[test]
400    fn blend_waves_resamples_the_old_line_and_mixes() {
401        let new = WaveLine {
402            verts: vec![[0.0, 0.0]; 4],
403            brk: None,
404        };
405        let old = WaveLine {
406            verts: vec![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
407            brk: None,
408        };
409        // mix = 1: the new wave untouched; mix = 0: the old wave resampled onto 4 vertices
410        assert_eq!(blend_waves(&new, &old, 1.0).verts, new.verts);
411        let b = blend_waves(&new, &old, 0.0);
412        // m = (3-1)/4 = 0.5: indices 0, .5, 1, 1.5
413        let want = [[1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0]];
414        for (g, w) in b.verts.iter().zip(want) {
415            assert!(
416                (g[0] - w[0]).abs() < 1e-6 && (g[1] - w[1]).abs() < 1e-6,
417                "{g:?} {w:?}"
418            );
419        }
420        // halfway
421        let b = blend_waves(&new, &old, 0.5);
422        assert!((b.verts[2][0] - 1.5).abs() < 1e-6 && (b.verts[2][1] - 2.0).abs() < 1e-6);
423    }
424
425    #[test]
426    fn blend_waves_moves_the_break_to_the_old_break() {
427        let new = WaveLine {
428            verts: vec![[0.0; 2]; 8],
429            brk: Some(4),
430        };
431        let old = WaveLine {
432            verts: vec![[0.0; 2]; 6],
433            brk: Some(3),
434        };
435        let b = blend_waves(&new, &old, 0.5);
436        // m = 5/8: nIdx == nBreak2 - 1 = 2 for fIdx in [2,3): i = 4 (2.5) -> break after vertex i + 1 = 5
437        assert_eq!(b.brk, Some(5));
438        // old wave without break keeps the new break
439        let old2 = WaveLine {
440            verts: vec![[0.0; 2]; 6],
441            brk: None,
442        };
443        assert_eq!(blend_waves(&new, &old2, 0.5).brk, Some(4));
444    }
445
446    #[test]
447    fn wave_alpha_blend_is_linear_in_the_cosine_mix() {
448        assert_eq!(blend_wave_alpha(1.0, 0.0, 1.0), 1.0);
449        assert_eq!(blend_wave_alpha(1.0, 0.0, 0.0), 0.0);
450        assert!((blend_wave_alpha(0.8, 0.2, 0.25) - (0.8 * 0.25 + 0.2 * 0.75)).abs() < 1e-7);
451    }
452}