Skip to main content

lactea_render/
warp_mesh.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//! Warp-mesh geometry and MD2's per-vertex UV formula (milkdropfs.cpp
6//! `CPlugin::ComputeGridAlphaValues`, vertex setup in plugin.cpp `AllocateMilkDropDX9`).
7//!
8//! The engine evaluates per-pixel code (if any) for every grid vertex and hands the resulting
9//! variables to [`warp_vertex_uv`]; presets without per-pixel code use [`warp_mesh_uniform`].
10//! The result is the `warp_uv` grid in [`crate::FrameInput`].
11//!
12//! Conventions (identical to MD2):
13//! * grid is `(gx+1) x (gy+1)` vertices, row-major, **row 0 is stored at clip y = -1**
14//!   (bottom of the screen). UV `v = 0` is the top of the texture, so row 0 samples `v ~ 1`.
15//! * `x`/`y` are clip-space coordinates (`x*0.5+0.5` / `y*-0.5+0.5` are the preset-space `x`/`y`
16//!   seen by per-pixel code, before the aspect correction).
17
18use crate::RenderError;
19
20/// Static mesh data: vertex positions and MD2's `rad`/`ang` per-vertex attributes.
21///
22/// The grid has an even number of cells (>= 2) per axis; [`MeshGeometry::new`] enforces that, which is why the
23/// fields are private.
24#[derive(Clone, Debug)]
25pub struct MeshGeometry {
26    pub(crate) gx: u32,
27    pub(crate) gy: u32,
28    pub(crate) aspect_x: f32,
29    pub(crate) aspect_y: f32,
30    pub(crate) x: Vec<f32>,
31    pub(crate) y: Vec<f32>,
32    pub(crate) rad: Vec<f32>,
33    pub(crate) ang: Vec<f32>,
34}
35
36/// `(m_fAspectX, m_fAspectY)` from texture size (plugin.cpp).
37pub fn aspect_xy(tex_w: u32, tex_h: u32) -> (f32, f32) {
38    let ax = if tex_h > tex_w {
39        tex_w as f32 / tex_h as f32
40    } else {
41        1.0
42    };
43    let ay = if tex_w > tex_h {
44        tex_h as f32 / tex_w as f32
45    } else {
46        1.0
47    };
48    (ax, ay)
49}
50
51impl MeshGeometry {
52    /// Build the mesh of `gx x gy` cells for a `tex_w x tex_h` image.
53    ///
54    /// Fails with [`RenderError::Invalid`] unless both cell counts are even and at least 2 (MD2 builds the grid
55    /// from four quadrants).
56    pub fn new(gx: u32, gy: u32, tex_w: u32, tex_h: u32) -> Result<Self, RenderError> {
57        if gx < 2 || gy < 2 || !gx.is_multiple_of(2) || !gy.is_multiple_of(2) {
58            return Err(RenderError::Invalid(format!(
59                "mesh dimensions must be even and >= 2, got {gx}x{gy}"
60            )));
61        }
62        let (ax, ay) = aspect_xy(tex_w, tex_h);
63        let n = ((gx + 1) * (gy + 1)) as usize;
64        let mut g = MeshGeometry {
65            gx,
66            gy,
67            aspect_x: ax,
68            aspect_y: ay,
69            x: Vec::with_capacity(n),
70            y: Vec::with_capacity(n),
71            rad: Vec::with_capacity(n),
72            ang: Vec::with_capacity(n),
73        };
74        for y in 0..=gy {
75            for x in 0..=gx {
76                let vx = x as f32 / gx as f32 * 2.0 - 1.0;
77                let vy = y as f32 / gy as f32 * 2.0 - 1.0;
78                let rad = (vx * ax).hypot(vy * ay);
79                let ang = if y == gy / 2 && x == gx / 2 {
80                    0.0
81                } else {
82                    (vy * ay).atan2(vx * ax)
83                };
84                g.x.push(vx);
85                g.y.push(vy);
86                g.rad.push(rad);
87                g.ang.push(ang);
88            }
89        }
90        Ok(g)
91    }
92
93    /// Number of cells (not vertices) in x.
94    pub fn gx(&self) -> u32 {
95        self.gx
96    }
97
98    /// Number of cells (not vertices) in y.
99    pub fn gy(&self) -> u32 {
100        self.gy
101    }
102
103    /// `m_fAspectX` (computed from the texture size).
104    pub fn aspect_x(&self) -> f32 {
105        self.aspect_x
106    }
107
108    /// `m_fAspectY` (computed from the texture size).
109    pub fn aspect_y(&self) -> f32 {
110        self.aspect_y
111    }
112
113    /// Clip-space x of each vertex (`m_verts[n].x`).
114    pub fn x(&self) -> &[f32] {
115        &self.x
116    }
117
118    /// Clip-space y of each vertex (`m_verts[n].y`).
119    pub fn y(&self) -> &[f32] {
120        &self.y
121    }
122
123    /// `m_vertinfo[n].rad` of each vertex.
124    pub fn rad(&self) -> &[f32] {
125        &self.rad
126    }
127
128    /// `m_vertinfo[n].ang` of each vertex (-pi..pi as `atan2f`, centre vertex 0).
129    pub fn ang(&self) -> &[f32] {
130        &self.ang
131    }
132
133    /// Number of vertices, `(gx + 1) * (gy + 1)`.
134    pub fn vertex_count(&self) -> usize {
135        ((self.gx + 1) * (self.gy + 1)) as usize
136    }
137
138    /// Index of the vertex at column `x`, row `y` (row 0 = bottom of the screen).
139    #[inline]
140    pub fn index(&self, x: u32, y: u32) -> usize {
141        (y * (self.gx + 1) + x) as usize
142    }
143
144    /// Preset-space `x` (0 = left .. 1 = right) of vertex `n`, as per-pixel code sees it:
145    /// `m_verts[n].x*0.5*aspectX + 0.5`.
146    pub fn pv_x(&self, n: usize) -> f32 {
147        self.x[n] * 0.5 * self.aspect_x + 0.5
148    }
149    /// Preset-space `y` (0 = top .. 1 = bottom): `m_verts[n].y*-0.5*aspectY + 0.5`.
150    pub fn pv_y(&self, n: usize) -> f32 {
151        self.y[n] * -0.5 * self.aspect_y + 0.5
152    }
153
154    /// projectM's own vertex data (`PerPixelMesh::InitializeMesh`) for the vertex at column `x`, lactea
155    /// row `y` (row 0 = bottom). projectM's mesh row 0 is the *top* of the image, so its `y` is
156    /// `row_pm / gy * 2 - 1` with `row_pm = gy - y` (float rounding differs from `-self.y[n]`);
157    /// `rad = hypotf(x*ax, y*ay)`, `ang = atan2f(y*ay, x*ax)` (0 at the centre vertex).
158    /// Returns `(pos, rad, ang)`.
159    pub fn projectm_vertex(&self, x: u32, y: u32) -> ([f32; 2], f32, f32) {
160        let row_pm = self.gy - y;
161        let vx = x as f32 / self.gx as f32 * 2.0 - 1.0;
162        let vy = row_pm as f32 / self.gy as f32 * 2.0 - 1.0;
163        let rad = (vx * self.aspect_x).hypot(vy * self.aspect_y);
164        let ang = if row_pm == self.gy / 2 && x == self.gx / 2 {
165            0.0
166        } else {
167            (vy * self.aspect_y).atan2(vx * self.aspect_x)
168        };
169        ([vx, vy], rad, ang)
170    }
171}
172
173/// The ten per-vertex motion variables after (optional) per-pixel code
174/// (`pv_zoom, pv_zoomexp, pv_rot, pv_warp, pv_cx, pv_cy, pv_dx, pv_dy, pv_sx, pv_sy`).
175#[derive(Clone, Copy, Debug, PartialEq)]
176pub struct VertexVars {
177    /// `pv_zoom`
178    pub zoom: f32,
179    /// `pv_zoomexp`
180    pub zoomexp: f32,
181    /// `pv_rot`
182    pub rot: f32,
183    /// `pv_warp`
184    pub warp: f32,
185    /// `pv_cx`
186    pub cx: f32,
187    /// `pv_cy`
188    pub cy: f32,
189    /// `pv_dx`
190    pub dx: f32,
191    /// `pv_dy`
192    pub dy: f32,
193    /// `pv_sx`
194    pub sx: f32,
195    /// `pv_sy`
196    pub sy: f32,
197}
198
199impl Default for VertexVars {
200    /// MD2 defaults (state.cpp `Default`): identity motion.
201    fn default() -> Self {
202        Self {
203            zoom: 1.0,
204            zoomexp: 1.0,
205            rot: 0.0,
206            warp: 1.0,
207            cx: 0.5,
208            cy: 0.5,
209            dx: 0.0,
210            dy: 0.0,
211            sx: 1.0,
212            sy: 1.0,
213        }
214    }
215}
216
217/// Warp-animation terms computed once per frame in `ComputeGridAlphaValues`.
218#[derive(Clone, Copy, Debug, PartialEq)]
219pub struct WarpAnim {
220    /// projectM's warp vertex shader evaluates the four warp terms with a mesh `y` of the
221    /// opposite sign (its mesh row 0 is the top of the image, MD2's the bottom). `true` flips
222    /// `y` in those terms ([`WarpAnim::projectm`]).
223    pub y_flip: bool,
224    /// projectM computes `pow(zoom, ..)` in a GPU vertex shader, where a negative base gives NaN (`exp2(y*log2(x))`);
225    /// MD2 does it on the CPU (`powf`, finite). `true` in [`WarpAnim::projectm`].
226    pub gpu_pow: bool,
227    /// `fWarpTime = GetTime() * m_fWarpAnimSpeed`
228    pub warp_time: f32,
229    /// `fWarpScaleInv = 1 / m_fWarpScale`
230    pub scale_inv: f32,
231    /// `f[0..4]`
232    pub f: [f32; 4],
233}
234
235impl WarpAnim {
236    /// `time` = `GetTime()`, `warp_anim_speed` = preset `fWarpAnimSpeed`, `warp_scale` = `fWarpScale`.
237    pub fn new(time: f32, warp_anim_speed: f32, warp_scale: f32) -> Self {
238        let warp_time = time * warp_anim_speed;
239        let f = [
240            11.68 + 4.0 * (warp_time * 1.413 + 10.0).cos(),
241            8.77 + 3.0 * (warp_time * 1.113 + 7.0).cos(),
242            10.54 + 3.0 * (warp_time * 1.233 + 3.0).cos(),
243            11.49 + 4.0 * (warp_time * 0.933 + 5.0).cos(),
244        ];
245        Self {
246            y_flip: false,
247            gpu_pow: false,
248            warp_time,
249            scale_inv: 1.0 / warp_scale,
250            f,
251        }
252    }
253
254    /// Like [`WarpAnim::new`] with projectM's `y` convention in the warp terms.
255    pub fn projectm(time: f32, warp_anim_speed: f32, warp_scale: f32) -> Self {
256        Self {
257            y_flip: true,
258            gpu_pow: true,
259            ..Self::new(time, warp_anim_speed, warp_scale)
260        }
261    }
262}
263
264/// MD2's per-vertex UV (the non-blending branch of `ComputeGridAlphaValues`).
265///
266/// `texel_offset_uv` = `texel_offset / texsize` (MD2: `0.5 / m_nTexSizeX`); added last.
267/// Returns `(tu, tv)`.
268pub fn warp_vertex_uv(
269    g: &MeshGeometry,
270    n: usize,
271    v: &VertexVars,
272    anim: &WarpAnim,
273    texel_offset_uv: [f32; 2],
274) -> [f32; 2] {
275    let vx = g.x[n];
276    let vy = g.y[n];
277    // `y` as the warp terms see it (see `WarpAnim::y_flip`)
278    let wy = if anim.y_flip { -vy } else { vy };
279    let rad = g.rad[n];
280    let f = &anim.f;
281
282    let zoom2 = if anim.gpu_pow && v.zoom < 0.0 {
283        f32::NAN
284    } else {
285        v.zoom.powf(v.zoomexp.powf(rad * 2.0 - 1.0))
286    };
287    let zoom2_inv = 1.0 / zoom2;
288
289    let mut u = vx * g.aspect_x * 0.5 * zoom2_inv + 0.5;
290    let mut vv = -vy * g.aspect_y * 0.5 * zoom2_inv + 0.5;
291
292    // stretch on X, Y
293    u = (u - v.cx) / v.sx + v.cx;
294    vv = (vv - v.cy) / v.sy + v.cy;
295
296    // warping
297    let wt = anim.warp_time;
298    let si = anim.scale_inv;
299    u += v.warp * 0.0035 * (wt * 0.333 + si * (vx * f[0] - wy * f[3])).sin();
300    vv += v.warp * 0.0035 * (wt * 0.375 - si * (vx * f[2] + wy * f[1])).cos();
301    u += v.warp * 0.0035 * (wt * 0.753 - si * (vx * f[1] - wy * f[2])).cos();
302    vv += v.warp * 0.0035 * (wt * 0.825 + si * (vx * f[0] + wy * f[3])).sin();
303
304    // rotation
305    let u2 = u - v.cx;
306    let v2 = vv - v.cy;
307    let cos_rot = v.rot.cos();
308    let sin_rot = v.rot.sin();
309    u = u2 * cos_rot - v2 * sin_rot + v.cx;
310    vv = u2 * sin_rot + v2 * cos_rot + v.cy;
311
312    // translation
313    u -= v.dx;
314    vv -= v.dy;
315
316    // undo aspect ratio fix
317    u = (u - 0.5) * (1.0 / g.aspect_x) + 0.5;
318    vv = (vv - 0.5) * (1.0 / g.aspect_y) + 0.5;
319
320    // final texel-offset translation
321    u += texel_offset_uv[0];
322    vv += texel_offset_uv[1];
323    [u, vv]
324}
325
326/// The default per-vertex path (no per-pixel code): every vertex uses the same frame variables.
327pub fn warp_mesh_uniform(
328    g: &MeshGeometry,
329    v: &VertexVars,
330    anim: &WarpAnim,
331    texel_offset_uv: [f32; 2],
332) -> Vec<[f32; 2]> {
333    (0..g.vertex_count())
334        .map(|n| warp_vertex_uv(g, n, v, anim, texel_offset_uv))
335        .collect()
336}
337
338/// `texel_offset` (texels) -> UV offset for a texture size, as `RenderConfig` defines it.
339pub fn texel_offset_uv(texel_offset: [f32; 2], tex_w: u32, tex_h: u32) -> [f32; 2] {
340    [
341        texel_offset[0] / tex_w as f32,
342        texel_offset[1] / tex_h as f32,
343    ]
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    fn close(a: f32, b: f32) -> bool {
351        (a - b).abs() < 1e-5
352    }
353
354    #[test]
355    fn geometry_matches_md2_setup() {
356        let g = MeshGeometry::new(48, 36, 640, 360).unwrap();
357        assert_eq!(g.vertex_count(), 49 * 37);
358        assert!(close(g.aspect_x, 1.0));
359        assert!(close(g.aspect_y, 360.0 / 640.0));
360        // row 0 = clip y -1, x runs -1..1
361        assert!(close(g.x[0], -1.0) && close(g.y[0], -1.0));
362        assert!(close(g.x[48], 1.0) && close(g.y[48], -1.0));
363        let last = g.vertex_count() - 1;
364        assert!(close(g.x[last], 1.0) && close(g.y[last], 1.0));
365        // center vertex: rad 0, ang forced to 0
366        let c = g.index(24, 18);
367        assert!(close(g.rad[c], 0.0) && g.ang[c] == 0.0);
368        // corner rad = sqrt(ax^2 + ay^2)
369        let corner = (1.0f32 + (360.0f32 / 640.0).powi(2)).sqrt();
370        assert!(close(g.rad[0], corner));
371        // preset-space coords: row 0 is the *bottom* (pv_y = 1)
372        assert!(close(g.pv_y(0), 0.5 + 0.5 * g.aspect_y));
373        assert!(close(g.pv_x(0), 0.0));
374    }
375
376    #[test]
377    fn identity_motion_maps_to_screen_uv() {
378        // zoom=1, rot=0, warp=0, no translation: uv must equal the screen position (v=0 at top)
379        let g = MeshGeometry::new(48, 36, 640, 360).unwrap();
380        let anim = WarpAnim::new(3.0, 1.0, 1.0);
381        let v = VertexVars {
382            warp: 0.0,
383            ..Default::default()
384        };
385        let uv = warp_mesh_uniform(&g, &v, &anim, [0.0, 0.0]);
386        for n in 0..g.vertex_count() {
387            assert!(close(uv[n][0], g.x[n] * 0.5 + 0.5), "u {n}");
388            assert!(close(uv[n][1], -g.y[n] * 0.5 + 0.5), "v {n}");
389        }
390        // row 0 (bottom of screen) samples v = 1
391        assert!(close(uv[0][1], 1.0));
392    }
393
394    #[test]
395    fn zoom_rot_translate_hand_computed() {
396        let g = MeshGeometry::new(2, 2, 100, 100).unwrap(); // aspect 1,1; vertices at -1,0,1
397        let anim = WarpAnim::new(0.0, 1.0, 1.0);
398        // zoom 2 (zoomexp 1 -> constant), pure zoom: u = x*0.5/2 + 0.5
399        let v = VertexVars {
400            zoom: 2.0,
401            warp: 0.0,
402            ..Default::default()
403        };
404        let uv = warp_vertex_uv(&g, g.index(2, 0), &v, &anim, [0.0, 0.0]); // x=1,y=-1
405        assert!(close(uv[0], 0.75) && close(uv[1], 0.75));
406        // rotation by pi/2 about (0.5,0.5): vertex x=1,y=1 (screen u=1,v=0): (u2,v2)=(0.5,-0.5)
407        // -> (u2*0 - v2*1, u2*1 + v2*0) = (0.5, 0.5) -> (1.0, 1.0)
408        let v = VertexVars {
409            rot: std::f32::consts::FRAC_PI_2,
410            warp: 0.0,
411            ..Default::default()
412        };
413        let uv = warp_vertex_uv(&g, g.index(2, 2), &v, &anim, [0.0, 0.0]);
414        assert!(close(uv[0], 1.0) && close(uv[1], 1.0));
415        // translation + texel offset
416        let v = VertexVars {
417            dx: 0.1,
418            dy: -0.2,
419            warp: 0.0,
420            ..Default::default()
421        };
422        let uv = warp_vertex_uv(&g, g.index(1, 1), &v, &anim, [0.001, 0.002]);
423        assert!(close(uv[0], 0.5 - 0.1 + 0.001) && close(uv[1], 0.5 + 0.2 + 0.002));
424    }
425
426    #[test]
427    fn warp_terms_are_applied() {
428        let g = MeshGeometry::new(4, 4, 64, 64).unwrap();
429        let anim = WarpAnim::new(1.0, 1.0, 1.0);
430        assert!(close(anim.f[0], 11.68 + 4.0 * (1.413f32 + 10.0).cos()));
431        let a = warp_vertex_uv(
432            &g,
433            7,
434            &VertexVars {
435                warp: 0.0,
436                ..Default::default()
437            },
438            &anim,
439            [0.0; 2],
440        );
441        let b = warp_vertex_uv(
442            &g,
443            7,
444            &VertexVars {
445                warp: 1.0,
446                ..Default::default()
447            },
448            &anim,
449            [0.0; 2],
450        );
451        let (du, dv) = ((b[0] - a[0]).abs(), (b[1] - a[1]).abs());
452        assert!(
453            du > 0.0 && du < 0.0141 && dv < 0.0141,
454            "warp displacement bounded by 2*0.0035: {du} {dv}"
455        );
456    }
457
458    /// `projectm_vertex` is projectM's `InitializeMesh` row for the mirrored mesh row: row 0 (bottom) is
459    /// projectM's last row (`y = +1`), the centre vertex has `ang = 0`, and the float rounding is projectM's
460    /// (`y = row_pm/gy*2-1`, e.g. row 34 of 36 is 0.8888889 where `-(2/36*2-1)` is not bit-identical).
461    #[test]
462    fn projectm_vertex_follows_initialize_mesh() {
463        let g = MeshGeometry::new(48, 36, 640, 360).unwrap();
464        let (p0, rad0, _) = g.projectm_vertex(0, 0);
465        assert_eq!(p0, [-1.0, 1.0]);
466        assert!(close(rad0, (1.0f32 + (360.0f32 / 640.0).powi(2)).sqrt()));
467        let (pc, radc, angc) = g.projectm_vertex(24, 18);
468        assert_eq!((pc, radc, angc), ([0.0, 0.0], 0.0, 0.0));
469        // mesh row 2 of projectM (top) is lactea row 34; its y is exactly 2/36*2-1
470        let (p, rad, ang) = g.projectm_vertex(24, 34);
471        assert_eq!(p[1], 2.0f32 / 36.0 * 2.0 - 1.0);
472        assert_eq!(rad, (p[1] * g.aspect_y).abs());
473        assert!(ang < 0.0, "top half has negative atan2(y, x)");
474        // centre row, left half: atan2f(+0, -x) = +pi
475        assert_eq!(g.projectm_vertex(3, 18).2, std::f32::consts::PI);
476    }
477
478    #[test]
479    fn negative_zoom_is_nan_on_the_gpu_but_finite_in_md2() {
480        let g = MeshGeometry::new(4, 4, 64, 64).unwrap();
481        let v = VertexVars {
482            zoom: -0.5,
483            ..Default::default()
484        };
485        let uv = warp_vertex_uv(&g, 7, &v, &WarpAnim::projectm(1.0, 1.0, 1.0), [0.0; 2]);
486        assert!(uv[0].is_nan() && uv[1].is_nan());
487        let uv = warp_vertex_uv(&g, 7, &v, &WarpAnim::new(1.0, 1.0, 1.0), [0.0; 2]);
488        assert!(uv[0].is_finite() && uv[1].is_finite());
489        // positive zoom is unaffected
490        let v = VertexVars {
491            zoom: 1.5,
492            ..Default::default()
493        };
494        let uv = warp_vertex_uv(&g, 7, &v, &WarpAnim::projectm(1.0, 1.0, 1.0), [0.0; 2]);
495        assert!(uv[0].is_finite() && uv[1].is_finite());
496    }
497}