Skip to main content

lactea_render/
noise.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//! Port of MD2's procedural noise textures (plugin.cpp `AddNoiseTex` / `AddNoiseVol`,
6//! `fCubicInterpolate`, `dwCubicInterpolate`).
7//!
8//! MD2 seeds its generator from `QueryPerformanceCounter`; here every texture is generated
9//! from the renderer's seeded [`Rng`], so the *algorithm* (value range, 8-bit packing quirks,
10//! cubic smoothing lattice) is MD2's and the *content* is deterministic per seed. To match the
11//! reference render bit-for-bit, inject its dumped noise with `Renderer::inject_noise` (feature `diagnostics`).
12//!
13//! Sizes (plugin.cpp `Init`): `noise_lq` 256/zoom 1, `noise_lq_lite` 32/1, `noise_mq` 256/4,
14//! `noise_hq` 256/8, `noisevol_lq` 32/1, `noisevol_hq` 32/4.
15
16use crate::config::CompatRules;
17use crate::rng::Rng;
18use lactea_abi::NoiseTex;
19
20/// `(size, zoom_factor, is_volume)` for each built-in noise texture.
21pub const fn noise_spec(tex: NoiseTex) -> (u32, u32, bool) {
22    match tex {
23        NoiseTex::Lq => (256, 1, false),
24        NoiseTex::LqLite => (32, 1, false),
25        NoiseTex::Mq => (256, 4, false),
26        NoiseTex::Hq => (256, 8, false),
27        NoiseTex::VolLq => (32, 1, true),
28        NoiseTex::VolHq => (32, 4, true),
29    }
30}
31
32/// All six textures in `NoiseTex::index()` order.
33pub const ALL_NOISE: [NoiseTex; 6] = [
34    NoiseTex::Lq,
35    NoiseTex::LqLite,
36    NoiseTex::Mq,
37    NoiseTex::Hq,
38    NoiseTex::VolLq,
39    NoiseTex::VolHq,
40];
41
42/// The built-in 2D textures projectM's `TextureManager` has registered before it scans any directory
43/// (`TextureManager::Preload`): a shape's `image=` of exactly one of these names samples it and never reaches the
44/// file lookup. (`idlem` / `idleheadphones` are embedded PNGs; the 3D `noisevol_*` volumes bound to a 2D sampler are
45/// undefined behaviour upstream.) `name` is compared as is: projectM's lookup is case-sensitive.
46pub fn builtin_image_noise(name: &str) -> Option<NoiseTex> {
47    Some(match name {
48        "noise_lq" => NoiseTex::Lq,
49        "noise_lq_lite" => NoiseTex::LqLite,
50        "noise_mq" => NoiseTex::Mq,
51        "noise_hq" => NoiseTex::Hq,
52        _ => return None,
53    })
54}
55
56fn cubic(y0: f32, y1: f32, y2: f32, y3: f32, t: f32) -> f32 {
57    let t2 = t * t;
58    let a0 = y3 - y2 - y0 + y1;
59    let a1 = y0 - y1 - a0;
60    let a2 = y2 - y0;
61    let a3 = y1;
62    a0 * t * t2 + a1 * t2 + a2 * t + a3
63}
64
65/// MD2 `dwCubicInterpolate`: per-byte cubic on a packed A8R8G8B8 dword, clamped, truncated.
66fn dw_cubic(y0: u32, y1: u32, y2: u32, y3: u32, t: f32) -> u32 {
67    let mut ret = 0u32;
68    let mut shift = 0;
69    for _ in 0..4 {
70        let f = cubic(
71            ((y0 >> shift) & 0xFF) as f32 / 255.0,
72            ((y1 >> shift) & 0xFF) as f32 / 255.0,
73            ((y2 >> shift) & 0xFF) as f32 / 255.0,
74            ((y3 >> shift) & 0xFF) as f32 / 255.0,
75            t,
76        );
77        let f = f.clamp(0.0, 1.0);
78        ret |= ((f * 255.0) as u32) << shift;
79        shift += 8;
80    }
81    ret
82}
83
84/// One random pixel: MD2 packs `(rand(0..RANGE-1) + RANGE/2)` per channel with plain shifts and
85/// ORs, so for RANGE=256 the 9th bit of each channel bleeds into the next-higher channel.
86/// That quirk is reproduced on purpose.
87fn random_dword(rng: &mut Rng, range: u32) -> u32 {
88    let a = rng.below(range) + range / 2;
89    let r = rng.below(range) + range / 2;
90    let g = rng.below(range) + range / 2;
91    let b = rng.below(range) + range / 2;
92    (a << 24) | (r << 16) | (g << 8) | b
93}
94
95fn fill_lines(rng: &mut Rng, dst: &mut [u32], size: usize, range: u32) {
96    for line in dst.chunks_exact_mut(size) {
97        for p in line.iter_mut() {
98            *p = random_dword(rng, range);
99        }
100        // "swap some pixels randomly, to improve 'randomness'"
101        for _ in 0..size {
102            let x1 = rng.below(size as u32) as usize;
103            let x2 = rng.below(size as u32) as usize;
104            line.swap(x1, x2);
105        }
106    }
107}
108
109fn dwords_to_rgba(d: &[u32]) -> Vec<u8> {
110    let mut out = Vec::with_capacity(d.len() * 4);
111    for &v in d {
112        // A8R8G8B8 dword -> R,G,B,A bytes
113        out.extend_from_slice(&[(v >> 16) as u8, (v >> 8) as u8, v as u8, (v >> 24) as u8]);
114    }
115    out
116}
117
118/// One smoothed sample of a `zoom`-spaced lattice: the cubic through the four lattice points around `pos` along
119/// a line of `n` samples (wrapping), where `at(i)` is the buffer index of the line's `i`-th sample.
120fn cubic_on_line(d: &[u32], at: impl Fn(usize) -> usize, pos: usize, zoom: usize, n: usize) -> u32 {
121    let base = (pos / zoom) * zoom + n;
122    let y0 = d[at((base - zoom) % n)];
123    let y1 = d[at(base % n)];
124    let y2 = d[at((base + zoom) % n)];
125    let y3 = d[at((base + zoom * 2) % n)];
126    dw_cubic(y0, y1, y2, y3, (pos % zoom) as f32 / zoom as f32)
127}
128
129/// `AddNoiseTex`: `size`x`size` RGBA8, row 0 first.
130pub fn gen_noise_tex(rng: &mut Rng, size: u32, zoom: u32) -> Vec<u8> {
131    let n = size as usize;
132    let zoom = zoom as usize;
133    let range = if zoom > 1 { 216 } else { 256 };
134    let mut d = vec![0u32; n * n];
135    fill_lines(rng, &mut d, n, range);
136
137    if zoom > 1 {
138        // across, only on the main lines
139        for y in (0..n).step_by(zoom) {
140            for x in (0..n).filter(|x| x % zoom != 0) {
141                d[y * n + x] = cubic_on_line(&d, |i| y * n + i, x, zoom, n);
142            }
143        }
144        // down, on every line
145        for x in 0..n {
146            for y in (0..n).filter(|y| y % zoom != 0) {
147                d[y * n + x] = cubic_on_line(&d, |i| i * n + x, y, zoom, n);
148            }
149        }
150    }
151    dwords_to_rgba(&d)
152}
153
154/// `AddNoiseVol`: `size`^3 RGBA8, slice (z) major, then row, then x.
155///
156/// With `rules.noisevol_row_stride` the smoothing passes step through z with a stride of `size` instead of
157/// `size * size` (projectM's `MilkdropNoise.cpp`), so they mix and overwrite unrelated rows.
158pub fn gen_noise_vol(rng: &mut Rng, size: u32, zoom: u32, rules: &CompatRules) -> Vec<u8> {
159    let n = size as usize;
160    let zoom = zoom as usize;
161    let slice = n * n;
162    let zs = if rules.noisevol_row_stride { n } else { slice };
163    let range = if zoom > 1 { 216 } else { 256 };
164    let mut d = vec![0u32; n * slice];
165    for z in 0..n {
166        fill_lines(rng, &mut d[z * slice..(z + 1) * slice], n, range);
167    }
168
169    if zoom > 1 {
170        // across X, only on main lines of main slices
171        for z in (0..n).step_by(zoom) {
172            for y in (0..n).step_by(zoom) {
173                let row = z * zs + y * n;
174                for x in (0..n).filter(|x| x % zoom != 0) {
175                    d[row + x] = cubic_on_line(&d, |i| row + i, x, zoom, n);
176                }
177            }
178        }
179        // down Y, on main slices
180        for z in (0..n).step_by(zoom) {
181            let base_z = z * zs;
182            for x in 0..n {
183                for y in (0..n).filter(|y| y % zoom != 0) {
184                    d[y * n + base_z + x] = cubic_on_line(&d, |i| i * n + base_z + x, y, zoom, n);
185                }
186            }
187        }
188        // through Z, everywhere
189        for x in 0..n {
190            for y in 0..n {
191                let base_y = y * n;
192                for z in (0..n).filter(|z| z % zoom != 0) {
193                    d[z * zs + base_y + x] = cubic_on_line(&d, |i| i * zs + base_y + x, z, zoom, n);
194                }
195            }
196        }
197    }
198    dwords_to_rgba(&d)
199}
200
201/// Generate one of the six built-in textures as RGBA8 (2D: row 0 first; 3D: z-major slices).
202pub fn generate(tex: NoiseTex, rng: &mut Rng, rules: &CompatRules) -> Vec<u8> {
203    let (size, zoom, vol) = noise_spec(tex);
204    if vol {
205        gen_noise_vol(rng, size, zoom, rules)
206    } else {
207        gen_noise_tex(rng, size, zoom)
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use crate::config::Compat;
215
216    #[test]
217    fn sizes_and_determinism() {
218        let rules = Compat::MilkDrop2.rules();
219        for tex in ALL_NOISE {
220            let (s, _, vol) = noise_spec(tex);
221            let a = generate(tex, &mut Rng::new(7), &rules);
222            let b = generate(tex, &mut Rng::new(7), &rules);
223            let expect = if vol {
224                (s * s * s * 4) as usize
225            } else {
226                (s * s * 4) as usize
227            };
228            assert_eq!(a.len(), expect, "{tex:?}");
229            assert_eq!(a, b, "{tex:?} must be deterministic");
230            assert_ne!(a, generate(tex, &mut Rng::new(8), &rules));
231        }
232    }
233
234    #[test]
235    fn smoothed_texture_is_smoother_than_raw() {
236        // mean |horizontal neighbour diff| of the red channel
237        fn rough(img: &[u8], n: usize) -> f64 {
238            let mut s = 0.0;
239            for y in 0..n {
240                for x in 0..n - 1 {
241                    s += (img[(y * n + x) * 4] as f64 - img[(y * n + x + 1) * 4] as f64).abs();
242                }
243            }
244            s / (n * (n - 1)) as f64
245        }
246        let raw = gen_noise_tex(&mut Rng::new(3), 64, 1);
247        let smooth = gen_noise_tex(&mut Rng::new(3), 64, 8);
248        assert!(rough(&smooth, 64) < rough(&raw, 64) * 0.6);
249    }
250
251    #[test]
252    fn byte_packing_quirk() {
253        // RANGE=256: channel values are 128..383, so the 9th bit bleeds into the next channel;
254        // the blue byte (no neighbour below) is a plain 8-bit value.
255        let img = gen_noise_tex(&mut Rng::new(5), 32, 1);
256        assert!(img.chunks_exact(4).any(|p| p[3] != 0));
257    }
258
259    /// `TextureManager::Preload` registers the four 2D noise textures under these exact (case-sensitive) names.
260    #[test]
261    fn shape_image_names_of_the_builtin_noise_textures() {
262        assert_eq!(builtin_image_noise("noise_lq"), Some(NoiseTex::Lq));
263        assert_eq!(builtin_image_noise("noise_lq_lite"), Some(NoiseTex::LqLite));
264        assert_eq!(builtin_image_noise("noise_mq"), Some(NoiseTex::Mq));
265        assert_eq!(builtin_image_noise("noise_hq"), Some(NoiseTex::Hq));
266        for n in [
267            "noisevol_lq",
268            "noisevol_hq",
269            "NOISE_LQ",
270            "noise",
271            "clouds",
272            "",
273        ] {
274            assert_eq!(builtin_image_noise(n), None, "{n}");
275        }
276    }
277
278    /// projectM's volume smoothing steps through z with a stride of `size` (`MilkdropNoise.cpp:186-266`), MD2 with
279    /// `size * size`; the two must produce different volumes.
280    #[test]
281    fn noisevol_row_stride_follows_projectm_formula() {
282        let (n, zoom) = (32usize, 4usize);
283        let pm = Compat::ProjectM.rules();
284        let md2 = Compat::MilkDrop2.rules();
285        assert!(pm.noisevol_row_stride && !md2.noisevol_row_stride);
286        let a = gen_noise_vol(&mut Rng::new(11), n as u32, zoom as u32, &pm);
287        let b = gen_noise_vol(&mut Rng::new(11), n as u32, zoom as u32, &md2);
288        assert_ne!(a, b);
289
290        // Cell (z=0, y=0, x=1): the X pass writes `z*size + y*size + x` from the main-line samples at x = 0, 4, 8, -4,
291        // and no later pass touches it (y = 0 and z = 0 are lattice rows), so it equals the cubic of the raw values.
292        let mut rng = Rng::new(11);
293        let mut raw = vec![0u32; n * n * n];
294        for z in 0..n {
295            fill_lines(&mut rng, &mut raw[z * n * n..(z + 1) * n * n], n, 216);
296        }
297        let at = |i: usize| raw[i];
298        let expect = dw_cubic(at(n - 4), at(0), at(4), at(8), 0.25);
299        let px = &a[4..8];
300        let want = [
301            (expect >> 16) as u8,
302            (expect >> 8) as u8,
303            expect as u8,
304            (expect >> 24) as u8,
305        ];
306        assert_eq!(px, want);
307    }
308}