Skip to main content

lactea_render/
flash_limit.rs

1// SPDX-FileCopyrightText: 2026 Gianluca Boiano
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Photosensitivity: a post pass that limits how fast each colour channel of each pixel may change.
5//!
6//! The pass keeps the frame it showed last and moves it towards the new frame by at most `limit * dt` per channel.
7//! Slow changes pass unchanged; a channel flashing at frequency `f` can swing by at most `limit / (2 f)`. The idea
8//! (per-channel, per-pixel, rate from frame times, image fades in from black, image kept in a 10-bit format so small
9//! steps are not rounded away) follows projectM's flash limiter proposal (projectM pull request 1080); this
10//! implementation is written for wgpu.
11
12use crate::config::RenderError;
13use crate::shaders;
14use wgpu::util::DeviceExt;
15
16/// Format of the shown-frame images: ten bits per channel, so steps of a fraction of an 8-bit level survive.
17pub const FLASH_STATE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgb10a2Unorm;
18
19/// The fallback frame interval when two frame times do not advance (first frame, repeated or rewound time).
20pub(crate) const FALLBACK_FRAME_SECONDS: f32 = 1.0 / 60.0;
21
22struct State {
23    texture: wgpu::Texture,
24    view: wgpu::TextureView,
25}
26
27/// Limits the per-channel change between the frames it is fed. Owns two [`FLASH_STATE_FORMAT`] images of one size
28/// (the shown frame and the next); nothing is allocated before [`FlashLimiter::new`].
29///
30/// [`crate::Renderer::set_flash_limit`] drives one internally for `render_frame`. A host that composites frames
31/// itself (preset transitions) feeds its final image to [`FlashLimiter::apply`] and presents the returned view.
32pub struct FlashLimiter {
33    device: wgpu::Device,
34    pipeline: wgpu::RenderPipeline,
35    bgl: wgpu::BindGroupLayout,
36    state: [State; 2],
37    /// Index of the image showing the last frame.
38    shown: usize,
39    size: (u32, u32),
40    /// The shown frame is black again from the next [`FlashLimiter::apply`] on.
41    cleared: bool,
42}
43
44impl FlashLimiter {
45    /// A limiter for images of `width x height`; the first frame fades in from black.
46    ///
47    /// Fails with [`RenderError::Invalid`] if the size is zero or beyond the device's texture limit.
48    pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Result<Self, RenderError> {
49        let max = device.limits().max_texture_dimension_2d;
50        if width == 0 || height == 0 || width > max || height > max {
51            return Err(RenderError::Invalid(format!(
52                "flash limiter size {width}x{height} must be non-zero and within the device limit of {max}"
53            )));
54        }
55        let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
56            binding,
57            visibility: wgpu::ShaderStages::FRAGMENT,
58            ty: wgpu::BindingType::Texture {
59                sample_type: wgpu::TextureSampleType::Float { filterable: false },
60                view_dimension: wgpu::TextureViewDimension::D2,
61                multisampled: false,
62            },
63            count: None,
64        };
65        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
66            label: Some("flash limit"),
67            entries: &[
68                wgpu::BindGroupLayoutEntry {
69                    binding: 0,
70                    visibility: wgpu::ShaderStages::FRAGMENT,
71                    ty: wgpu::BindingType::Buffer {
72                        ty: wgpu::BufferBindingType::Uniform,
73                        has_dynamic_offset: false,
74                        min_binding_size: None,
75                    },
76                    count: None,
77                },
78                tex_entry(1),
79                tex_entry(2),
80            ],
81        });
82        let sm = device.create_shader_module(wgpu::ShaderModuleDescriptor {
83            label: Some("flash limit"),
84            source: wgpu::ShaderSource::Wgsl(shaders::FLASH_LIMIT_SRC.into()),
85        });
86        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
87            label: Some("flash limit"),
88            bind_group_layouts: &[Some(&bgl)],
89            immediate_size: 0,
90        });
91        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
92            label: Some("flash limit"),
93            layout: Some(&layout),
94            vertex: wgpu::VertexState {
95                module: &sm,
96                entry_point: Some("vs_main"),
97                compilation_options: Default::default(),
98                buffers: &[],
99            },
100            primitive: wgpu::PrimitiveState::default(),
101            depth_stencil: None,
102            multisample: wgpu::MultisampleState::default(),
103            fragment: Some(wgpu::FragmentState {
104                module: &sm,
105                entry_point: Some("fs_main"),
106                compilation_options: Default::default(),
107                targets: &[Some(wgpu::ColorTargetState {
108                    format: FLASH_STATE_FORMAT,
109                    blend: None,
110                    write_mask: wgpu::ColorWrites::ALL,
111                })],
112            }),
113            multiview_mask: None,
114            cache: None,
115        });
116        let state = || {
117            let texture = device.create_texture(&wgpu::TextureDescriptor {
118                label: Some("flash limit state"),
119                size: wgpu::Extent3d {
120                    width,
121                    height,
122                    depth_or_array_layers: 1,
123                },
124                mip_level_count: 1,
125                sample_count: 1,
126                dimension: wgpu::TextureDimension::D2,
127                format: FLASH_STATE_FORMAT,
128                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
129                    | wgpu::TextureUsages::TEXTURE_BINDING
130                    | wgpu::TextureUsages::COPY_SRC,
131                view_formats: &[],
132                texture_binding_view_dimension: None,
133            });
134            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
135            State { texture, view }
136        };
137        Ok(Self {
138            device: device.clone(),
139            pipeline,
140            bgl,
141            state: [state(), state()],
142            shown: 0,
143            size: (width, height),
144            // new textures are zero (black) already
145            cleared: false,
146        })
147    }
148
149    /// The image size this limiter was made for.
150    pub fn size(&self) -> (u32, u32) {
151        self.size
152    }
153
154    /// Forget the shown frame: the next one fades in from black again.
155    pub fn reset(&mut self) {
156        self.cleared = true;
157    }
158
159    /// Index (0 or 1) of the image holding the last limited frame; [`FlashLimiter::view`] of it.
160    pub(crate) fn shown_index(&self) -> usize {
161        self.shown
162    }
163
164    /// One of the two state images.
165    pub(crate) fn view(&self, index: usize) -> &wgpu::TextureView {
166        &self.state[index].view
167    }
168
169    /// The texture of the last limited frame ([`FLASH_STATE_FORMAT`]), e.g. for read-back.
170    pub fn shown_texture(&self) -> &wgpu::Texture {
171        &self.state[self.shown].texture
172    }
173
174    /// Record the limiting of `src` (any float-filterable or unfilterable colour image of this limiter's size) into
175    /// `encoder`: each channel of the shown frame moves towards `src` by at most `max_step` (in units of the full
176    /// 0..1 range). `max_step` is `limit * dt`; a non-finite or negative value freezes the image. Returns the view of
177    /// the limited frame, which stays the shown frame for the next call.
178    pub fn apply(
179        &mut self,
180        encoder: &mut wgpu::CommandEncoder,
181        src: &wgpu::TextureView,
182        max_step: f32,
183    ) -> &wgpu::TextureView {
184        let max_step = if max_step.is_finite() {
185            max_step.max(0.0)
186        } else {
187            0.0
188        };
189        if self.cleared {
190            let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
191                label: Some("flash limit reset"),
192                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
193                    view: &self.state[self.shown].view,
194                    depth_slice: None,
195                    resolve_target: None,
196                    ops: wgpu::Operations {
197                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
198                        store: wgpu::StoreOp::Store,
199                    },
200                })],
201                ..Default::default()
202            });
203            self.cleared = false;
204        }
205        let next = 1 - self.shown;
206        let params = [max_step, 0.0, 0.0, 0.0f32];
207        let ub = self
208            .device
209            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
210                label: Some("flash limit"),
211                contents: bytemuck::bytes_of(&params),
212                usage: wgpu::BufferUsages::UNIFORM,
213            });
214        let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
215            label: Some("flash limit"),
216            layout: &self.bgl,
217            entries: &[
218                wgpu::BindGroupEntry {
219                    binding: 0,
220                    resource: ub.as_entire_binding(),
221                },
222                wgpu::BindGroupEntry {
223                    binding: 1,
224                    resource: wgpu::BindingResource::TextureView(src),
225                },
226                wgpu::BindGroupEntry {
227                    binding: 2,
228                    resource: wgpu::BindingResource::TextureView(&self.state[self.shown].view),
229                },
230            ],
231        });
232        {
233            let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
234                label: Some("flash limit"),
235                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
236                    view: &self.state[next].view,
237                    depth_slice: None,
238                    resolve_target: None,
239                    ops: wgpu::Operations {
240                        load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
241                        store: wgpu::StoreOp::Store,
242                    },
243                })],
244                ..Default::default()
245            });
246            rp.set_pipeline(&self.pipeline);
247            rp.set_bind_group(0, &bg, &[]);
248            rp.draw(0..3, 0..1);
249        }
250        self.shown = next;
251        &self.state[next].view
252    }
253}