lactea-render 0.2.4

wgpu backend reproducing the MilkDrop 2 frame pipeline; host-provided device, renders into any texture.
Documentation
// SPDX-FileCopyrightText: 2026 Gianluca Boiano
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Photosensitivity: a post pass that limits how fast each colour channel of each pixel may change.
//!
//! The pass keeps the frame it showed last and moves it towards the new frame by at most `limit * dt` per channel.
//! Slow changes pass unchanged; a channel flashing at frequency `f` can swing by at most `limit / (2 f)`. The idea
//! (per-channel, per-pixel, rate from frame times, image fades in from black, image kept in a 10-bit format so small
//! steps are not rounded away) follows projectM's flash limiter proposal (projectM pull request 1080); this
//! implementation is written for wgpu.

use crate::config::RenderError;
use crate::shaders;
use wgpu::util::DeviceExt;

/// Format of the shown-frame images: ten bits per channel, so steps of a fraction of an 8-bit level survive.
pub const FLASH_STATE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgb10a2Unorm;

/// The fallback frame interval when two frame times do not advance (first frame, repeated or rewound time).
pub(crate) const FALLBACK_FRAME_SECONDS: f32 = 1.0 / 60.0;

struct State {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
}

/// Limits the per-channel change between the frames it is fed. Owns two [`FLASH_STATE_FORMAT`] images of one size
/// (the shown frame and the next); nothing is allocated before [`FlashLimiter::new`].
///
/// [`crate::Renderer::set_flash_limit`] drives one internally for `render_frame`. A host that composites frames
/// itself (preset transitions) feeds its final image to [`FlashLimiter::apply`] and presents the returned view.
pub struct FlashLimiter {
    device: wgpu::Device,
    pipeline: wgpu::RenderPipeline,
    bgl: wgpu::BindGroupLayout,
    state: [State; 2],
    /// Index of the image showing the last frame.
    shown: usize,
    size: (u32, u32),
    /// The shown frame is black again from the next [`FlashLimiter::apply`] on.
    cleared: bool,
}

impl FlashLimiter {
    /// A limiter for images of `width x height`; the first frame fades in from black.
    ///
    /// Fails with [`RenderError::Invalid`] if the size is zero or beyond the device's texture limit.
    pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Result<Self, RenderError> {
        let max = device.limits().max_texture_dimension_2d;
        if width == 0 || height == 0 || width > max || height > max {
            return Err(RenderError::Invalid(format!(
                "flash limiter size {width}x{height} must be non-zero and within the device limit of {max}"
            )));
        }
        let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::FRAGMENT,
            ty: wgpu::BindingType::Texture {
                sample_type: wgpu::TextureSampleType::Float { filterable: false },
                view_dimension: wgpu::TextureViewDimension::D2,
                multisampled: false,
            },
            count: None,
        };
        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("flash limit"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                tex_entry(1),
                tex_entry(2),
            ],
        });
        let sm = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("flash limit"),
            source: wgpu::ShaderSource::Wgsl(shaders::FLASH_LIMIT_SRC.into()),
        });
        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("flash limit"),
            bind_group_layouts: &[Some(&bgl)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("flash limit"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &sm,
                entry_point: Some("vs_main"),
                compilation_options: Default::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            fragment: Some(wgpu::FragmentState {
                module: &sm,
                entry_point: Some("fs_main"),
                compilation_options: Default::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: FLASH_STATE_FORMAT,
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });
        let state = || {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("flash limit state"),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: FLASH_STATE_FORMAT,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING
                    | wgpu::TextureUsages::COPY_SRC,
                view_formats: &[],
                texture_binding_view_dimension: None,
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            State { texture, view }
        };
        Ok(Self {
            device: device.clone(),
            pipeline,
            bgl,
            state: [state(), state()],
            shown: 0,
            size: (width, height),
            // new textures are zero (black) already
            cleared: false,
        })
    }

    /// The image size this limiter was made for.
    pub fn size(&self) -> (u32, u32) {
        self.size
    }

    /// Forget the shown frame: the next one fades in from black again.
    pub fn reset(&mut self) {
        self.cleared = true;
    }

    /// Index (0 or 1) of the image holding the last limited frame; [`FlashLimiter::view`] of it.
    pub(crate) fn shown_index(&self) -> usize {
        self.shown
    }

    /// One of the two state images.
    pub(crate) fn view(&self, index: usize) -> &wgpu::TextureView {
        &self.state[index].view
    }

    /// The texture of the last limited frame ([`FLASH_STATE_FORMAT`]), e.g. for read-back.
    pub fn shown_texture(&self) -> &wgpu::Texture {
        &self.state[self.shown].texture
    }

    /// Record the limiting of `src` (any float-filterable or unfilterable colour image of this limiter's size) into
    /// `encoder`: each channel of the shown frame moves towards `src` by at most `max_step` (in units of the full
    /// 0..1 range). `max_step` is `limit * dt`; a non-finite or negative value freezes the image. Returns the view of
    /// the limited frame, which stays the shown frame for the next call.
    pub fn apply(
        &mut self,
        encoder: &mut wgpu::CommandEncoder,
        src: &wgpu::TextureView,
        max_step: f32,
    ) -> &wgpu::TextureView {
        let max_step = if max_step.is_finite() {
            max_step.max(0.0)
        } else {
            0.0
        };
        if self.cleared {
            let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("flash limit reset"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &self.state[self.shown].view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                ..Default::default()
            });
            self.cleared = false;
        }
        let next = 1 - self.shown;
        let params = [max_step, 0.0, 0.0, 0.0f32];
        let ub = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("flash limit"),
                contents: bytemuck::bytes_of(&params),
                usage: wgpu::BufferUsages::UNIFORM,
            });
        let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("flash limit"),
            layout: &self.bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: ub.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(src),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(&self.state[self.shown].view),
                },
            ],
        });
        {
            let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("flash limit"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &self.state[next].view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                ..Default::default()
            });
            rp.set_pipeline(&self.pipeline);
            rp.set_bind_group(0, &bg, &[]);
            rp.draw(0..3, 0..1);
        }
        self.shown = next;
        &self.state[next].view
    }
}