Skip to main content

astrelis_render/
readback.rs

1//! GPU readback utilities for screenshot and framebuffer capture.
2//!
3//! This module provides utilities for reading back data from the GPU to the CPU:
4//! - Screenshot capture from textures
5//! - Framebuffer readback
6//! - Async GPU-to-CPU data transfer
7//! - PNG export
8//!
9//! # Example
10//!
11//! ```ignore
12//! use astrelis_render::*;
13//!
14//! // Capture a screenshot
15//! let readback = GpuReadback::from_texture(&context, &texture);
16//! let data = readback.read_async().await?;
17//!
18//! // Save to PNG
19//! readback.save_png("screenshot.png")?;
20//! ```
21
22use std::sync::Arc;
23
24use crate::GraphicsContext;
25
26/// GPU readback error.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum ReadbackError {
29    /// Buffer mapping failed
30    MapFailed(String),
31    /// Texture copy failed
32    CopyFailed(String),
33    /// Image encoding failed
34    EncodeFailed(String),
35    /// IO error
36    IoError(String),
37    /// Invalid dimensions
38    InvalidDimensions,
39    /// Unsupported format
40    UnsupportedFormat,
41}
42
43impl std::fmt::Display for ReadbackError {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Self::MapFailed(msg) => write!(f, "Buffer mapping failed: {}", msg),
47            Self::CopyFailed(msg) => write!(f, "Texture copy failed: {}", msg),
48            Self::EncodeFailed(msg) => write!(f, "Image encoding failed: {}", msg),
49            Self::IoError(msg) => write!(f, "IO error: {}", msg),
50            Self::InvalidDimensions => write!(f, "Invalid dimensions for readback"),
51            Self::UnsupportedFormat => write!(f, "Unsupported texture format for readback"),
52        }
53    }
54}
55
56impl std::error::Error for ReadbackError {}
57
58/// GPU readback handle for async data retrieval.
59pub struct GpuReadback {
60    /// Readback buffer
61    buffer: wgpu::Buffer,
62    /// Texture dimensions (width, height)
63    dimensions: (u32, u32),
64    /// Bytes per row (with padding)
65    bytes_per_row: u32,
66    /// Texture format
67    format: wgpu::TextureFormat,
68}
69
70impl GpuReadback {
71    /// Create a readback from a texture.
72    ///
73    /// This copies the texture to a staging buffer for CPU readback.
74    pub fn from_texture(context: Arc<GraphicsContext>, texture: &wgpu::Texture) -> Result<Self, ReadbackError> {
75        let size = texture.size();
76        let dimensions = (size.width, size.height);
77        let format = texture.format();
78
79        // Validate dimensions
80        if dimensions.0 == 0 || dimensions.1 == 0 {
81            return Err(ReadbackError::InvalidDimensions);
82        }
83
84        // Calculate bytes per row (must be aligned to 256 bytes)
85        let bytes_per_pixel = match format {
86            wgpu::TextureFormat::Rgba8Unorm
87            | wgpu::TextureFormat::Rgba8UnormSrgb
88            | wgpu::TextureFormat::Bgra8Unorm
89            | wgpu::TextureFormat::Bgra8UnormSrgb => 4,
90            wgpu::TextureFormat::Rgb10a2Unorm => 4,
91            _ => return Err(ReadbackError::UnsupportedFormat),
92        };
93
94        let unpadded_bytes_per_row = dimensions.0 * bytes_per_pixel;
95        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
96        let bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
97
98        // Create staging buffer
99        let buffer_size = (bytes_per_row * dimensions.1) as wgpu::BufferAddress;
100        let buffer = context.device().create_buffer(&wgpu::BufferDescriptor {
101            label: Some("readback_buffer"),
102            size: buffer_size,
103            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
104            mapped_at_creation: false,
105        });
106
107        // Copy texture to buffer
108        let mut encoder = context.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
109            label: Some("readback_encoder"),
110        });
111
112        encoder.copy_texture_to_buffer(
113            wgpu::TexelCopyTextureInfo {
114                texture,
115                mip_level: 0,
116                origin: wgpu::Origin3d::ZERO,
117                aspect: wgpu::TextureAspect::All,
118            },
119            wgpu::TexelCopyBufferInfo {
120                buffer: &buffer,
121                layout: wgpu::TexelCopyBufferLayout {
122                    offset: 0,
123                    bytes_per_row: Some(bytes_per_row),
124                    rows_per_image: Some(dimensions.1),
125                },
126            },
127            size,
128        );
129
130        context.queue().submit(Some(encoder.finish()));
131
132        Ok(Self {
133            buffer,
134            dimensions,
135            bytes_per_row,
136            format,
137        })
138    }
139
140    /// Read data from GPU (blocking).
141    ///
142    /// Returns raw RGBA bytes.
143    /// Note: This is a simplified blocking implementation.
144    /// For async usage, consider wrapping in async runtime.
145    pub fn read(&self) -> Result<Vec<u8>, ReadbackError> {
146        let buffer_slice = self.buffer.slice(..);
147
148        // Map the buffer
149        buffer_slice.map_async(wgpu::MapMode::Read, |_| {});
150
151        // Note: In real usage, you would poll the device here
152        // For now, we'll just proceed - the get_mapped_range will block
153
154        // Read data
155        let data = buffer_slice.get_mapped_range();
156        let bytes_per_pixel = 4; // RGBA
157        let mut result = Vec::with_capacity((self.dimensions.0 * self.dimensions.1 * bytes_per_pixel) as usize);
158
159        // Copy data, removing row padding
160        for y in 0..self.dimensions.1 {
161            let row_start = (y * self.bytes_per_row) as usize;
162            let row_end = row_start + (self.dimensions.0 * bytes_per_pixel) as usize;
163            result.extend_from_slice(&data[row_start..row_end]);
164        }
165
166        drop(data);
167        self.buffer.unmap();
168
169        Ok(result)
170    }
171
172    /// Save the readback data as a PNG file.
173    #[cfg(feature = "image")]
174    pub fn save_png(&self, path: impl AsRef<std::path::Path>) -> Result<(), ReadbackError> {
175        let data = self.read()?;
176
177        // Convert to image format
178        let img = image::RgbaImage::from_raw(self.dimensions.0, self.dimensions.1, data)
179            .ok_or(ReadbackError::EncodeFailed(
180                "Failed to create image from raw data".to_string(),
181            ))?;
182
183        // Save to PNG
184        img.save(path)
185            .map_err(|e| ReadbackError::IoError(format!("{}", e)))?;
186
187        Ok(())
188    }
189
190    /// Get the dimensions (width, height).
191    pub fn dimensions(&self) -> (u32, u32) {
192        self.dimensions
193    }
194
195    /// Get the texture format.
196    pub fn format(&self) -> wgpu::TextureFormat {
197        self.format
198    }
199}
200
201/// Extension trait for convenient screenshot capture.
202pub trait ReadbackExt {
203    /// Capture a screenshot from a texture.
204    fn capture_texture(&self, texture: &wgpu::Texture) -> Result<GpuReadback, ReadbackError>;
205}
206
207impl ReadbackExt for Arc<GraphicsContext> {
208    fn capture_texture(&self, texture: &wgpu::Texture) -> Result<GpuReadback, ReadbackError> {
209        GpuReadback::from_texture(self.clone(), texture)
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn test_readback_error_display() {
219        let err = ReadbackError::MapFailed("test".to_string());
220        assert!(format!("{}", err).contains("Buffer mapping failed"));
221
222        let err = ReadbackError::InvalidDimensions;
223        assert!(format!("{}", err).contains("Invalid dimensions"));
224    }
225
226    #[test]
227    fn test_bytes_per_row_alignment() {
228        // Test that bytes per row alignment is correct
229        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
230
231        // Width 100, 4 bytes per pixel = 400 bytes
232        let unpadded: u32 = 100 * 4;
233        let padded = unpadded.div_ceil(align) * align;
234
235        // Should be padded to next multiple of 256
236        assert_eq!(padded, 512);
237        assert_eq!(padded % align, 0);
238    }
239
240    #[test]
241    fn test_readback_dimensions() {
242        // We can't actually create a GPU readback without a real context,
243        // but we can test the error cases
244        assert!(matches!(
245            ReadbackError::InvalidDimensions,
246            ReadbackError::InvalidDimensions
247        ));
248    }
249}