1use crate::config::RenderError;
13use crate::shaders;
14use wgpu::util::DeviceExt;
15
16pub const FLASH_STATE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgb10a2Unorm;
18
19pub(crate) const FALLBACK_FRAME_SECONDS: f32 = 1.0 / 60.0;
21
22struct State {
23 texture: wgpu::Texture,
24 view: wgpu::TextureView,
25}
26
27pub struct FlashLimiter {
33 device: wgpu::Device,
34 pipeline: wgpu::RenderPipeline,
35 bgl: wgpu::BindGroupLayout,
36 state: [State; 2],
37 shown: usize,
39 size: (u32, u32),
40 cleared: bool,
42}
43
44impl FlashLimiter {
45 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 cleared: false,
146 })
147 }
148
149 pub fn size(&self) -> (u32, u32) {
151 self.size
152 }
153
154 pub fn reset(&mut self) {
156 self.cleared = true;
157 }
158
159 pub(crate) fn shown_index(&self) -> usize {
161 self.shown
162 }
163
164 pub(crate) fn view(&self, index: usize) -> &wgpu::TextureView {
166 &self.state[index].view
167 }
168
169 pub fn shown_texture(&self) -> &wgpu::Texture {
171 &self.state[self.shown].texture
172 }
173
174 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(¶ms),
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}