Skip to main content

lactea_render/
config.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//! Renderer configuration and the MD2-vs-projectM compatibility switch.
6
7use lactea_abi::{RunConfig, ShaderInterface};
8
9/// Which reference behaviour the renderer follows where MilkDrop 2 (`third_party/md2`) and
10/// projectM differ. Default: projectM.
11///
12/// Every divergence handled by this switch (see [`Compat::rules`]):
13///
14/// | item | `ProjectM` | `MilkDrop2` |
15/// |---|---|---|
16/// | `_c3.w`/`_c4.w` (`vol`, `vol_att`) | `(bass+mid+treb)*0.333` | `0.3333*treb` (C comma-operator bug) |
17/// | `_c12.y` (`mip_y`) | from height | from width (typo) |
18/// | `_c1` (aspect "sd") | zeros | `aspect` for the sd variant |
19/// | no-shader warp decay | `min(decay,1)` as float, no 8-bit rounding | `(int)(decay*255)&0xFF` (truncated, wraps) |
20/// | vertex colours (waves, shapes, borders, mv, echo) | float, modulo-wrapped like `& 0xFF` when out of 0..1 | 8-bit truncated |
21/// | no-shader comp hue tint | always applied | only if `fShader > 0.001`, blended by `fShader` |
22/// | thick / dots main-wave passes | whenever `thick \|\| dots` | additionally needs `texsize >= 512` |
23/// | custom-shape thick outline offset | `1/W` (half a pixel) | `2/W` (one pixel) |
24/// | motion vectors: first frame | skipped | drawn |
25/// | motion vectors: min length / lookup | 1.25 px, geometrically correct row | 1 px, mirrored-row lookup (`ReversePropagatePoint`) |
26/// | comp-shader `sampler_main` | current frame (after waves/borders) | previous frame (`m_lpVS[0]` in `ApplyShaderParams`) |
27/// | warp mesh `ang` seam | no fix (interpolates across the +-pi seam row) | `ang` patched to -pi / +pi per half |
28/// | comp mesh UV | `uv + 0.5/size` (half-texel) | exact (the D3D9 half-pixel compensation nets to 0) |
29/// | warp-shader `VsOut.diffuse` | `(decay, decay, decay, 1)` | `(1, 1, 1, 1)` |
30/// | no-shader composite hue-tint corners | `shade[0..1]` at the *top* corners (projectM draws the quad in its flipped frame) | `shade[0..1]` at the bottom corners |
31/// | blur pass 0 vertical `+1 texel` bias | `-1` (projectM samples the upside-down stored source with `uv.y` flipped, so the bias goes up) | `+1` (down) |
32/// | warp mesh cell diagonal | bottom-left to top-right in image space (projectM's mesh row 0 is the top) | top-left to bottom-right |
33/// | no-shader composite / filter quad diagonal | `TL,TR,BL,BR` strip: split along top-right to bottom-left (hue-tint colours interpolate differently) | triangles `(0,1,2),(2,1,3)` of `geom::echo_quad` (bottom-right to top-left) |
34/// | no-shader echo / gamma quad size | scaled by `VideoEcho`'s `aspectMultX/Y` (x stretched by `H/W` on portrait targets, UVs unchanged) | `1 + 1/size` |
35/// | no-shader gamma pass count | `(int)(gamma - 0.0001) + 1` | `(int)(gamma - 0.001) + 1` |
36/// | lines / points | GL rasterisation rules emulated exactly ([`StrokeRaster`]) | D3D9 thin quads |
37/// | custom-wave dots | the 2n-1 vertices of `SmoothWave`, always 1 px (`gl_PointSize` ignored) | the n source points, `1 + thick` px |
38/// | custom-wave thick offset | `1/W` ndc in x *and* y (half a pixel in x, `H/2W` px in y) | `2/W`, `2/H` (one pixel) |
39/// | `rot_*` uniforms | translation row dropped (`glm::mat3x4` of a `mat4`: only the 3 rotation columns are uploaded) | `float4x3` incl. the translation row |
40/// | first frame of a preset whose shaders sample blur (the frame that allocates the blur textures) | shapes, waves, main wave, darken centre, borders lost (`BlurTexture::Update` restores FBO 0) | drawn |
41/// | custom wave / shape slots that run | 4 each (`CustomWaveformCount`, `CustomShapeCount`; slots 4..15 are ignored) | 16 each |
42/// | warp shader `sampler_main` (first `main` sampler in name order) | filter linear, address from `bTexWrap` (`WarpedBlit` rebinds unit 0) | whatever the shader's sampler prefix says |
43/// | preset change (`Transition::Soft`) | image-space cross-fade of two independently rendered presets by one of six built-in transition shaders (`md2_preset_blend = false`) | MD2's own blend inside one frame pipeline: both states' equations run, per-vertex UVs blended by a random pattern, old/new shaders drawn as alpha-tiled passes (`md2_preset_blend = true`) |
44///
45/// Not switchable (identical in both): blur chain, blur source (previous frame image), blur
46/// min/max "push apart" typo.
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
48pub enum Compat {
49    /// projectM's behaviour (the default).
50    #[default]
51    ProjectM,
52    /// MilkDrop 2's behaviour (Direct3D 9 semantics).
53    MilkDrop2,
54}
55
56/// The individual behaviours selected by a [`Compat`] value (see the table there for the
57/// projectM / MilkDrop 2 values of each).
58#[derive(Clone, Copy, Debug, PartialEq)]
59#[non_exhaustive]
60pub struct CompatRules {
61    /// `vol` / `vol_att` follow MD2's comma-operator bug (`0.3333*treb`).
62    pub vol_is_comma_bug: bool,
63    /// `_c12.y` (`mip_y`) is derived from the width instead of the height (MD2 typo).
64    pub mip_y_from_width: bool,
65    /// `_c1` (aspect "sd") is all zeros.
66    pub c1_is_zero: bool,
67    /// The no-shader warp decay is truncated to 8 bits and wraps, `(int)(decay*255)&0xFF`.
68    pub decay_8bit: bool,
69    /// Vertex colours are 8-bit truncated; otherwise float, modulo-wrapped like `& 0xFF` when outside 0..1.
70    pub quantize_vertex_colors: bool,
71    /// The no-shader composite hue tint is always applied; otherwise only if `fShader > 0.001`, blended by `fShader`.
72    pub hue_tint_always: bool,
73    /// Thick / dots main-wave passes additionally need a texture size of at least 512.
74    pub thick_needs_512: bool,
75    /// Main waveform geometry/alpha follow projectM `Waveforms/*.cpp` (`wavegen::main_wave_geometry_projectm`)
76    /// instead of the MD2 `DrawWave` port (`wavegen::main_wave_geometry`).
77    pub pm_waveforms: bool,
78    /// The custom-shape thick outline offset is one pixel (`2/W`) instead of half a pixel (`1/W`).
79    pub shape_thick_full_pixel: bool,
80    /// Motion vectors are skipped on the first frame.
81    pub mv_skip_first_frame: bool,
82    /// Minimum motion-vector length in pixels.
83    pub mv_min_len_px: f32,
84    /// Motion-vector lookup uses MD2's mirrored row (`ReversePropagatePoint`).
85    pub mv_mirrored_lookup: bool,
86    /// The composite shader's `sampler_main` reads the previous frame instead of the current one.
87    pub comp_reads_previous: bool,
88    /// The warp mesh `ang` seam is patched to -pi / +pi per half instead of interpolating across the seam row.
89    pub ang_seam_fix: bool,
90    /// The composite mesh UV gets a half-texel offset (`uv + 0.5/size`).
91    pub comp_uv_half_texel: bool,
92    /// A warp shader's `VsOut.diffuse` is `(decay, decay, decay, 1)` instead of `(1, 1, 1, 1)`.
93    pub shader_warp_diffuse_is_decay: bool,
94    /// The translation row of the `rot_*` uniforms is dropped (`glm::mat3x4` of a `mat4`).
95    pub rot_translation_dropped: bool,
96    /// The no-shader composite hue-tint colours `shade[0..1]` sit at the top corners instead of the bottom ones.
97    pub shade_top_first: bool,
98    /// Blur pass 0 samples an upside-down source, so its vertical `+1 texel` bias is `-1`.
99    pub blur_src_flipped: bool,
100    /// Warp mesh cells are split bottom-left to top-right in image space instead of top-left to bottom-right.
101    pub warp_diag_flipped: bool,
102    /// The no-shader composite / filter quad is split top-right to bottom-left instead of bottom-right to top-left.
103    pub echo_diag_flipped: bool,
104    /// projectM stretches the echo / gamma quad by `aspectMultX/Y` of `VideoEcho::Draw` (`geom::echo_aspect_mult`):
105    /// identity for landscape targets, a horizontal `H/W` magnification of the centre for portrait ones. MD2 draws the
106    /// plain `1 + 1/size` quad.
107    pub echo_quad_aspect: bool,
108    /// Epsilon of the gamma pass count of the no-echo composite, `(int)(gamma - eps) + 1` passes: projectM
109    /// (`VideoEcho::DrawGammaAdjustment`) `0.0001`, MD2 (`ShowToUser_NoShaders`) `0.001`.
110    pub gamma_pass_eps: f32,
111    /// Lines and points follow OpenGL rasterisation rules (see [`StrokeRaster`]) instead of D3D9 thin quads.
112    pub gl_strokes: bool,
113    /// Custom-wave dots use the `2n-1` vertices of `SmoothWave`; otherwise the `n` source points.
114    pub wave_dots_smoothed: bool,
115    /// Point sizes (`1 + thick` px) are honoured; otherwise points are always 1 px (`gl_PointSize` ignored).
116    pub point_size_honored: bool,
117    /// The custom-wave thick offset is `1/W` ndc in x *and* y; otherwise `2/W`, `2/H` (one pixel).
118    pub wave_thick_ndc_inc: bool,
119    /// Custom-wave point positions: projectM `static_cast<float>((x * 2.0 - 1.0) * invAspectX)` (the product is taken in
120    /// double, one rounding to `f32`); MD2 `(float)(x * 2 - 1) * m_fInvAspectX` (rounded to `f32` before the product).
121    pub wave_point_f64_aspect: bool,
122    /// projectM textures have a single level (no `glGenerateMipmap`, samplers use the plain `GL_LINEAR` /
123    /// `GL_NEAREST` min filter), so `tex2D` never blends mip levels and `tex2Dlod` / `tex2Dbias` read level 0.
124    /// MD2 uses D3D9 textures with a mip chain (trilinear).
125    pub no_mipmaps: bool,
126    /// projectM evaluates the warp UV formula (`pow`, `sin`, `cos`, multiply-adds) in its *vertex shader*, so the
127    /// result carries the GPU's approximations and fusion; MD2 does it on the CPU (`D3DX`/libm floats).
128    /// With this rule the renderer runs the warp vertex shader on the per-vertex inputs of `FrameInput::warp_gpu`.
129    pub warp_uv_on_gpu: bool,
130    /// projectM: the internal images are RGBA; `main` starts at alpha 0, the no-shader warp keeps `tex.a`,
131    /// shaders write 1, overlays blend alpha with the colour factors and textured fills multiply by `tex.a`.
132    /// MD2 (X8R8G8B8) has no alpha: sampled alpha is 1 and nothing is written.
133    pub main_alpha: bool,
134    /// projectM binds the `GL_NEAREST` flip texture (set by `TextureAttachment`) for textured shapes that sample the
135    /// main image; MD2 samples it bilinearly.
136    pub shape_main_nearest: bool,
137    /// projectM: on the frame that (re)allocates the blur textures (first frame after preset load / resize) of a preset
138    /// whose shaders sample blur, `BlurTexture::Update` restores the wrong framebuffer, so shapes, waves, main wave,
139    /// darken-centre and borders of that frame are drawn to the default framebuffer and lost. MD2 draws them.
140    pub blur_alloc_drops_overlays: bool,
141    /// projectM draws in GL window space (y up), lactea's targets are y down (wgpu / D3D9): both use the top-left
142    /// rule, so a pixel centre lying exactly on a *horizontal* triangle edge goes to the polygon below the edge in
143    /// wgpu and to the polygon above it in projectM. With this rule such triangle fills (borders whose
144    /// `size * H / 2` is a half integer) are nudged by one sub-pixel step (`geom::gl_fill_ties`). MD2 (D3D9) has
145    /// the wgpu rule.
146    pub gl_fill_ties: bool,
147    /// Borders are one 8-vertex / 8-triangle mesh in projectM (`Border.cpp`, mirrored vertically by its y-flipping
148    /// projection), four rotated quads in MD2. Identical for sane sizes, different when `ob + ib > 1` or a size is
149    /// negative (self-overlapping triangles).
150    pub pm_border_mesh: bool,
151    /// Number of custom wave / custom shape slots that run: projectM `CustomWaveformCount` /
152    /// `CustomShapeCount` = 4 (the keys `wavecode_4..15` / `shapecode_4..15` are never read), MD2 / `MAX_CUSTOM_*` = 16.
153    pub custom_slots: usize,
154    /// projectM's `PerPixelMesh::WarpedBlit` binds its own sampler (`GL_LINEAR`, `GL_REPEAT` / `GL_CLAMP_TO_EDGE` from the
155    /// per-frame `wrap` variable, i.e. `bTexWrap`) on texture unit 0 *after* the warp shader loaded its samplers, which
156    /// replaces the sampler of the first `main` descriptor (`std::set` order of the sampler names, `main` always
157    /// present): a warp shader's `sampler_main` follows `wrap`, not the `fw_`/`fc_`/`pw_`/`pc_` prefix. MD2 uses the
158    /// sampler declared in the shader.
159    pub warp_main_sampler_from_wrap: bool,
160    /// Soft cuts follow MilkDrop 2's `m_bBlending` (`state.cpp` `StartBlendFrom`, `milkdropfs.cpp` `RenderFrame`): the old
161    /// preset's state stays alive next to the new one inside a single frame pipeline (one renderer, old shaders in
162    /// `m_OldShaders`). projectM instead renders both presets to their own images and blends the finished images with
163    /// one of six transition shaders ([`TransitionKind`](crate::TransitionKind)).
164    pub md2_preset_blend: bool,
165}
166
167impl Compat {
168    /// The behaviours of this compatibility mode.
169    pub fn rules(self) -> CompatRules {
170        match self {
171            Compat::ProjectM => CompatRules {
172                vol_is_comma_bug: false,
173                mip_y_from_width: false,
174                c1_is_zero: true,
175                decay_8bit: false,
176                quantize_vertex_colors: false,
177                hue_tint_always: true,
178                thick_needs_512: false,
179                pm_waveforms: true,
180                shape_thick_full_pixel: false,
181                mv_skip_first_frame: true,
182                mv_min_len_px: 1.25,
183                mv_mirrored_lookup: false,
184                comp_reads_previous: false,
185                ang_seam_fix: false,
186                comp_uv_half_texel: true,
187                shader_warp_diffuse_is_decay: true,
188                rot_translation_dropped: true,
189                shade_top_first: true,
190                blur_src_flipped: true,
191                warp_diag_flipped: true,
192                echo_diag_flipped: true,
193                echo_quad_aspect: true,
194                gamma_pass_eps: 0.0001,
195                gl_strokes: true,
196                wave_dots_smoothed: true,
197                point_size_honored: false,
198                wave_thick_ndc_inc: true,
199                wave_point_f64_aspect: true,
200                no_mipmaps: true,
201                warp_uv_on_gpu: true,
202                main_alpha: true,
203                shape_main_nearest: true,
204                blur_alloc_drops_overlays: true,
205                gl_fill_ties: true,
206                pm_border_mesh: true,
207                custom_slots: 4,
208                warp_main_sampler_from_wrap: true,
209                md2_preset_blend: false,
210            },
211            Compat::MilkDrop2 => CompatRules {
212                vol_is_comma_bug: true,
213                mip_y_from_width: true,
214                c1_is_zero: false,
215                decay_8bit: true,
216                quantize_vertex_colors: true,
217                hue_tint_always: false,
218                thick_needs_512: true,
219                pm_waveforms: false,
220                shape_thick_full_pixel: true,
221                mv_skip_first_frame: false,
222                mv_min_len_px: 1.0,
223                mv_mirrored_lookup: true,
224                comp_reads_previous: true,
225                ang_seam_fix: true,
226                comp_uv_half_texel: false,
227                shader_warp_diffuse_is_decay: false,
228                rot_translation_dropped: false,
229                shade_top_first: false,
230                blur_src_flipped: false,
231                warp_diag_flipped: false,
232                echo_diag_flipped: false,
233                echo_quad_aspect: false,
234                gamma_pass_eps: 0.001,
235                gl_strokes: false,
236                wave_dots_smoothed: false,
237                point_size_honored: true,
238                wave_thick_ndc_inc: false,
239                wave_point_f64_aspect: false,
240                no_mipmaps: false,
241                warp_uv_on_gpu: false,
242                main_alpha: false,
243                shape_main_nearest: false,
244                blur_alloc_drops_overlays: false,
245                gl_fill_ties: false,
246                pm_border_mesh: false,
247                custom_slots: 16,
248                warp_main_sampler_from_wrap: false,
249                md2_preset_blend: true,
250            },
251        }
252    }
253}
254
255/// How 1-pixel lines and points (custom/main waves, shape outlines, motion vectors) are rasterised.
256///
257/// projectM draws `GL_LINES`/`GL_LINE_STRIP`/`GL_LINE_LOOP`/`GL_POINTS`, non-antialiased (`GL_LINE_SMOOTH` has no
258/// effect on Mesa). The GPU's own line rule (diamond exit) decides every stroke pixel, so the choice below only
259/// matters for pixel-exactness.
260#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
261#[non_exhaustive]
262pub enum StrokeRaster {
263    /// `wgpu` `LineList` / `PointList` primitives (1 px): fastest, but the rule is the driver's and can differ
264    /// from projectM's GL rules for many stroke pixels.
265    Native,
266    /// Exact CPU emulation of projectM's GL rules (strip / diamond exit / point floor), every lit pixel
267    /// drawn as a 1-px point at its centre: identical on every GPU.
268    #[default]
269    Emulated,
270    /// Thin quads (one pixel wide band covering the major axis extent): the D3D9 look MilkDrop 2 had.
271    /// `Compat::MilkDrop2` always draws strokes this way, whatever the configured mode.
272    Quads,
273}
274
275/// Renderer construction parameters.
276#[derive(Clone, Debug)]
277pub struct RenderConfig {
278    /// Internal image width (`m_nTexSizeX`; MD2 "auto exact" = window size), also the output width.
279    pub width: u32,
280    /// Internal image height, also the output height.
281    pub height: u32,
282    /// Warp mesh cells `[gx, gy]` (both even, e.g. `[48, 36]`).
283    pub mesh: [u32; 2],
284    /// In texels; added to warp UVs (`MD2: 0.5`, projectM/modern APIs: `0`).
285    pub texel_offset: [f32; 2],
286    /// Format of the host target view passed to `render_frame`. `*Srgb` formats are compensated so
287    /// stored bytes equal a non-sRGB render.
288    pub output_format: wgpu::TextureFormat,
289    /// Seeds noise textures, rotation matrices, hue offsets.
290    pub seed: u64,
291    /// MD2 vs projectM behaviour where they differ (default projectM).
292    pub compat: Compat,
293    /// Rasterisation of 1-pixel lines and points, see [`StrokeRaster`].
294    pub stroke: StrokeRaster,
295}
296
297impl Default for RenderConfig {
298    fn default() -> Self {
299        Self::from_run(&RunConfig::default(), wgpu::TextureFormat::Rgba8Unorm)
300    }
301}
302
303impl RenderConfig {
304    /// Build a config from the ABI's [`RunConfig`] (size, mesh, texel offset, seed) and the host
305    /// target format; compatibility and stroke mode take their defaults.
306    pub fn from_run(run: &RunConfig, output_format: wgpu::TextureFormat) -> Self {
307        Self {
308            width: run.width,
309            height: run.height,
310            mesh: run.mesh,
311            texel_offset: run.texel_offset,
312            output_format,
313            seed: run.seed,
314            compat: Compat::default(),
315            stroke: StrokeRaster::default(),
316        }
317    }
318}
319
320/// A warp or composite shader: WGSL module source (starting with `lactea_abi::WGSL_COMMON`,
321/// entry `fs_main`) plus the resource interface the renderer binds in group 1.
322#[derive(Clone, Debug)]
323pub struct CompiledShader {
324    /// WGSL module source.
325    pub wgsl: String,
326    /// Resource interface bound in group 1.
327    pub interface: ShaderInterface,
328}
329
330/// Errors reported by the renderer.
331#[derive(Debug)]
332#[non_exhaustive]
333pub enum RenderError {
334    /// Shader module / pipeline rejected by wgpu validation.
335    Shader(String),
336    /// Bad argument (sizes, data length, ...).
337    Invalid(String),
338    /// GPU read-back failed.
339    Readback(String),
340}
341
342impl std::fmt::Display for RenderError {
343    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344        match self {
345            RenderError::Shader(s) => write!(f, "shader error: {s}"),
346            RenderError::Invalid(s) => write!(f, "invalid argument: {s}"),
347            RenderError::Readback(s) => write!(f, "readback error: {s}"),
348        }
349    }
350}
351impl std::error::Error for RenderError {}