Skip to main content

lactea_render/
uniforms.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//! Filling of [`MilkUniforms`] exactly like `CPlugin::ApplyShaderParams` (milkdropfs.cpp),
6//! including its quirks, plus the preset-level random state (`CState::RandomizePresetVars`).
7
8use crate::blur::safe_blur_min_max;
9use crate::config::CompatRules;
10use crate::frame::{BlurParams, FrameInput, PassRandom};
11use crate::rng::Rng;
12use lactea_abi::{MilkUniforms, NUM_ROT};
13
14/// Per-preset random rotation/translation parameters (`m_rot_base`, `m_rot_speed`, `m_xlate`)
15/// for the 24 `rot_*` matrices, plus `m_rand_preset`.
16#[derive(Clone, Debug, PartialEq)]
17pub struct RotParams {
18    /// `m_rot_base`: starting angles of each matrix.
19    pub base: [[f32; 3]; NUM_ROT],
20    /// `m_rot_speed`: angular speed of each matrix.
21    pub speed: [[f32; 3]; NUM_ROT],
22    /// `m_xlate`: translation of each matrix.
23    pub xlate: [[f32; 3]; NUM_ROT],
24    /// `m_rand_preset` as drawn by `RandomizePresetVars` (the engine may also supply its own in
25    /// [`FrameInput::rand_preset`]; the uniform always uses the `FrameInput` value).
26    pub rand_preset: [f32; 4],
27    /// `m_fRandStart[0..4]` / projectM `hueRandomOffsets`: phases of the hue-shader corner colours.
28    pub hue_offsets: [f32; 4],
29}
30
31impl RotParams {
32    /// `CState::RandomizePresetVars`, with MD2's `FRAND` replaced by the seeded generator.
33    /// Call once per preset load.
34    pub fn randomize(rng: &mut Rng) -> Self {
35        let mut p = RotParams {
36            base: [[0.0; 3]; NUM_ROT],
37            speed: [[0.0; 3]; NUM_ROT],
38            xlate: [[0.0; 3]; NUM_ROT],
39            rand_preset: [rng.frand(), rng.frand(), rng.frand(), rng.frand()],
40            hue_offsets: [
41                rng.below(64841) as f32 * 0.01,
42                rng.below(53751) as f32 * 0.01,
43                rng.below(42661) as f32 * 0.01,
44                rng.below(31571) as f32 * 0.01,
45            ],
46        };
47        for k in 0..NUM_ROT {
48            let rot_mult = 0.9 * (k as f32 / 8.0).powf(3.2);
49            let xlate_mult = 1.0;
50            p.xlate[k] = [
51                (rng.frand() * 2.0 - 1.0) * xlate_mult,
52                (rng.frand() * 2.0 - 1.0) * xlate_mult,
53                (rng.frand() * 2.0 - 1.0) * xlate_mult,
54            ];
55            p.base[k] = [rng.frand() * 6.28, rng.frand() * 6.28, rng.frand() * 6.28];
56            p.speed[k] = [
57                (rng.frand() * 2.0 - 1.0) * rot_mult,
58                (rng.frand() * 2.0 - 1.0) * rot_mult,
59                (rng.frand() * 2.0 - 1.0) * rot_mult,
60            ];
61        }
62        p
63    }
64}
65
66impl Default for RotParams {
67    fn default() -> Self {
68        Self::randomize(&mut Rng::new(0))
69    }
70}
71
72type M4 = [[f32; 4]; 4];
73
74fn mat_mul(a: &M4, b: &M4) -> M4 {
75    let mut r = [[0.0f32; 4]; 4];
76    for i in 0..4 {
77        for j in 0..4 {
78            let mut s = 0.0;
79            for k in 0..4 {
80                s += a[i][k] * b[k][j];
81            }
82            r[i][j] = s;
83        }
84    }
85    r
86}
87
88fn ident() -> M4 {
89    let mut m = [[0.0; 4]; 4];
90    for i in 0..4 {
91        m[i][i] = 1.0;
92    }
93    m
94}
95
96/// `D3DXMatrixRotationX` (row-vector convention).
97fn rotation_x(a: f32) -> [[f32; 4]; 4] {
98    let (s, c) = a.sin_cos();
99    let mut m = ident();
100    m[1][1] = c;
101    m[1][2] = s;
102    m[2][1] = -s;
103    m[2][2] = c;
104    m
105}
106
107/// `D3DXMatrixRotationY`.
108fn rotation_y(a: f32) -> [[f32; 4]; 4] {
109    let (s, c) = a.sin_cos();
110    let mut m = ident();
111    m[0][0] = c;
112    m[0][2] = -s;
113    m[2][0] = s;
114    m[2][2] = c;
115    m
116}
117
118/// `D3DXMatrixRotationZ`.
119fn rotation_z(a: f32) -> [[f32; 4]; 4] {
120    let (s, c) = a.sin_cos();
121    let mut m = ident();
122    m[0][0] = c;
123    m[0][1] = s;
124    m[1][0] = -s;
125    m[1][1] = c;
126    m
127}
128
129/// `D3DXMatrixTranslation`.
130fn translation(x: f32, y: f32, z: f32) -> [[f32; 4]; 4] {
131    let mut m = ident();
132    m[3][0] = x;
133    m[3][1] = y;
134    m[3][2] = z;
135    m
136}
137
138/// `temp = Rx * T * Rz * Ry` (D3DXMatrixMultiply order used by `ApplyShaderParams`).
139pub fn rot_matrix(ax: f32, ay: f32, az: f32, t: [f32; 3]) -> [[f32; 4]; 4] {
140    let mut m = mat_mul(&rotation_x(ax), &translation(t[0], t[1], t[2]));
141    m = mat_mul(&m, &rotation_z(az));
142    mat_mul(&m, &rotation_y(ay))
143}
144
145/// Pack a D3DX 4x4 (row-major `m[row][col]`) into the ABI's `float4x3` -> `mat3x4` layout:
146/// `out[col][row] = m[row][col]` for `col < 3`.
147pub fn pack_float4x3(m: &M4) -> [[f32; 4]; 3] {
148    let mut out = [[0.0f32; 4]; 3];
149    for col in 0..3 {
150        for row in 0..4 {
151            out[col][row] = m[row][col];
152        }
153    }
154    out
155}
156
157/// `rot_*` matrices: `[0..4)` static, `[4..20)` slow/fast/very-fast/ultra-fast dynamic
158/// (`base + speed*time`), `[20..24)` random every call (`FRAND*6.28`, `FRAND` translation).
159pub(crate) fn rot_matrices(rot: &RotParams, time: f64, rng: &mut Rng) -> [[[f32; 4]; 3]; NUM_ROT] {
160    let mut out = [[[0.0f32; 4]; 3]; NUM_ROT];
161    for i in 0..20 {
162        // MD2: `m_rot_base.x + m_rot_speed.x*time` with `time` a double.
163        let ang = |k: usize| (rot.base[i][k] as f64 + rot.speed[i][k] as f64 * time) as f32;
164        let m = rot_matrix(ang(0), ang(1), ang(2), rot.xlate[i]);
165        out[i] = pack_float4x3(&m);
166    }
167    for i in 20..24 {
168        let ax = rng.frand() * 6.28;
169        let ay = rng.frand() * 6.28;
170        let az = rng.frand() * 6.28;
171        let t = [rng.frand(), rng.frand(), rng.frand()];
172        let m = rot_matrix(ax, ay, az, t);
173        out[i] = pack_float4x3(&m);
174    }
175    out
176}
177
178/// projectM uploads `glm::mat3x4(mat4)`: only the three rotation columns, so the translation
179/// (row 3 of the ABI's `float4x3`) is lost. Zero it (see [`crate::CompatRules::rot_translation_dropped`]).
180pub fn drop_rot_translation(rot: &mut [[[f32; 4]; 3]; NUM_ROT]) {
181    for m in rot.iter_mut() {
182        for col in m.iter_mut() {
183            col[3] = 0.0;
184        }
185    }
186}
187
188/// Sizes of the noise textures as `(w, h, 1/w, 1/h)` in `NoiseTex::index()` order.
189pub(crate) fn noise_texsizes() -> [[f32; 4]; 6] {
190    let mut out = [[0.0; 4]; 6];
191    for (i, t) in crate::noise::ALL_NOISE.iter().enumerate() {
192        let (s, _, _) = crate::noise::noise_spec(*t);
193        let s = s as f32;
194        out[i] = [s, s, 1.0 / s, 1.0 / s];
195    }
196    out
197}
198
199/// Everything [`fill_milk_uniforms`] reads besides the random generator.
200///
201/// * `width`, `height`: `GetWidth()/GetHeight()` (used for aspect and the mip registers).
202/// * `tex_w`, `tex_h`: `m_nTexSizeX/Y` (`_c7`).
203/// * `q`, `blur`: the `q1..q32` values and blur range of the state the pass belongs to (the frame's own, or the old
204///   preset's during a MilkDrop 2 blend).
205pub(crate) struct MilkUniformInputs<'a> {
206    pub width: u32,
207    pub height: u32,
208    pub tex_w: u32,
209    pub tex_h: u32,
210    pub frame: &'a FrameInput,
211    pub q: &'a [f32; 32],
212    pub blur: &'a BlurParams,
213    pub rot: &'a RotParams,
214    pub rules: &'a CompatRules,
215    pub pass: Option<&'a PassRandom>,
216}
217
218impl<'a> MilkUniformInputs<'a> {
219    /// Inputs for a pass of `f`'s own state: texture size = `width x height`, `q` and `blur` taken from `f`.
220    pub fn for_frame(
221        width: u32,
222        height: u32,
223        f: &'a FrameInput,
224        rot: &'a RotParams,
225        rules: &'a CompatRules,
226        pass: Option<&'a PassRandom>,
227    ) -> Self {
228        Self {
229            width,
230            height,
231            tex_w: width,
232            tex_h: height,
233            frame: f,
234            q: &f.q,
235            blur: &f.blur,
236            rot,
237            rules,
238            pass,
239        }
240    }
241}
242
243/// Fill [`MilkUniforms`] like `ApplyShaderParams`.
244///
245/// * `rot_rng`: consumed for the 4 per-call random rotation matrices.
246///
247/// MD2-vs-projectM choices come from `rules` (see [`crate::Compat`]):
248/// * `_c3.w`/`_c4.w` (`vol`, `vol_att`): projectM `(b+m+t)*0.333`; MD2 `0.3333f*(a, b, c)` — the
249///   C comma operator, i.e. `0.3333 * treb`.
250/// * `mip_y`: projectM from the height; MD2 from the *width* (typo).
251/// * `_c1`: projectM zeros; MD2 the "sd" aspect.
252/// * `_c8.._c11` use the double-precision `time` (`time*0.329f` etc.).
253pub(crate) fn fill_milk_uniforms(inp: &MilkUniformInputs<'_>, rot_rng: &mut Rng) -> MilkUniforms {
254    let MilkUniformInputs {
255        width,
256        height,
257        tex_w,
258        tex_h,
259        frame: f,
260        q,
261        blur,
262        rot,
263        rules,
264        pass,
265    } = *inp;
266    let mut u = MilkUniforms::default();
267    let w = width as f32;
268    let h = height as f32;
269
270    match pass {
271        Some(p) => {
272            u.rand_frame = p.rand_frame;
273            u.rand_preset = p.rand_preset;
274        }
275        None => {
276            u.rand_frame = f.rand_frame;
277            u.rand_preset = f.rand_preset;
278        }
279    }
280
281    // aspect (non screen-dependent mode)
282    let (mut aspect_x, mut aspect_y) = (1.0f32, 1.0f32);
283    if width > height {
284        aspect_y = h / w;
285    } else {
286        aspect_x = w / h;
287    }
288    u.c[0] = [aspect_x, aspect_y, 1.0 / aspect_x, 1.0 / aspect_y];
289    if !rules.c1_is_zero {
290        u.c[1] = [aspect_x, aspect_y, 1.0 / aspect_x, 1.0 / aspect_y];
291    }
292    // `_c2.x`: time since preset start wrapped at 10000 s (`ApplyShaderParams` / projectM `LoadVariables`).
293    let ft = f.time as f32;
294    let wrapped = ft - ((ft as f64 / 10000.0) as i32 * 10000) as f32;
295    u.c[2] = [wrapped, f.fps, f.frame as f32, f.progress];
296    let (vol, vol_att) = if rules.vol_is_comma_bug {
297        (0.3333 * f.treb, 0.3333 * f.treb_att)
298    } else {
299        (
300            (f.bass + f.mid + f.treb) * 0.333,
301            (f.bass_att + f.mid_att + f.treb_att) * 0.333,
302        )
303    };
304    u.c[3] = [f.bass, f.mid, f.treb, vol];
305    u.c[4] = [f.bass_att, f.mid_att, f.treb_att, vol_att];
306
307    let (bmin, bmax) = safe_blur_min_max(blur.min, blur.max);
308    u.c[5] = [bmax[0] - bmin[0], bmin[0], bmax[1] - bmin[1], bmin[1]];
309    u.c[6] = [bmax[2] - bmin[2], bmin[2], bmin[0], bmax[0]];
310    u.c[7] = [
311        tex_w as f32,
312        tex_h as f32,
313        1.0 / tex_w as f32,
314        1.0 / tex_h as f32,
315    ];
316
317    let t = f.time;
318    let cosv = |m: [f32; 4], o: [f32; 4]| -> [f32; 4] {
319        let mut r = [0.0; 4];
320        for k in 0..4 {
321            r[k] = 0.5 + 0.5 * ((t * m[k] as f64 + o[k] as f64) as f32).cos();
322        }
323        r
324    };
325    let sinv = |m: [f32; 4], o: [f32; 4]| -> [f32; 4] {
326        let mut r = [0.0; 4];
327        for k in 0..4 {
328            r[k] = 0.5 + 0.5 * ((t * m[k] as f64 + o[k] as f64) as f32).sin();
329        }
330        r
331    };
332    let fast_m = [0.329, 1.293, 5.070, 20.051];
333    let fast_o = [1.2, 3.9, 2.5, 5.4];
334    let slow_m = [0.0050, 0.0085, 0.0133, 0.0217];
335    let slow_o = [2.7, 5.3, 4.5, 3.8];
336    u.c[8] = cosv(fast_m, fast_o);
337    u.c[9] = sinv(fast_m, fast_o);
338    u.c[10] = cosv(slow_m, slow_o);
339    u.c[11] = sinv(slow_m, slow_o);
340
341    let mip_x = w.ln() / 2.0f32.ln();
342    let mip_y = if rules.mip_y_from_width {
343        w.ln() / 2.0f32.ln()
344    } else {
345        h.ln() / 2.0f32.ln()
346    };
347    u.c[12] = [mip_x, mip_y, 0.5 * (mip_x + mip_y), 0.0];
348    u.c[13] = [bmin[1], bmax[1], bmin[2], bmax[2]];
349
350    for i in 0..8 {
351        u.q[i] = [q[i * 4], q[i * 4 + 1], q[i * 4 + 2], q[i * 4 + 3]];
352    }
353    u.rot = match pass.and_then(|p| p.rot.as_deref()) {
354        Some(r) => *r,
355        None => {
356            let mut r = rot_matrices(rot, f.time, rot_rng);
357            if rules.rot_translation_dropped {
358                drop_rot_translation(&mut r);
359            }
360            r
361        }
362    };
363    u.texsize_noise = noise_texsizes();
364    u
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370    use crate::config::Compat;
371
372    fn close(a: f32, b: f32) -> bool {
373        (a - b).abs() < 1e-5
374    }
375
376    fn frame() -> FrameInput {
377        let mut f = FrameInput::default();
378        f.time = 12.5;
379        f.fps = 60.0;
380        f.frame = 750;
381        f.progress = 0.25;
382        f.bass = 1.1;
383        f.mid = 0.9;
384        f.treb = 0.6;
385        f.bass_att = 1.2;
386        f.mid_att = 1.0;
387        f.treb_att = 0.3;
388        f.blur.min = [0.1, 0.2, 0.3];
389        f.blur.max = [0.9, 0.8, 0.7];
390        for i in 0..32 {
391            f.q[i] = i as f32 + 1.0;
392        }
393        f.rand_frame = [0.1, 0.2, 0.3, 0.4];
394        f.rand_preset = [0.5, 0.6, 0.7, 0.8];
395        f
396    }
397
398    #[test]
399    fn registers_match_hand_computation() {
400        let f = frame();
401        let rot = RotParams::default();
402        let u = fill_milk_uniforms(
403            &MilkUniformInputs::for_frame(640, 360, &f, &rot, &Compat::MilkDrop2.rules(), None),
404            &mut Rng::new(1),
405        );
406        // aspect (wide): (1, 0.5625, 1, 1/0.5625)
407        assert_eq!(u.c[0], [1.0, 0.5625, 1.0, 1.0 / 0.5625]);
408        assert_eq!(u.c[1], u.c[0]); // MD2 compat: sd aspect
409        assert_eq!(u.c[2], [12.5, 60.0, 750.0, 0.25]);
410        // vol is the comma-operator quirk: 0.3333 * treb, NOT the average
411        assert_eq!(u.c[3][..3], [1.1, 0.9, 0.6]);
412        assert!(close(u.c[3][3], 0.3333 * 0.6));
413        assert!(close(u.c[4][3], 0.3333 * 0.3));
414        // blur: window sizes progress: level2 clamped into level1 [0.1,0.9] -> [0.2,0.8]; level3 -> [0.3,0.7]
415        assert!(
416            close(u.c[5][0], 0.8)
417                && close(u.c[5][1], 0.1)
418                && close(u.c[5][2], 0.6)
419                && close(u.c[5][3], 0.2)
420        );
421        assert!(
422            close(u.c[6][0], 0.4)
423                && close(u.c[6][1], 0.3)
424                && close(u.c[6][2], 0.1)
425                && close(u.c[6][3], 0.9)
426        );
427        assert!(
428            close(u.c[13][0], 0.2)
429                && close(u.c[13][1], 0.8)
430                && close(u.c[13][2], 0.3)
431                && close(u.c[13][3], 0.7)
432        );
433        assert_eq!(u.c[7], [640.0, 360.0, 1.0 / 640.0, 1.0 / 360.0]);
434        // roam
435        let c = 0.5 + 0.5 * ((12.5f64 * 0.329f32 as f64 + 1.2f32 as f64) as f32).cos();
436        assert!(close(u.c[8][0], c));
437        let s = 0.5 + 0.5 * ((12.5f64 * 20.051f32 as f64 + 5.4f32 as f64) as f32).sin();
438        assert!(close(u.c[9][3], s));
439        let sc = 0.5 + 0.5 * ((12.5f64 * 0.0085f32 as f64 + 5.3f32 as f64) as f32).cos();
440        assert!(close(u.c[10][1], sc));
441        // mip: both from the width
442        let m = 640f32.ln() / 2f32.ln();
443        assert!(close(u.c[12][0], m) && close(u.c[12][1], m) && close(u.c[12][2], m));
444        // projectM compat: vol = (b+m+t)*0.333, mip_y from height, _c1 zero
445        let up = fill_milk_uniforms(
446            &MilkUniformInputs::for_frame(640, 360, &f, &rot, &Compat::ProjectM.rules(), None),
447            &mut Rng::new(1),
448        );
449        assert!(close(up.c[3][3], (1.1 + 0.9 + 0.6) * 0.333));
450        assert!(close(up.c[4][3], (1.2 + 1.0 + 0.3) * 0.333));
451        assert!(close(up.c[12][1], 360f32.ln() / 2f32.ln()));
452        assert_eq!(up.c[1], [0.0; 4]);
453        // q packing
454        assert_eq!(u.q[0], [1.0, 2.0, 3.0, 4.0]);
455        assert_eq!(u.q[7], [29.0, 30.0, 31.0, 32.0]);
456        assert_eq!(u.rand_frame, [0.1, 0.2, 0.3, 0.4]);
457        assert_eq!(u.rand_preset, [0.5, 0.6, 0.7, 0.8]);
458        // noise sizes
459        assert_eq!(u.texsize_noise[0], [256.0, 256.0, 1.0 / 256.0, 1.0 / 256.0]);
460        assert_eq!(u.texsize_noise[1][0], 32.0);
461        assert_eq!(u.texsize_noise[5][0], 32.0);
462    }
463
464    #[test]
465    fn portrait_aspect() {
466        let f = frame();
467        let u = fill_milk_uniforms(
468            &MilkUniformInputs::for_frame(
469                360,
470                640,
471                &f,
472                &RotParams::default(),
473                &Compat::MilkDrop2.rules(),
474                None,
475            ),
476            &mut Rng::new(1),
477        );
478        assert_eq!(u.c[0], [0.5625, 1.0, 1.0 / 0.5625, 1.0]);
479    }
480
481    #[test]
482    fn rot_matrices_static_dynamic_random() {
483        let rot = RotParams::randomize(&mut Rng::new(42));
484        // rot_s1 has speed exactly 0; rot_s2..4 drift slowly (0.9*(k/8)^3.2 rad/s max)
485        let a = rot_matrices(&rot, 0.0, &mut Rng::new(1));
486        let b = rot_matrices(&rot, 100.0, &mut Rng::new(1));
487        assert_eq!(a[0], b[0], "rot_s1 is static");
488        assert_ne!(a[2], b[2], "rot_s3 drifts slowly (0.9*(2/8)^3.2 rad/s max)");
489        // dynamic ones change
490        assert_ne!(a[8], b[8]);
491        // random ones depend on the rng, not time
492        let c = rot_matrices(&rot, 0.0, &mut Rng::new(2));
493        assert_ne!(a[20], c[20]);
494        assert_eq!(a[19], c[19]);
495    }
496
497    #[test]
498    fn rot_matrix_layout_matches_d3dx() {
499        // pure Z rotation by 90deg with translation: D3DX row-vector math:
500        // v=(1,0,0,1) * (Rx*T*Rz*Ry). Rx=I. T moves by t. Rz rotates (x,y): (x,y)->(x*c - y*s, x*s + y*c)
501        let m = rot_matrix(0.0, 0.0, std::f32::consts::FRAC_PI_2, [0.0, 0.0, 0.0]);
502        let p = pack_float4x3(&m);
503        // WGSL `v * M` for mat3x4: result_i = dot(v, column_i)
504        let v = [1.0f32, 0.0, 0.0, 1.0];
505        let res: Vec<f32> = (0..3)
506            .map(|c| (0..4).map(|k| v[k] * p[c][k]).sum())
507            .collect();
508        assert!(close(res[0], 0.0) && close(res[1], 1.0) && close(res[2], 0.0));
509        // translation lives in row 3 -> last element of each column
510        let m = rot_matrix(0.0, 0.0, 0.0, [0.25, 0.5, 0.75]);
511        let p = pack_float4x3(&m);
512        assert_eq!([p[0][3], p[1][3], p[2][3]], [0.25, 0.5, 0.75]);
513    }
514
515    #[test]
516    fn randomize_matches_md2_distribution() {
517        let r = RotParams::randomize(&mut Rng::new(9));
518        // rot_mult = 0.9*(k/8)^3.2: exactly zero only for k = 0, tiny for the other "static" ones
519        assert_eq!(r.speed[0], [0.0; 3]);
520        for k in 1..4 {
521            let lim = 0.9 * (k as f32 / 8.0).powf(3.2) + 1e-6;
522            assert!(
523                r.speed[k].iter().all(|s| s.abs() <= lim),
524                "static rotation {k} speed bound"
525            );
526        }
527        for k in 0..NUM_ROT {
528            for c in 0..3 {
529                assert!(r.base[k][c] >= 0.0 && r.base[k][c] < 6.28);
530                assert!(r.xlate[k][c].abs() <= 1.0);
531                assert!(r.speed[k][c].abs() <= 0.9 * (k as f32 / 8.0).powf(3.2) + 1e-6);
532            }
533        }
534    }
535}