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/// | preset code lines (`md2_code_join`) | joined with `\n` | joined with nothing and `//` / `\\` comments stripped (`CState::StripLinefeedCharsAndComments`) |
45/// | gamma / echo / filter flags / main-wave mode and flags (`frame_vars_drive_post`) | the preset's initial values | the per-frame variable values |
46/// | shader random streams (`shared_shader_rand`) | separate warp / comp streams, constructor draws after `rand_preset` | one shared stream per preset |
47/// | warp animation terms (`warp_anim_projectm`) | projectM's `y` sign and GPU `pow` | MD2's |
48/// | `shapecode_N_image` key (`custom_shape_image`) | read | not a key (stays in `extra`) |
49/// | no-shader composite sampler address (`noshader_comp_wrap`) | clamp | wrap |
50/// | expression language (`md3_ns_eel2`) | projectm-eval | projectm-eval / projectm-eval / ns-eel2 (MilkDrop 3 only) |
51/// | preset code that fails to compile (`md3_drop_failed_code`) | the preset is rejected | the preset is rejected (MilkDrop 2 itself drops the part; not ported) / MilkDrop 3 drops the part and loads |
52/// | `.milk2` double presets (`md3_double_preset`) | not loaded (error) | not loaded (error) |
53/// | soft-cut blend patterns (`md3_blend_patterns`) | (projectM transition shaders) | BeatDrop's 19 (MD3: its 30) |
54///
55/// `MilkDrop3` is `MilkDrop2` plus the MilkDrop 3 deltas (see `docs/md3.md`); every MD3 delta is a field of
56/// [`CompatRules`], and [`Compat::md2_family`] is true for both variants.
57///
58/// Not switchable (identical in both): blur chain, blur source (previous frame image), blur
59/// min/max "push apart" typo.
60#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
61pub enum Compat {
62    /// projectM's behaviour (the default).
63    #[default]
64    ProjectM,
65    /// MilkDrop 2's behaviour (Direct3D 9 semantics).
66    MilkDrop2,
67    /// MilkDrop 3 (3.37) behaviour: MilkDrop 2 / BeatDrop rules plus the MilkDrop 3 deltas. MD3's source is unpublished;
68    /// its behaviour is implemented from clean-room specs, see `docs/md3.md`.
69    MilkDrop3,
70}
71
72/// The individual behaviours selected by a [`Compat`] value (see the table there for the
73/// projectM / MilkDrop 2 values of each).
74#[derive(Clone, Copy, Debug, PartialEq)]
75#[non_exhaustive]
76pub struct CompatRules {
77    /// `vol` / `vol_att` follow MD2's comma-operator bug (`0.3333*treb`).
78    pub vol_is_comma_bug: bool,
79    /// `_c12.y` (`mip_y`) is derived from the width instead of the height (MD2 typo).
80    pub mip_y_from_width: bool,
81    /// `_c1` (aspect "sd") is all zeros.
82    pub c1_is_zero: bool,
83    /// The no-shader warp decay is truncated to 8 bits and wraps, `(int)(decay*255)&0xFF`.
84    pub decay_8bit: bool,
85    /// Vertex colours are 8-bit truncated; otherwise float, modulo-wrapped like `& 0xFF` when outside 0..1.
86    pub quantize_vertex_colors: bool,
87    /// The no-shader composite hue tint is always applied; otherwise only if `fShader > 0.001`, blended by `fShader`.
88    pub hue_tint_always: bool,
89    /// Thick / dots main-wave passes additionally need a texture size of at least 512.
90    pub thick_needs_512: bool,
91    /// Main waveform geometry/alpha follow projectM `Waveforms/*.cpp` (`wavegen::main_wave_geometry_projectm`)
92    /// instead of the MD2 `DrawWave` port (`wavegen::main_wave_geometry`).
93    pub pm_waveforms: bool,
94    /// The custom-shape thick outline offset is one pixel (`2/W`) instead of half a pixel (`1/W`).
95    pub shape_thick_full_pixel: bool,
96    /// Motion vectors are skipped on the first frame.
97    pub mv_skip_first_frame: bool,
98    /// Minimum motion-vector length in pixels.
99    pub mv_min_len_px: f32,
100    /// Motion-vector lookup uses MD2's mirrored row (`ReversePropagatePoint`).
101    pub mv_mirrored_lookup: bool,
102    /// The composite shader's `sampler_main` reads the previous frame instead of the current one.
103    pub comp_reads_previous: bool,
104    /// The warp mesh `ang` seam is patched to -pi / +pi per half instead of interpolating across the seam row.
105    pub ang_seam_fix: bool,
106    /// The composite mesh UV gets a half-texel offset (`uv + 0.5/size`).
107    pub comp_uv_half_texel: bool,
108    /// A warp shader's `VsOut.diffuse` is `(decay, decay, decay, 1)` instead of `(1, 1, 1, 1)`.
109    pub shader_warp_diffuse_is_decay: bool,
110    /// The translation row of the `rot_*` uniforms is dropped (`glm::mat3x4` of a `mat4`).
111    pub rot_translation_dropped: bool,
112    /// The no-shader composite hue-tint colours `shade[0..1]` sit at the top corners instead of the bottom ones.
113    pub shade_top_first: bool,
114    /// Blur pass 0 samples an upside-down source, so its vertical `+1 texel` bias is `-1`.
115    pub blur_src_flipped: bool,
116    /// Warp mesh cells are split bottom-left to top-right in image space instead of top-left to bottom-right.
117    pub warp_diag_flipped: bool,
118    /// The no-shader composite / filter quad is split top-right to bottom-left instead of bottom-right to top-left.
119    pub echo_diag_flipped: bool,
120    /// projectM stretches the echo / gamma quad by `aspectMultX/Y` of `VideoEcho::Draw` (`geom::echo_aspect_mult`):
121    /// identity for landscape targets, a horizontal `H/W` magnification of the centre for portrait ones. MD2 draws the
122    /// plain `1 + 1/size` quad.
123    pub echo_quad_aspect: bool,
124    /// Epsilon of the gamma pass count of the no-echo composite, `(int)(gamma - eps) + 1` passes: projectM
125    /// (`VideoEcho::DrawGammaAdjustment`) `0.0001`, MD2 (`ShowToUser_NoShaders`) `0.001`.
126    pub gamma_pass_eps: f32,
127    /// Lines and points follow OpenGL rasterisation rules (see [`StrokeRaster`]) instead of D3D9 thin quads.
128    pub gl_strokes: bool,
129    /// Custom-wave dots use the `2n-1` vertices of `SmoothWave`; otherwise the `n` source points.
130    pub wave_dots_smoothed: bool,
131    /// Point sizes (`1 + thick` px) are honoured; otherwise points are always 1 px (`gl_PointSize` ignored).
132    pub point_size_honored: bool,
133    /// The custom-wave thick offset is `1/W` ndc in x *and* y; otherwise `2/W`, `2/H` (one pixel).
134    pub wave_thick_ndc_inc: bool,
135    /// Custom-wave point positions: projectM `static_cast<float>((x * 2.0 - 1.0) * invAspectX)` (the product is taken in
136    /// double, one rounding to `f32`); MD2 `(float)(x * 2 - 1) * m_fInvAspectX` (rounded to `f32` before the product).
137    pub wave_point_f64_aspect: bool,
138    /// projectM textures have a single level (no `glGenerateMipmap`, samplers use the plain `GL_LINEAR` /
139    /// `GL_NEAREST` min filter), so `tex2D` never blends mip levels and `tex2Dlod` / `tex2Dbias` read level 0.
140    /// MD2 uses D3D9 textures with a mip chain (trilinear).
141    pub no_mipmaps: bool,
142    /// projectM evaluates the warp UV formula (`pow`, `sin`, `cos`, multiply-adds) in its *vertex shader*, so the
143    /// result carries the GPU's approximations and fusion; MD2 does it on the CPU (`D3DX`/libm floats).
144    /// With this rule the renderer runs the warp vertex shader on the per-vertex inputs of `FrameInput::warp_gpu`.
145    pub warp_uv_on_gpu: bool,
146    /// projectM: the internal images are RGBA; `main` starts at alpha 0, the no-shader warp keeps `tex.a`,
147    /// shaders write 1, overlays blend alpha with the colour factors and textured fills multiply by `tex.a`.
148    /// MD2 (X8R8G8B8) has no alpha: sampled alpha is 1 and nothing is written.
149    pub main_alpha: bool,
150    /// projectM binds the `GL_NEAREST` flip texture (set by `TextureAttachment`) for textured shapes that sample the
151    /// main image; MD2 samples it bilinearly.
152    pub shape_main_nearest: bool,
153    /// projectM: on the frame that (re)allocates the blur textures (first frame after preset load / resize) of a preset
154    /// whose shaders sample blur, `BlurTexture::Update` restores the wrong framebuffer, so shapes, waves, main wave,
155    /// darken-centre and borders of that frame are drawn to the default framebuffer and lost. MD2 draws them.
156    pub blur_alloc_drops_overlays: bool,
157    /// projectM draws in GL window space (y up), lactea's targets are y down (wgpu / D3D9): both use the top-left
158    /// rule, so a pixel centre lying exactly on a *horizontal* triangle edge goes to the polygon below the edge in
159    /// wgpu and to the polygon above it in projectM. With this rule such triangle fills (borders whose
160    /// `size * H / 2` is a half integer) are nudged by one sub-pixel step (`geom::gl_fill_ties`). MD2 (D3D9) has
161    /// the wgpu rule.
162    pub gl_fill_ties: bool,
163    /// projectM's GL driver (Mesa) moves `interpolated input ± uniform/constant` (and a few other linear operations)
164    /// of the user warp / composite fragment shader into the vertex stage and interpolates the result, which differs
165    /// from interpolating the input and adding in the fragment stage by about 1 ulp. With this rule the HLSL
166    /// translator emits those per-vertex values (`CompiledShader::folds`) and the renderer delivers them as extra
167    /// varyings. MD2 (D3D9) and wgpu keep the fragment-stage arithmetic.
168    pub gl_varying_fold: bool,
169    /// Borders are one 8-vertex / 8-triangle mesh in projectM (`Border.cpp`, mirrored vertically by its y-flipping
170    /// projection), four rotated quads in MD2. Identical for sane sizes, different when `ob + ib > 1` or a size is
171    /// negative (self-overlapping triangles).
172    pub pm_border_mesh: bool,
173    /// Number of custom wave / custom shape slots that run: projectM `CustomWaveformCount` /
174    /// `CustomShapeCount` = 4 (the keys `wavecode_4..15` / `shapecode_4..15` are never read), MD2 / `MAX_CUSTOM_*` = 16.
175    pub custom_slots: usize,
176    /// projectM's `PerPixelMesh::WarpedBlit` binds its own sampler (`GL_LINEAR`, `GL_REPEAT` / `GL_CLAMP_TO_EDGE` from the
177    /// per-frame `wrap` variable, i.e. `bTexWrap`) on texture unit 0 *after* the warp shader loaded its samplers, which
178    /// replaces the sampler of the first `main` descriptor (`std::set` order of the sampler names, `main` always
179    /// present): a warp shader's `sampler_main` follows `wrap`, not the `fw_`/`fc_`/`pw_`/`pc_` prefix. MD2 uses the
180    /// sampler declared in the shader.
181    pub warp_main_sampler_from_wrap: bool,
182    /// Soft cuts follow MilkDrop 2's `m_bBlending` (`state.cpp` `StartBlendFrom`, `milkdropfs.cpp` `RenderFrame`): the old
183    /// preset's state stays alive next to the new one inside a single frame pipeline (one renderer, old shaders in
184    /// `m_OldShaders`). projectM instead renders both presets to their own images and blends the finished images with
185    /// one of six transition shaders ([`TransitionKind`](crate::TransitionKind)).
186    pub md2_preset_blend: bool,
187    /// Preset code lines are joined like `CState::StripLinefeedCharsAndComments`: the `\x01` line separators are
188    /// deleted without a replacement and `//` / `\\` comments are dropped up to the next separator, so a statement
189    /// split across two lines glues its halves together (`k1 = is_` + `beat*...` is `k1 = is_beat*...`). Otherwise the
190    /// lines are joined with `\n` (projectM). Applies to every EEL code part, never to shader text.
191    pub md2_code_join: bool,
192    /// `gamma`, `echo_*`, `brighten` / `darken` / `solarize` / `invert` and the main wave's `wave_mode` /
193    /// `wave_thick` / `wave_usedots` / `wave_additive` take the per-frame variable values instead of the preset's
194    /// initial values (projectM reads the file values).
195    pub frame_vars_drive_post: bool,
196    /// The warp and composite shaders share one random stream per preset (drawn once per frame); projectM keeps one
197    /// stream per pass and consumes the constructor draws after `rand_preset`.
198    pub shared_shader_rand: bool,
199    /// The warp animation terms use projectM's `y` sign and GPU-style `pow` (`WarpAnim::projectm`) instead of MD2's.
200    pub warp_anim_projectm: bool,
201    /// `shapecode_N_image` (projectM addition) names a user texture a textured shape samples.
202    pub custom_shape_image: bool,
203    /// The no-shader composite pass samples the feedback image with the `Wrap` address mode; otherwise `Clamp`.
204    pub noshader_comp_wrap: bool,
205    /// The main waveform follows MilkDrop 3 (`wavegen_md3::main_wave_geometry_md3_raw`): 17 modes `0..=16` selected by
206    /// the C remainder `(int)wave_mode % 17` (a negative result draws 480 zero vertices), one channel per formula.
207    pub md3_wave_modes: bool,
208    /// Largest `sides` a custom shape is drawn with (smallest is 3): projectM and MilkDrop 2 100, MilkDrop 3 500.
209    pub max_shape_sides: i32,
210    /// MilkDrop 3 adds the four warp `sin` / `cos` terms to the warp UV only when `|warp| > 0.0001`.
211    pub md3_warp_skip_tiny: bool,
212    /// MilkDrop 3 hides the outer / inner borders while a preset blend is running if the host's `DisableBox`
213    /// setting is on (`EngineConfig::md3_disable_box`).
214    pub md3_border_gate: bool,
215    /// MD3 `AutoHardCutMode` 1..7 (`lactea::auto_cut`) is active: the engine watches the previous frame's `bass` /
216    /// `treb` and asks for instant preset changes or injects composite-shader effects. Off under projectM and MD2.
217    pub md3_auto_hard_cut: bool,
218    /// MD3 display time of a preset: `BlendTimeAuto + TimeBetweenPresets + (rand() % 1000) * TimeBetweenPresetsRand *
219    /// 0.001` (hosts feed it to `PresetControl::set_md3_time_rand`) instead of projectM's gaussian easter egg.
220    pub md3_preset_time_rand: bool,
221    /// MilkDrop 3 audio analysis (`AnalysisMode::Md3`): left channel only, 576-sample Hann FFT, 8-bit quantised input
222    /// scaled by `VolumeSensitivity`, silence -> 1.0 (`docs/md3.md`, shader inputs).
223    pub md3_audio_analysis: bool,
224    /// The MilkDrop 3 shader FFT texture (`sampler_fft`): a max-normalised, gated, smeared attack / decay recursion of
225    /// the left spectrum, run once per rendered frame and kept across presets; `FFTAttack` / `FFTDecay` are sticky
226    /// globals set by every preset load.
227    pub md3_shader_fft: bool,
228    /// MilkDrop 3's extended expression and shader variables: `q1..q64`, `t1..t16`, `monitor2` / `monitor3` and the
229    /// `_c14` / `_qi.._qp` shader constants (the mouse is a shader input only: `mouse.x` does not compile in preset code).
230    pub md3_extended_vars: bool,
231    /// The MilkDrop 3 shader prelude is part of every translated shader (`get_fft`, `get_fft_hz`, `mouse*`,
232    /// `q33..q64`, `sampler_fft`).
233    pub md3_shader_prelude: bool,
234    /// The shader constant `time` (`_c2.x`) is the time since *this state's* preset started, modulo 10000; otherwise
235    /// the absolute frame time.
236    pub md3_shader_time: bool,
237    /// The generated composite shader of presets without `comp_N` text uses the original MilkDrop 2 formulas:
238    /// brighten `sqrt(ret)`, solarize `ret * (1 - ret) * 4` (BeatDrop: `1 - (1 - ret)^2`, `* 2`).
239    pub md3_md2_comp_effects: bool,
240    /// Preset expressions run on ns-eel2 (`lactea_eel::Dialect::NsEel2`, MilkDrop 3's engine: unguarded `/`,
241    /// assignment filtering, integer `%`, `$PI` constants, 8M-entry `megabuf`, wrapping `gmegabuf`
242    /// and registers that outlive presets, ...) instead of projectm-eval. `docs/md3.md`, "Expression engine".
243    pub md3_ns_eel2: bool,
244    /// A code part that fails to compile is dropped (with a warning) and the preset still loads: a failed init part
245    /// zeroes the post-init `q` values, a failed per-frame / per-vertex / wave / shape part simply does not run.
246    /// Otherwise the first failing part rejects the preset (`EngineError::Compile`).
247    pub md3_drop_failed_code: bool,
248    /// MilkDrop 3 `.milk2` double presets: two presets in one file, played as a frozen MD2 soft cut with its own
249    /// progress modes (`docs/md3.md`). Loading a `.milk2` without this rule is an error.
250    pub md3_double_preset: bool,
251    /// Ordinary soft cuts draw their blend pattern from MilkDrop 3's 30 patterns (the enabled list) instead of
252    /// BeatDrop's 19. Needs `md2_preset_blend`.
253    pub md3_blend_patterns: bool,
254    /// MilkDrop 3: a preset's sprite block (`SpriteName` .. `SpriteRepeatY`, docs/md3.md) loads an image and draws
255    /// it every frame at the layer the preset names, with the 11 sprite blend modes. projectM and MilkDrop 2 never
256    /// draw preset sprites.
257    pub md3_preset_sprites: bool,
258    /// MilkDrop 3: shader textures (`sampler_<name>`) are also searched in the `sprites` and `gifs` folders, accept
259    /// `.gif` / `.jfif` files, and an animated GIF shows the frame picked by `fmod(time, total)` of its delays.
260    pub md3_gif_textures: bool,
261    /// MilkDrop 3: a burning sprite in layers 1..4 is drawn **twice** into the feedback image (it burns into the
262    /// image it is already drawn on), so additive and alpha modes are twice as strong with `SpriteBurn=1` as with 0.
263    /// Measured against MD3 under Wine (docs/md3.md, sprites).
264    pub md3_sprite_burn_twice: bool,
265}
266
267impl Compat {
268    /// The behaviours of this compatibility mode.
269    pub fn rules(self) -> CompatRules {
270        match self {
271            Compat::ProjectM => CompatRules {
272                vol_is_comma_bug: false,
273                mip_y_from_width: false,
274                c1_is_zero: true,
275                decay_8bit: false,
276                quantize_vertex_colors: false,
277                hue_tint_always: true,
278                thick_needs_512: false,
279                pm_waveforms: true,
280                shape_thick_full_pixel: false,
281                mv_skip_first_frame: true,
282                mv_min_len_px: 1.25,
283                mv_mirrored_lookup: false,
284                comp_reads_previous: false,
285                ang_seam_fix: false,
286                comp_uv_half_texel: true,
287                shader_warp_diffuse_is_decay: true,
288                rot_translation_dropped: true,
289                shade_top_first: true,
290                blur_src_flipped: true,
291                warp_diag_flipped: true,
292                echo_diag_flipped: true,
293                echo_quad_aspect: true,
294                gamma_pass_eps: 0.0001,
295                gl_strokes: true,
296                wave_dots_smoothed: true,
297                point_size_honored: false,
298                wave_thick_ndc_inc: true,
299                wave_point_f64_aspect: true,
300                no_mipmaps: true,
301                warp_uv_on_gpu: true,
302                main_alpha: true,
303                shape_main_nearest: true,
304                blur_alloc_drops_overlays: true,
305                gl_fill_ties: true,
306                gl_varying_fold: true,
307                pm_border_mesh: true,
308                custom_slots: 4,
309                warp_main_sampler_from_wrap: true,
310                md2_preset_blend: false,
311                md2_code_join: false,
312                frame_vars_drive_post: false,
313                shared_shader_rand: false,
314                warp_anim_projectm: true,
315                custom_shape_image: true,
316                noshader_comp_wrap: false,
317                md3_wave_modes: false,
318                max_shape_sides: 100,
319                md3_warp_skip_tiny: false,
320                md3_border_gate: false,
321                md3_auto_hard_cut: false,
322                md3_preset_time_rand: false,
323                md3_audio_analysis: false,
324                md3_shader_fft: false,
325                md3_extended_vars: false,
326                md3_shader_prelude: false,
327                md3_shader_time: false,
328                md3_md2_comp_effects: false,
329                md3_ns_eel2: false,
330                md3_drop_failed_code: false,
331                md3_double_preset: false,
332                md3_blend_patterns: false,
333                md3_preset_sprites: false,
334                md3_gif_textures: false,
335                md3_sprite_burn_twice: false,
336            },
337            Compat::MilkDrop2 => CompatRules {
338                vol_is_comma_bug: true,
339                mip_y_from_width: true,
340                c1_is_zero: false,
341                decay_8bit: true,
342                quantize_vertex_colors: true,
343                hue_tint_always: false,
344                thick_needs_512: true,
345                pm_waveforms: false,
346                shape_thick_full_pixel: true,
347                mv_skip_first_frame: false,
348                mv_min_len_px: 1.0,
349                mv_mirrored_lookup: true,
350                comp_reads_previous: true,
351                ang_seam_fix: true,
352                comp_uv_half_texel: false,
353                shader_warp_diffuse_is_decay: false,
354                rot_translation_dropped: false,
355                shade_top_first: false,
356                blur_src_flipped: false,
357                warp_diag_flipped: false,
358                echo_diag_flipped: false,
359                echo_quad_aspect: false,
360                gamma_pass_eps: 0.001,
361                gl_strokes: false,
362                wave_dots_smoothed: false,
363                point_size_honored: true,
364                wave_thick_ndc_inc: false,
365                wave_point_f64_aspect: false,
366                no_mipmaps: false,
367                warp_uv_on_gpu: false,
368                main_alpha: false,
369                shape_main_nearest: false,
370                blur_alloc_drops_overlays: false,
371                gl_fill_ties: false,
372                gl_varying_fold: false,
373                pm_border_mesh: false,
374                custom_slots: 16,
375                warp_main_sampler_from_wrap: false,
376                md2_preset_blend: true,
377                md2_code_join: true,
378                frame_vars_drive_post: true,
379                shared_shader_rand: true,
380                warp_anim_projectm: false,
381                custom_shape_image: false,
382                noshader_comp_wrap: true,
383                md3_wave_modes: false,
384                max_shape_sides: 100,
385                md3_warp_skip_tiny: false,
386                md3_border_gate: false,
387                md3_auto_hard_cut: false,
388                md3_preset_time_rand: false,
389                md3_audio_analysis: false,
390                md3_shader_fft: false,
391                md3_extended_vars: false,
392                md3_shader_prelude: false,
393                md3_shader_time: false,
394                md3_md2_comp_effects: false,
395                md3_ns_eel2: false,
396                md3_drop_failed_code: false,
397                md3_double_preset: false,
398                md3_blend_patterns: false,
399                md3_preset_sprites: false,
400                md3_gif_textures: false,
401                md3_sprite_burn_twice: false,
402            },
403            // The MilkDrop 3 deltas go here, one `CompatRules` field each.
404            Compat::MilkDrop3 => CompatRules {
405                md3_wave_modes: true,
406                max_shape_sides: 500,
407                md3_warp_skip_tiny: true,
408                md3_border_gate: true,
409                md3_auto_hard_cut: true,
410                md3_preset_time_rand: true,
411                md3_audio_analysis: true,
412                md3_shader_fft: true,
413                md3_extended_vars: true,
414                md3_shader_prelude: true,
415                md3_shader_time: true,
416                md3_md2_comp_effects: true,
417                md3_ns_eel2: true,
418                md3_drop_failed_code: true,
419                md3_double_preset: true,
420                md3_blend_patterns: true,
421                md3_preset_sprites: true,
422                md3_gif_textures: true,
423                md3_sprite_burn_twice: true,
424                ..Compat::MilkDrop2.rules()
425            },
426        }
427    }
428
429    /// MilkDrop 2 or MilkDrop 3: the modes that run the whole MilkDrop 2 code path (preset importer, shader
430    /// translation, soft-cut machinery). Individual behaviours are [`CompatRules`] fields, not this.
431    pub fn md2_family(self) -> bool {
432        matches!(self, Compat::MilkDrop2 | Compat::MilkDrop3)
433    }
434}
435
436/// How 1-pixel lines and points (custom/main waves, shape outlines, motion vectors) are rasterised.
437///
438/// projectM draws `GL_LINES`/`GL_LINE_STRIP`/`GL_LINE_LOOP`/`GL_POINTS`, non-antialiased (`GL_LINE_SMOOTH` has no
439/// effect on Mesa). The GPU's own line rule (diamond exit) decides every stroke pixel, so the choice below only
440/// matters for pixel-exactness.
441#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
442#[non_exhaustive]
443pub enum StrokeRaster {
444    /// `wgpu` `LineList` / `PointList` primitives (1 px): fastest, but the rule is the driver's and can differ
445    /// from projectM's GL rules for many stroke pixels.
446    Native,
447    /// Exact CPU emulation of projectM's GL rules (strip / diamond exit / point floor), every lit pixel
448    /// drawn as a 1-px point at its centre: identical on every GPU.
449    #[default]
450    Emulated,
451    /// Thin quads (one pixel wide band covering the major axis extent): the D3D9 look MilkDrop 2 had.
452    /// `Compat::MilkDrop2` always draws strokes this way, whatever the configured mode.
453    Quads,
454}
455
456/// Renderer construction parameters.
457#[derive(Clone, Debug)]
458pub struct RenderConfig {
459    /// Internal image width (`m_nTexSizeX`; MD2 "auto exact" = window size), also the output width.
460    pub width: u32,
461    /// Internal image height, also the output height.
462    pub height: u32,
463    /// Warp mesh cells `[gx, gy]` (both even, e.g. `[48, 36]`).
464    pub mesh: [u32; 2],
465    /// In texels; added to warp UVs (`MD2: 0.5`, projectM/modern APIs: `0`).
466    pub texel_offset: [f32; 2],
467    /// Format of the host target view passed to `render_frame`. `*Srgb` formats are compensated so
468    /// stored bytes equal a non-sRGB render.
469    pub output_format: wgpu::TextureFormat,
470    /// Seeds noise textures, rotation matrices, hue offsets.
471    pub seed: u64,
472    /// MD2 vs projectM behaviour where they differ (default projectM).
473    pub compat: Compat,
474    /// Rasterisation of 1-pixel lines and points, see [`StrokeRaster`].
475    pub stroke: StrokeRaster,
476}
477
478impl Default for RenderConfig {
479    fn default() -> Self {
480        Self::from_run(&RunConfig::default(), wgpu::TextureFormat::Rgba8Unorm)
481    }
482}
483
484impl RenderConfig {
485    /// Build a config from the ABI's [`RunConfig`] (size, mesh, texel offset, seed) and the host
486    /// target format; compatibility and stroke mode take their defaults.
487    pub fn from_run(run: &RunConfig, output_format: wgpu::TextureFormat) -> Self {
488        Self {
489            width: run.width,
490            height: run.height,
491            mesh: run.mesh,
492            texel_offset: run.texel_offset,
493            output_format,
494            seed: run.seed,
495            compat: Compat::default(),
496            stroke: StrokeRaster::default(),
497        }
498    }
499}
500
501/// A warp or composite shader: WGSL module source (starting with `lactea_abi::WGSL_COMMON`,
502/// entry `fs_main`) plus the resource interface the renderer binds in group 1.
503#[derive(Clone, Debug)]
504pub struct CompiledShader {
505    /// WGSL module source.
506    pub wgsl: String,
507    /// Resource interface bound in group 1.
508    pub interface: ShaderInterface,
509    /// Per-vertex values interpolated as extra varyings (`lactea_hlsl::Translated::folds`). Entry `k` is a complete
510    /// WGSL function `fn fold_k(vs_uv: vec4<f32>, vs_rad_ang: vec2<f32>, vs_diffuse: vec4<f32>) -> f32` that may read
511    /// the `WGSL_COMMON` uniforms and call earlier `fold_j`. The fragment shader's `VsOut` carries them as
512    /// `@location(3 + k / 4) fold{k / 4}: vec4<f32>`, component `k % 4`. Empty: no extra varyings.
513    pub folds: Vec<String>,
514}
515
516/// Errors reported by the renderer.
517#[derive(Debug)]
518#[non_exhaustive]
519pub enum RenderError {
520    /// Shader module / pipeline rejected by wgpu validation.
521    Shader(String),
522    /// Bad argument (sizes, data length, ...).
523    Invalid(String),
524    /// GPU read-back failed.
525    Readback(String),
526}
527
528impl std::fmt::Display for RenderError {
529    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
530        match self {
531            RenderError::Shader(s) => write!(f, "shader error: {s}"),
532            RenderError::Invalid(s) => write!(f, "invalid argument: {s}"),
533            RenderError::Readback(s) => write!(f, "readback error: {s}"),
534        }
535    }
536}
537impl std::error::Error for RenderError {}