Skip to main content

lactea_render/
sprite.rs

1// SPDX-FileCopyrightText: 2026 Gianluca Boiano
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! MilkDrop 3 preset sprites: the quad draw with the 11 blend modes (MD3 3.37, docs/md3.md "Sprites").
5//!
6//! MD3 draws a sprite with the fixed-function D3D9 pipeline: vertex colour, one texture stage and a blend
7//! state. The stage arithmetic is reproduced by one fragment entry point per mode, the blend factors by the
8//! pipeline's blend state, so each mode is exactly `out = C * SRC + D * DEST` of the table in the docs.
9//! Everything that decides *what* is drawn (sprite state, geometry, GIF frame) is the engine's; this module
10//! only turns a [`SpriteDraw`] into pixels.
11
12use std::collections::HashMap;
13use wgpu::util::DeviceExt;
14
15/// Number of blend modes (`0..=10`).
16pub const SPRITE_MODES: usize = 11;
17
18/// One corner of a sprite quad.
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct SpriteVertex {
21    /// Position in MD3's sprite space: `±1` is the target's edge, **y points down** (the D3D 2D projection of
22    /// MilkDrop flips y), z is 0.
23    pub pos: [f32; 2],
24    /// Texture coordinate (row 0 = top of the image); the sampler wraps in both directions.
25    pub uv: [f32; 2],
26}
27
28/// One sprite draw handed to the renderer in [`FrameInput::sprites`](crate::FrameInput::sprites).
29#[derive(Clone, Debug)]
30pub struct SpriteDraw {
31    /// Where it is drawn: `1..=4` into the feedback image (between warp / shapes / waves / main wave, so it
32    /// goes through the composite and is warped next frame), `0` onto the composited output. Other values are
33    /// not drawn.
34    pub layer: u8,
35    /// Image id given to [`Renderer::set_sprite_image`](crate::Renderer::set_sprite_image).
36    pub image: u32,
37    /// Frame of that image (animated GIFs); out of range draws nothing.
38    pub frame: usize,
39    /// Blend mode `0..=10`; any other value behaves as mode 0.
40    pub blend: i32,
41    /// `r, g, b` clamped to `0..1`; `a` is the per-frame alpha times the preset's `SpriteAlpha`, **not**
42    /// clamped (the vertex colour byte wraps like `trunc(255 a) & 0xFF`).
43    pub rgba: [f32; 4],
44    /// Triangle-strip order.
45    pub quad: [SpriteVertex; 4],
46    /// Layer 0: the sprite is also drawn into the feedback image after the composite has read it. Layers 1..4
47    /// already draw into the feedback image; there a burning sprite is drawn twice
48    /// (`CompatRules::md3_sprite_burn_twice`).
49    pub burn: bool,
50}
51
52/// The mode a `blend` value selects (`0` for anything outside `0..=10`).
53pub fn sprite_mode(blend: i32) -> usize {
54    if (0..SPRITE_MODES as i32).contains(&blend) {
55        blend as usize
56    } else {
57        0
58    }
59}
60
61/// `trunc(255 x) & 0xFF`: how D3D packs a float vertex colour channel.
62fn q8(x: f32) -> u8 {
63    ((x * 255.0) as i32 & 0xFF) as u8
64}
65
66/// The vertex colour `(r, g, b, a)` of a sprite in `mode`, after the byte quantisation of `D3DCOLOR`.
67///
68/// Modes 1 and 2 premultiply the colour by `a` and force alpha 1, mode 3 is plain white, mode 7 has a white
69/// colour (its colour comes from the texture and `TFACTOR`), mode 8 folds the colour `c` to `c > 0.5 ? 1 - c : c`.
70pub fn sprite_vertex_color(mode: usize, rgba: [f32; 4]) -> [u8; 4] {
71    let [r, g, b, a] = rgba;
72    match mode {
73        1 | 2 => [q8(r * a), q8(g * a), q8(b * a), 255],
74        3 => [255; 4],
75        7 => [255, 255, 255, q8(a)],
76        8 => {
77            let f = |c: f32| if c > 0.5 { 1.0 - c } else { c };
78            [q8(f(r)), q8(f(g)), q8(f(b)), q8(a)]
79        }
80        _ => [q8(r), q8(g), q8(b), q8(a)],
81    }
82}
83
84/// CPU model of the table: result of drawing a texel `texel` (straight alpha) over the destination colour `dst`
85/// with a sprite of colour `rgba` in `mode`, in `0..=255` units (not rounded). It follows the table, not the
86/// shader: stage colour `C` / alpha `A`, then `out = C * SRC + D * DEST` with the mode's factors.
87pub fn sprite_blend_reference(
88    mode: usize,
89    rgba: [f32; 4],
90    texel: [u8; 4],
91    dst: [u8; 3],
92) -> [f32; 3] {
93    let v = sprite_vertex_color(mode, rgba).map(|c| f32::from(c) / 255.0);
94    let t = texel.map(|c| f32::from(c) / 255.0);
95    let d = dst.map(|c| f32::from(c) / 255.0);
96    let sat = |x: f32| x.clamp(0.0, 1.0);
97    // stage-0 alpha: MODULATE(diffuse, texture) for 4, 7, 8, the diffuse alpha otherwise
98    let a = match mode {
99        4 | 7 | 8 => v[3] * t[3],
100        _ => v[3],
101    };
102    let mut c = [0.0f32; 3];
103    for i in 0..3 {
104        c[i] = match mode {
105            3 => t[i],
106            7 => sat(1.0 - t[i]),
107            9 => sat(t[i] + v[i] - 0.5),
108            10 => sat(2.0 * t[i] * v[i]),
109            _ => v[i] * t[i],
110        };
111    }
112    let mut out = [0.0f32; 3];
113    for i in 0..3 {
114        // (SRC factor, DEST factor)
115        let (s, dd) = match mode {
116            1 => (1.0, 0.0), // blend off
117            2 | 10 => (1.0, 1.0),
118            3 => (c[i], 1.0 - c[i]),
119            5 => (d[i], 0.0),
120            6 => (0.0, 1.0 - c[i]),
121            9 => (0.0, c[i]),
122            _ => (a, 1.0 - a),
123        };
124        out[i] = sat(c[i] * s + d[i] * dd) * 255.0;
125    }
126    out
127}
128
129/// GIF frame choice (MD3 3.37): `t = fmod(time, sum(delays))`, the first frame whose cumulative delay is
130/// strictly greater than `t`, else the last. One frame, no delays or a non-positive total always give frame 0.
131/// `delays` are in seconds and already follow the "`<= 0` means 0.1 s" rule.
132pub fn gif_frame_index(delays: &[f64], time: f64) -> usize {
133    let total: f64 = delays.iter().sum();
134    if delays.len() < 2 || total.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
135        return 0;
136    }
137    let t = time % total;
138    let mut acc = 0.0;
139    for (i, d) in delays.iter().enumerate() {
140        acc += d;
141        if acc > t {
142            return i;
143        }
144    }
145    delays.len() - 1
146}
147
148/// An image registered with [`Renderer::set_sprite_image`](crate::Renderer::set_sprite_image).
149pub(crate) struct SpriteImage {
150    /// One view per animation frame (a view keeps its texture alive).
151    pub(crate) frames: Vec<wgpu::TextureView>,
152}
153
154/// GPU vertex of a sprite quad.
155#[repr(C)]
156#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
157struct GpuVertex {
158    pos: [f32; 2],
159    uv: [f32; 2],
160    color: [f32; 4],
161}
162
163const ATTRS: [wgpu::VertexAttribute; 3] =
164    wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Float32x4];
165
166/// Vertex stage (sprite space has y down); the fragment entry points follow in [`FRAGMENT_RETURNS`].
167const VERTEX_SRC: &str = r#"
168@group(0) @binding(0) var tex: texture_2d<f32>;
169@group(0) @binding(1) var samp: sampler;
170
171struct VOut {
172    @builtin(position) position: vec4<f32>,
173    @location(0) uv: vec2<f32>,
174    @location(1) color: vec4<f32>,
175};
176
177@vertex
178fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>) -> VOut {
179    var o: VOut;
180    o.position = vec4<f32>(pos.x, -pos.y, 0.0, 1.0);
181    o.uv = uv;
182    o.color = color;
183    return o;
184}
185"#;
186
187/// The returned value of fragment entry point `fs<mode>`, indexed by mode (`t` is the texel, `in.color` the
188/// diffuse): the stage-0 colour and alpha of the table.
189const FRAGMENT_RETURNS: [&str; 11] = [
190    // 0 Blend: MODULATE(diffuse, texture) colour, diffuse alpha
191    "vec4<f32>(in.color.rgb * t.rgb, in.color.a)",
192    // 1 Decal: colour only, alpha 1 (blending off)
193    "vec4<f32>(in.color.rgb * t.rgb, 1.0)",
194    // 2 Additive: colour only, alpha 1
195    "vec4<f32>(in.color.rgb * t.rgb, 1.0)",
196    // 3 Srccolor: the texture alone
197    "vec4<f32>(t.rgb, 1.0)",
198    // 4 Colorkey: alpha = diffuse * texture alpha
199    "vec4<f32>(in.color.rgb * t.rgb, in.color.a * t.a)",
200    // 5 Multiplicative: colour only
201    "vec4<f32>(in.color.rgb * t.rgb, in.color.a)",
202    // 6 Subtractive: colour only
203    "vec4<f32>(in.color.rgb * t.rgb, in.color.a)",
204    // 7 Invert: SUBTRACT(TFACTOR = white, texture)
205    "vec4<f32>(clamp(vec3<f32>(1.0) - t.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a * t.a)",
206    // 8 Cut-off: MODULATE(texture, diffuse), alpha = diffuse * texture alpha
207    "vec4<f32>(t.rgb * in.color.rgb, in.color.a * t.a)",
208    // 9 Darken: ADDSIGNED(texture, diffuse)
209    "vec4<f32>(clamp(t.rgb + in.color.rgb - vec3<f32>(0.5), vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a)",
210    // 10 Vivid: MODULATE2X(texture, diffuse)
211    "vec4<f32>(clamp(2.0 * t.rgb * in.color.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), in.color.a)",
212];
213
214/// The complete WGSL module: vertex stage and one fragment entry point `fs<mode>` per mode.
215fn shader_source() -> String {
216    let mut s = String::from(VERTEX_SRC);
217    for (mode, ret) in FRAGMENT_RETURNS.iter().enumerate() {
218        s.push_str(&format!(
219            "@fragment fn fs{mode}(in: VOut) -> @location(0) vec4<f32> {{\n    let t = textureSample(tex, samp, in.uv);\n    return {ret};\n}}\n"
220        ));
221    }
222    s
223}
224
225/// `(SRCBLEND, DESTBLEND)` of a mode; `None` = alpha blending off (decal).
226fn factors(mode: usize) -> Option<(wgpu::BlendFactor, wgpu::BlendFactor)> {
227    use wgpu::BlendFactor as F;
228    Some(match mode {
229        1 => return None,
230        2 | 10 => (F::One, F::One),
231        3 => (F::Src, F::OneMinusSrc),
232        5 => (F::Dst, F::Zero),
233        6 => (F::Zero, F::OneMinusSrc),
234        9 => (F::Zero, F::Src),
235        _ => (F::SrcAlpha, F::OneMinusSrcAlpha),
236    })
237}
238
239/// The 11 sprite pipelines, built on first use.
240pub(crate) struct SpritePipes {
241    pipelines: Vec<wgpu::RenderPipeline>,
242}
243
244impl SpritePipes {
245    pub(crate) fn new(
246        device: &wgpu::Device,
247        bgl_tex: &wgpu::BindGroupLayout,
248        format: wgpu::TextureFormat,
249    ) -> Self {
250        let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
251            label: Some("sprite"),
252            source: wgpu::ShaderSource::Wgsl(shader_source().into()),
253        });
254        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
255            label: Some("sprite"),
256            bind_group_layouts: &[Some(bgl_tex)],
257            immediate_size: 0,
258        });
259        let pipelines = (0..SPRITE_MODES)
260            .map(|mode| {
261                let entry = format!("fs{mode}");
262                // the destination alpha is never touched: it carries no meaning in the MilkDrop 2 family
263                let keep_alpha = wgpu::BlendComponent {
264                    src_factor: wgpu::BlendFactor::Zero,
265                    dst_factor: wgpu::BlendFactor::One,
266                    operation: wgpu::BlendOperation::Add,
267                };
268                let blend = factors(mode).map(|(s, d)| wgpu::BlendState {
269                    color: wgpu::BlendComponent {
270                        src_factor: s,
271                        dst_factor: d,
272                        operation: wgpu::BlendOperation::Add,
273                    },
274                    alpha: keep_alpha,
275                });
276                device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
277                    label: Some("sprite"),
278                    layout: Some(&layout),
279                    vertex: wgpu::VertexState {
280                        module: &module,
281                        entry_point: Some("vs_main"),
282                        compilation_options: Default::default(),
283                        buffers: &[Some(wgpu::VertexBufferLayout {
284                            array_stride: std::mem::size_of::<GpuVertex>() as u64,
285                            step_mode: wgpu::VertexStepMode::Vertex,
286                            attributes: &ATTRS,
287                        })],
288                    },
289                    primitive: wgpu::PrimitiveState {
290                        topology: wgpu::PrimitiveTopology::TriangleStrip,
291                        ..Default::default()
292                    },
293                    depth_stencil: None,
294                    multisample: wgpu::MultisampleState::default(),
295                    fragment: Some(wgpu::FragmentState {
296                        module: &module,
297                        entry_point: Some(&entry),
298                        compilation_options: Default::default(),
299                        targets: &[Some(wgpu::ColorTargetState {
300                            format,
301                            blend,
302                            write_mask: wgpu::ColorWrites::ALL,
303                        })],
304                    }),
305                    multiview_mask: None,
306                    cache: None,
307                })
308            })
309            .collect();
310        Self { pipelines }
311    }
312
313    /// Draw `draws` in order onto `target` (loaded, not cleared).
314    pub(crate) fn draw(
315        &self,
316        device: &wgpu::Device,
317        encoder: &mut wgpu::CommandEncoder,
318        target: &wgpu::TextureView,
319        bgl_tex: &wgpu::BindGroupLayout,
320        sampler: &wgpu::Sampler,
321        images: &HashMap<u32, SpriteImage>,
322        draws: &[&SpriteDraw],
323    ) {
324        let mut verts: Vec<GpuVertex> = Vec::with_capacity(draws.len() * 4);
325        let mut groups: Vec<(usize, wgpu::BindGroup)> = Vec::with_capacity(draws.len());
326        for d in draws {
327            let Some(view) = images.get(&d.image).and_then(|i| i.frames.get(d.frame)) else {
328                continue;
329            };
330            let mode = sprite_mode(d.blend);
331            let color = sprite_vertex_color(mode, d.rgba).map(|c| f32::from(c) / 255.0);
332            verts.extend(d.quad.iter().map(|v| GpuVertex {
333                pos: v.pos,
334                uv: v.uv,
335                color,
336            }));
337            groups.push((
338                mode,
339                device.create_bind_group(&wgpu::BindGroupDescriptor {
340                    label: Some("sprite"),
341                    layout: bgl_tex,
342                    entries: &[
343                        wgpu::BindGroupEntry {
344                            binding: 0,
345                            resource: wgpu::BindingResource::TextureView(view),
346                        },
347                        wgpu::BindGroupEntry {
348                            binding: 1,
349                            resource: wgpu::BindingResource::Sampler(sampler),
350                        },
351                    ],
352                }),
353            ));
354        }
355        if groups.is_empty() {
356            return;
357        }
358        let buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
359            label: Some("sprite verts"),
360            contents: bytemuck::cast_slice(&verts),
361            usage: wgpu::BufferUsages::VERTEX,
362        });
363        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
364            label: Some("sprites"),
365            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
366                view: target,
367                depth_slice: None,
368                resolve_target: None,
369                ops: wgpu::Operations {
370                    load: wgpu::LoadOp::Load,
371                    store: wgpu::StoreOp::Store,
372                },
373            })],
374            ..Default::default()
375        });
376        pass.set_vertex_buffer(0, buf.slice(..));
377        for (i, (mode, bg)) in groups.iter().enumerate() {
378            pass.set_pipeline(&self.pipelines[*mode]);
379            pass.set_bind_group(0, bg, &[]);
380            let s = (i * 4) as u32;
381            pass.draw(s..s + 4, 0..1);
382        }
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    /// `T = (204, 102, 51, 255)`, `D = 128` of the blend table.
391    const T: [u8; 4] = [204, 102, 51, 255];
392    const D: [u8; 3] = [128; 3];
393
394    fn rounded(mode: usize, rgb: [f32; 3]) -> [i32; 3] {
395        sprite_blend_reference(mode, [rgb[0], rgb[1], rgb[2], 0.4], T, D).map(|c| c.round() as i32)
396    }
397
398    fn near(a: [i32; 3], b: [i32; 3]) -> bool {
399        a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1)
400    }
401
402    /// The reference reproduces the worked example of the specification (+-1 for hardware rounding).
403    #[test]
404    fn reference_matches_the_documented_example() {
405        let white = [
406            [158, 118, 97],
407            [82, 41, 20],
408            [210, 169, 148],
409            [189, 118, 113],
410            [158, 118, 97],
411            [102, 51, 26],
412            [26, 77, 102],
413            [97, 138, 158],
414            [77, 77, 77],
415            [128, 115, 90],
416            [255, 255, 230],
417        ];
418        let tint = [
419            [158, 101, 81],
420            [82, 24, 4],
421            [210, 152, 132],
422            [189, 118, 113],
423            [158, 101, 81],
424            [102, 31, 5],
425            [26, 97, 123],
426            [97, 138, 158],
427            [77, 93, 81],
428            [128, 64, 0],
429            [255, 250, 148],
430        ];
431        for mode in 0..SPRITE_MODES {
432            let got = rounded(mode, [1.0, 1.0, 1.0]);
433            assert!(near(got, white[mode]), "mode {mode} white: {got:?}");
434            let got = rounded(mode, [1.0, 0.6, 0.2]);
435            assert!(near(got, tint[mode]), "mode {mode} tint: {got:?}");
436        }
437    }
438
439    #[test]
440    fn keyed_texels_leave_the_destination_for_alpha_textured_modes() {
441        let keyed = [204, 102, 51, 0];
442        for mode in [4, 7, 8] {
443            let out = sprite_blend_reference(mode, [1.0, 1.0, 1.0, 0.4], keyed, D);
444            assert_eq!(out.map(|c| c.round() as i32), [128; 3], "mode {mode}");
445        }
446        // the others ignore the texel alpha
447        for mode in [0, 1, 2, 3, 5, 6, 9, 10] {
448            let a = sprite_blend_reference(mode, [1.0, 0.6, 0.2, 0.4], keyed, D);
449            let b = sprite_blend_reference(mode, [1.0, 0.6, 0.2, 0.4], T, D);
450            assert_eq!(a, b, "mode {mode}");
451        }
452    }
453
454    #[test]
455    fn vertex_colours_follow_the_table() {
456        let rgba = [1.0, 0.6, 0.2, 0.4];
457        assert_eq!(sprite_vertex_color(0, rgba), [255, 153, 51, 102]);
458        assert_eq!(sprite_vertex_color(1, rgba), [102, 61, 20, 255]);
459        assert_eq!(sprite_vertex_color(3, rgba), [255; 4]);
460        assert_eq!(sprite_vertex_color(7, rgba), [255, 255, 255, 102]);
461        // mode 8 folds the colour: 0.6 -> 0.4
462        let v8 = sprite_vertex_color(8, rgba);
463        assert_eq!((v8[0], v8[2], v8[3]), (0, 51, 102));
464        assert!((101..=102).contains(&v8[1]), "{v8:?}");
465        // the alpha byte wraps like `& 0xFF`
466        assert_eq!(sprite_vertex_color(0, [0.0, 0.0, 0.0, 2.0])[3], 254);
467    }
468
469    #[test]
470    fn out_of_range_blend_is_mode_zero() {
471        assert_eq!(sprite_mode(-1), 0);
472        assert_eq!(sprite_mode(11), 0);
473        assert_eq!(sprite_mode(10), 10);
474    }
475
476    #[test]
477    fn gif_frame_selection_follows_the_delay_rule() {
478        // delays [10, 20, 5] hundredths
479        let d = [0.1, 0.2, 0.05];
480        assert_eq!(gif_frame_index(&d, 0.0), 0);
481        assert_eq!(gif_frame_index(&d, 0.12), 1);
482        // cumulative 0.1, 0.3, 0.35: "0.3 > t" is false at exactly 0.3 and t = 0.31 is frame 2
483        assert_eq!(gif_frame_index(&d, 0.31), 2);
484        assert_eq!(gif_frame_index(&d, 0.36), 0, "0.36 mod 0.35 = 0.01");
485        assert_eq!(gif_frame_index(&d, 0.35 * 7.0 + 0.12), 1);
486        // single frames and degenerate delays stay on frame 0
487        assert_eq!(gif_frame_index(&[0.5], 3.0), 0);
488        assert_eq!(gif_frame_index(&[], 3.0), 0);
489        assert_eq!(gif_frame_index(&[0.0, 0.0], 3.0), 0);
490    }
491}