Skip to main content

rouge_render/
testing.rs

1use crate::gpu::begin_pass;
2use crate::surface::{
3    BufferDesc, Frame, SharedBuffer, Sharing, SurfaceConfig, SurfaceCx, SurfaceError, SurfaceEvent,
4    SurfaceId, SurfaceProducer, SurfaceSource, surface_channel,
5};
6use bytemuck::{Pod, Zeroable, bytes_of};
7use thiserror::Error;
8use wgpu::{
9    BindGroup, BindGroupDescriptor, BindGroupEntry, Buffer, BufferDescriptor, BufferUsages,
10    Color as ClearColor, ColorTargetState, ColorWrites, CommandEncoderDescriptor, Device,
11    FragmentState, LoadOp, MultisampleState, PipelineCompilationOptions, PrimitiveState,
12    RenderPipeline, RenderPipelineDescriptor, ShaderModuleDescriptor, ShaderSource, TextureFormat,
13    TextureViewDescriptor, VertexState,
14};
15
16const PATTERN_WGSL: &str = include_str!("shaders/test_pattern.wgsl");
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum Pattern {
20    Solid([u8; 4]),
21    Quadrants {
22        top_left: [u8; 4],
23        top_right: [u8; 4],
24        bottom_left: [u8; 4],
25        bottom_right: [u8; 4],
26    },
27}
28
29impl Pattern {
30    pub const fn quadrants(colors: [[u8; 4]; 4]) -> Pattern {
31        let [top_left, top_right, bottom_left, bottom_right] = colors;
32        Pattern::Quadrants {
33            top_left,
34            top_right,
35            bottom_left,
36            bottom_right,
37        }
38    }
39
40    fn colors(self) -> [[u8; 4]; 4] {
41        match self {
42            Pattern::Solid(color) => [color; 4],
43            Pattern::Quadrants {
44                top_left,
45                top_right,
46                bottom_left,
47                bottom_right,
48            } => [top_left, top_right, bottom_left, bottom_right],
49        }
50    }
51}
52
53#[derive(Debug, Error)]
54pub enum TestSurfaceError {
55    #[error("the surface has no size yet")]
56    NoSize,
57    #[error("every buffer is still held by the compositor")]
58    NoFreeBuffer,
59    #[error(transparent)]
60    Surface(#[from] SurfaceError),
61}
62
63#[derive(Clone, Copy, Debug)]
64pub struct TestSurfaceBuilder {
65    desc: BufferDesc,
66    size: Option<(u32, u32)>,
67}
68
69impl Default for TestSurfaceBuilder {
70    fn default() -> Self {
71        TestSurfaceBuilder {
72            desc: BufferDesc::new(0, 0),
73            size: None,
74        }
75    }
76}
77
78impl TestSurfaceBuilder {
79    pub fn buffers(mut self, buffers: u32) -> Self {
80        self.desc = self.desc.count(buffers);
81        self
82    }
83
84    pub fn sharing(mut self, sharing: Sharing) -> Self {
85        self.desc = self.desc.sharing(sharing);
86        self
87    }
88
89    pub fn format(mut self, format: TextureFormat) -> Self {
90        self.desc = self.desc.format(format);
91        self
92    }
93
94    pub fn size(mut self, width: u32, height: u32) -> Self {
95        self.size = Some((width, height));
96        self
97    }
98
99    pub fn build(self) -> (TestSurface, SurfaceSource) {
100        let (producer, source) = surface_channel();
101        let surface = TestSurface {
102            producer,
103            settings: self,
104            config: None,
105            painter: None,
106            detached: false,
107            log: Vec::new(),
108        };
109        (surface, source)
110    }
111}
112
113#[repr(C)]
114#[derive(Clone, Copy, Pod, Zeroable)]
115struct PatternUniform {
116    colors: [[f32; 4]; 4],
117    flip: [f32; 4],
118}
119
120struct Painter {
121    pipeline: RenderPipeline,
122    uniform: Buffer,
123    bind_group: BindGroup,
124}
125
126impl Painter {
127    fn new(device: &Device, format: TextureFormat) -> Painter {
128        let module = device.create_shader_module(ShaderModuleDescriptor {
129            label: Some("rouge test pattern"),
130            source: ShaderSource::Wgsl(PATTERN_WGSL.into()),
131        });
132        let pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
133            label: Some("rouge test pattern"),
134            layout: None,
135            vertex: VertexState {
136                module: &module,
137                entry_point: Some("vs_main"),
138                compilation_options: PipelineCompilationOptions::default(),
139                buffers: &[],
140            },
141            primitive: PrimitiveState::default(),
142            depth_stencil: None,
143            multisample: MultisampleState::default(),
144            fragment: Some(FragmentState {
145                module: &module,
146                entry_point: Some("fs_main"),
147                compilation_options: PipelineCompilationOptions::default(),
148                targets: &[Some(ColorTargetState {
149                    format,
150                    blend: None,
151                    write_mask: ColorWrites::ALL,
152                })],
153            }),
154            multiview_mask: None,
155            cache: None,
156        });
157        let uniform = device.create_buffer(&BufferDescriptor {
158            label: Some("rouge test pattern"),
159            size: size_of::<PatternUniform>() as u64,
160            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
161            mapped_at_creation: false,
162        });
163        let bind_group = device.create_bind_group(&BindGroupDescriptor {
164            label: Some("rouge test pattern"),
165            layout: &pipeline.get_bind_group_layout(0),
166            entries: &[BindGroupEntry {
167                binding: 0,
168                resource: uniform.as_entire_binding(),
169            }],
170        });
171        Painter {
172            pipeline,
173            uniform,
174            bind_group,
175        }
176    }
177}
178
179pub struct TestSurface {
180    producer: SurfaceProducer,
181    settings: TestSurfaceBuilder,
182    config: Option<SurfaceConfig>,
183    painter: Option<Painter>,
184    detached: bool,
185    log: Vec<SurfaceEvent>,
186}
187
188impl TestSurface {
189    pub fn builder() -> TestSurfaceBuilder {
190        TestSurfaceBuilder::default()
191    }
192
193    pub fn new() -> (TestSurface, SurfaceSource) {
194        TestSurfaceBuilder::default().build()
195    }
196
197    pub fn pump(&mut self) -> Result<&[SurfaceEvent], TestSurfaceError> {
198        self.log.clear();
199        while let Some(event) = self.producer.try_recv() {
200            match event {
201                SurfaceEvent::Configure(config) => self.config = Some(config),
202                SurfaceEvent::Detached => self.detached = true,
203                SurfaceEvent::Attached | SurfaceEvent::FrameRequest { .. } => {}
204            }
205            self.log.push(event);
206        }
207        self.configure()?;
208        Ok(&self.log)
209    }
210
211    pub fn present(&mut self, pattern: Pattern) -> Result<(), TestSurfaceError> {
212        self.present_frame(pattern, |frame| frame)
213    }
214
215    pub fn present_frame(
216        &mut self,
217        pattern: Pattern,
218        frame: impl FnOnce(Frame) -> Frame,
219    ) -> Result<(), TestSurfaceError> {
220        self.render(pattern, false, frame)
221    }
222
223    pub fn present_flipped(
224        &mut self,
225        pattern: Pattern,
226        frame: impl FnOnce(Frame) -> Frame,
227    ) -> Result<(), TestSurfaceError> {
228        self.render(pattern, true, frame)
229    }
230
231    pub fn request_frame(&self) {
232        self.producer.request_frame();
233    }
234
235    pub fn fail(&self, error: SurfaceError) {
236        self.producer.fail(error);
237    }
238
239    pub fn id(&self) -> SurfaceId {
240        self.producer.id()
241    }
242
243    pub fn config(&self) -> Option<SurfaceConfig> {
244        self.config
245    }
246
247    pub fn cx(&self) -> Option<&SurfaceCx> {
248        self.producer.cx()
249    }
250
251    pub fn free_buffers(&self) -> usize {
252        self.producer.free_buffers()
253    }
254
255    pub fn buffers(&self) -> &[SharedBuffer] {
256        self.producer.buffers()
257    }
258
259    pub fn is_detached(&self) -> bool {
260        self.detached
261    }
262
263    fn size(&self) -> Option<(u32, u32)> {
264        self.settings.size.or_else(|| {
265            let config = self.config?;
266            (config.width > 0 && config.height > 0).then_some((config.width, config.height))
267        })
268    }
269
270    fn configure(&mut self) -> Result<(), TestSurfaceError> {
271        let (Some(_), Some((width, height))) = (self.producer.cx(), self.size()) else {
272            return Ok(());
273        };
274        let desc = BufferDesc {
275            width,
276            height,
277            ..self.settings.desc
278        };
279        Ok(self.producer.configure(desc)?)
280    }
281
282    fn render(
283        &mut self,
284        pattern: Pattern,
285        flip: bool,
286        frame: impl FnOnce(Frame) -> Frame,
287    ) -> Result<(), TestSurfaceError> {
288        self.configure()?;
289        let cx = self.producer.cx().ok_or(SurfaceError::NotAttached)?.clone();
290        if self.size().is_none() {
291            return Err(TestSurfaceError::NoSize);
292        }
293        let (buffer, shared) = self
294            .producer
295            .acquire()
296            .ok_or(TestSurfaceError::NoFreeBuffer)?;
297        let texture = shared.texture();
298        let painter = self
299            .painter
300            .get_or_insert_with(|| Painter::new(cx.device(), texture.format()));
301        let uniform = PatternUniform {
302            colors: pattern
303                .colors()
304                .map(|color| color.map(|channel| f32::from(channel) / 255.0)),
305            flip: [f32::from(u8::from(flip)), 0.0, 0.0, 0.0],
306        };
307        cx.queue()
308            .write_buffer(&painter.uniform, 0, bytes_of(&uniform));
309        let view = texture.create_view(&TextureViewDescriptor::default());
310        let mut encoder = cx
311            .device()
312            .create_command_encoder(&CommandEncoderDescriptor::default());
313        let mut pass = begin_pass(&mut encoder, &view, LoadOp::Clear(ClearColor::TRANSPARENT));
314        pass.set_pipeline(&painter.pipeline);
315        pass.set_bind_group(0, &painter.bind_group, &[]);
316        pass.draw(0..3, 0..1);
317        drop(pass);
318        cx.queue().submit([encoder.finish()]);
319        self.producer.submit(frame(Frame::new(buffer)));
320        Ok(())
321    }
322}