1use std::fmt;
4
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
7pub enum ChannelSwizzle {
8 #[default]
10 None,
11 SwapRB,
13}
14
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17pub struct ReadbackOptions {
18 pub swizzle: ChannelSwizzle,
19 pub y_flip: bool,
20 pub unpremultiply: bool,
21}
22
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
25pub struct DepthReadbackOptions {
26 pub y_flip: bool,
27}
28
29#[derive(Debug)]
31pub enum ReadbackError {
32 NotInitialized,
33 Poll(wgpu::PollError),
34 ChannelClosed(std::sync::mpsc::RecvError),
35 BufferAsync(wgpu::BufferAsyncError),
36 MapRange(wgpu::MapRangeError),
37}
38
39impl fmt::Display for ReadbackError {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 match self {
42 Self::NotInitialized => write!(f, "readback staging buffer is not initialized"),
43 Self::Poll(err) => write!(f, "device poll failed during readback: {err}"),
44 Self::ChannelClosed(err) => write!(f, "buffer map callback channel closed: {err}"),
45 Self::BufferAsync(err) => write!(f, "buffer map async operation failed: {err}"),
46 Self::MapRange(err) => write!(f, "failed to map staging buffer range: {err}"),
47 }
48 }
49}
50
51impl std::error::Error for ReadbackError {
52 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
53 match self {
54 Self::NotInitialized => None,
55 Self::Poll(err) => Some(err),
56 Self::ChannelClosed(err) => Some(err),
57 Self::BufferAsync(err) => Some(err),
58 Self::MapRange(err) => Some(err),
59 }
60 }
61}
62
63fn copy_texture_to_staging_buffer(
64 encoder: &mut wgpu::CommandEncoder,
65 texture: &wgpu::Texture,
66 aspect: wgpu::TextureAspect,
67 buffer: &wgpu::Buffer,
68 width: u32,
69 height: u32,
70 row_pitch: u32,
71) {
72 encoder.copy_texture_to_buffer(
73 wgpu::TexelCopyTextureInfo {
74 texture,
75 mip_level: 0,
76 origin: wgpu::Origin3d::ZERO,
77 aspect,
78 },
79 wgpu::TexelCopyBufferInfo {
80 buffer,
81 layout: wgpu::TexelCopyBufferLayout {
82 offset: 0,
83 bytes_per_row: Some(row_pitch),
84 rows_per_image: Some(height),
85 },
86 },
87 wgpu::Extent3d {
88 width,
89 height,
90 depth_or_array_layers: 1,
91 },
92 );
93}
94
95fn map_buffer_sync(
96 device: &wgpu::Device,
97 buffer: &wgpu::Buffer,
98 on_mapped: impl FnOnce(&[u8]),
99) -> Result<(), ReadbackError> {
100 let slice = buffer.slice(..);
101 let (tx, rx) = std::sync::mpsc::channel();
102 slice.map_async(wgpu::MapMode::Read, move |res| {
103 let _ = tx.send(res);
104 });
105
106 #[cfg(target_arch = "wasm32")]
107 let _ = device;
108
109 #[cfg(not(target_arch = "wasm32"))]
110 device
111 .poll(wgpu::PollType::wait_indefinitely())
112 .map_err(ReadbackError::Poll)?;
113
114 rx.recv()
115 .map_err(ReadbackError::ChannelClosed)?
116 .map_err(ReadbackError::BufferAsync)?;
117
118 {
119 let mapped = slice.get_mapped_range().map_err(ReadbackError::MapRange)?;
120 on_mapped(&mapped);
121 }
122 buffer.unmap();
123 Ok(())
124}
125
126pub struct ColorReadbackBuffer {
128 pub buffer: wgpu::Buffer,
129 pub width: u32,
130 pub height: u32,
131 pub row_pitch: u32,
132 pub unpadded_row_bytes: u32,
133}
134
135impl ColorReadbackBuffer {
136 pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
138 let unpadded_row_bytes = width * 4;
139 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
140 let row_pitch = unpadded_row_bytes.next_multiple_of(align);
141 let buffer_size = (row_pitch * height) as u64;
142
143 let buffer = device.create_buffer(&wgpu::BufferDescriptor {
144 label: Some("graphics_core_color_readback_buffer"),
145 size: buffer_size,
146 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
147 mapped_at_creation: false,
148 });
149
150 Self {
151 buffer,
152 width,
153 height,
154 row_pitch,
155 unpadded_row_bytes,
156 }
157 }
158
159 pub fn copy_from_texture(&self, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) {
161 copy_texture_to_staging_buffer(
162 encoder,
163 texture,
164 wgpu::TextureAspect::All,
165 &self.buffer,
166 self.width,
167 self.height,
168 self.row_pitch,
169 );
170 }
171}
172
173pub struct ReadbackSurface {
178 staging: Option<ColorReadbackBuffer>,
179 cached_pixels: Vec<u8>,
180 width: u32,
181 height: u32,
182 options: ReadbackOptions,
183}
184
185impl ReadbackSurface {
186 pub fn new(options: ReadbackOptions) -> Self {
187 Self {
188 staging: None,
189 cached_pixels: Vec::new(),
190 width: 0,
191 height: 0,
192 options,
193 }
194 }
195
196 pub fn options(&self) -> ReadbackOptions {
197 self.options
198 }
199
200 pub fn set_options(&mut self, options: ReadbackOptions) {
201 self.options = options;
202 }
203
204 pub fn width(&self) -> u32 {
205 self.width
206 }
207
208 pub fn height(&self) -> u32 {
209 self.height
210 }
211
212 pub fn unpadded_row_pitch(&self) -> u32 {
213 self.width * 4
214 }
215
216 pub fn size_bytes(&self) -> usize {
217 self.cached_pixels.len()
218 }
219
220 pub fn cached_pixels(&self) -> &[u8] {
221 &self.cached_pixels
222 }
223
224 pub fn ensure_dimensions(&mut self, device: &wgpu::Device, width: u32, height: u32) -> bool {
227 let w = width.max(1);
228 let h = height.max(1);
229 if self.staging.is_some() && self.width == w && self.height == h {
230 return false;
231 }
232 self.staging = Some(ColorReadbackBuffer::new(device, w, h));
233 self.cached_pixels.resize((w * h * 4) as usize, 0);
234 self.width = w;
235 self.height = h;
236 true
237 }
238
239 pub fn copy_from_texture(
241 &self,
242 encoder: &mut wgpu::CommandEncoder,
243 texture: &wgpu::Texture,
244 ) -> Result<(), ReadbackError> {
245 let staging = self.staging.as_ref().ok_or(ReadbackError::NotInitialized)?;
246 staging.copy_from_texture(encoder, texture);
247 Ok(())
248 }
249
250 pub fn map_and_repack(&mut self, device: &wgpu::Device) -> Result<&[u8], ReadbackError> {
252 let staging = self.staging.as_ref().ok_or(ReadbackError::NotInitialized)?;
253 let width = self.width;
254 let height = self.height;
255 let row_pitch = staging.row_pitch;
256 let options = self.options;
257 let cached = &mut self.cached_pixels;
258
259 map_buffer_sync(device, &staging.buffer, |mapped| {
260 repack_rgba_rows(mapped, cached, width, height, row_pitch, options);
261 })?;
262 Ok(&self.cached_pixels)
263 }
264
265 pub fn readback_sync(
267 &mut self,
268 device: &wgpu::Device,
269 queue: &wgpu::Queue,
270 texture: &wgpu::Texture,
271 ) -> Result<&[u8], ReadbackError> {
272 self.ensure_dimensions(device, texture.width(), texture.height());
273 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
274 label: Some("graphics_core_readback_encoder"),
275 });
276 self.copy_from_texture(&mut encoder, texture)?;
277 queue.submit(std::iter::once(encoder.finish()));
278 self.map_and_repack(device)
279 }
280}
281
282pub fn repack_rgba_rows(
285 src_padded: &[u8],
286 dst: &mut [u8],
287 width: u32,
288 height: u32,
289 padded_row_pitch: u32,
290 options: ReadbackOptions,
291) {
292 let w = width as usize;
293 let h = height as usize;
294 let unpadded = w * 4;
295 let padded = padded_row_pitch as usize;
296 debug_assert!(src_padded.len() >= h.saturating_sub(1) * padded + unpadded);
297 debug_assert!(dst.len() >= h * unpadded);
298
299 for y in 0..h {
300 let dst_y = if options.y_flip { h - 1 - y } else { y };
301 let src_row = &src_padded[y * padded..y * padded + unpadded];
302 let dst_row = &mut dst[dst_y * unpadded..dst_y * unpadded + unpadded];
303
304 if options.swizzle == ChannelSwizzle::None && !options.unpremultiply {
305 dst_row.copy_from_slice(src_row);
306 continue;
307 }
308
309 for (src_px, dst_px) in src_row.chunks_exact(4).zip(dst_row.chunks_exact_mut(4)) {
310 let (mut c0, mut c1, mut c2, a) = (src_px[0], src_px[1], src_px[2], src_px[3]);
311 if options.unpremultiply {
312 if a == 0 {
313 c0 = 0;
314 c1 = 0;
315 c2 = 0;
316 } else if a < 255 {
317 let a32 = a as u32;
318 c0 = ((c0 as u32 * 255 + a32 / 2) / a32).min(255) as u8;
319 c1 = ((c1 as u32 * 255 + a32 / 2) / a32).min(255) as u8;
320 c2 = ((c2 as u32 * 255 + a32 / 2) / a32).min(255) as u8;
321 }
322 }
323
324 match options.swizzle {
325 ChannelSwizzle::None => {
326 dst_px[0] = c0;
327 dst_px[1] = c1;
328 dst_px[2] = c2;
329 dst_px[3] = a;
330 }
331 ChannelSwizzle::SwapRB => {
332 dst_px[0] = c2;
333 dst_px[1] = c1;
334 dst_px[2] = c0;
335 dst_px[3] = a;
336 }
337 }
338 }
339 }
340}
341
342pub struct DepthReadbackBuffer {
344 pub buffer: wgpu::Buffer,
345 pub width: u32,
346 pub height: u32,
347 pub row_pitch: u32,
348 pub unpadded_row_bytes: u32,
349}
350
351impl DepthReadbackBuffer {
352 pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
353 let unpadded_row_bytes = width * std::mem::size_of::<f32>() as u32;
354 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
355 let row_pitch = unpadded_row_bytes.next_multiple_of(align);
356 let buffer_size = (row_pitch * height) as u64;
357
358 let buffer = device.create_buffer(&wgpu::BufferDescriptor {
359 label: Some("graphics_core_depth_readback_buffer"),
360 size: buffer_size,
361 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
362 mapped_at_creation: false,
363 });
364
365 Self {
366 buffer,
367 width,
368 height,
369 row_pitch,
370 unpadded_row_bytes,
371 }
372 }
373
374 pub fn copy_from_texture(&self, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) {
376 copy_texture_to_staging_buffer(
377 encoder,
378 texture,
379 wgpu::TextureAspect::DepthOnly,
380 &self.buffer,
381 self.width,
382 self.height,
383 self.row_pitch,
384 );
385 }
386}
387
388pub struct DepthReadbackSurface {
390 staging: Option<DepthReadbackBuffer>,
391 cached_depths: Vec<f32>,
392 width: u32,
393 height: u32,
394 options: DepthReadbackOptions,
395}
396
397impl DepthReadbackSurface {
398 pub fn new(options: DepthReadbackOptions) -> Self {
399 Self {
400 staging: None,
401 cached_depths: Vec::new(),
402 width: 0,
403 height: 0,
404 options,
405 }
406 }
407
408 pub fn options(&self) -> DepthReadbackOptions {
409 self.options
410 }
411
412 pub fn set_options(&mut self, options: DepthReadbackOptions) {
413 self.options = options;
414 }
415
416 pub fn width(&self) -> u32 {
417 self.width
418 }
419
420 pub fn height(&self) -> u32 {
421 self.height
422 }
423
424 pub fn cached_depths(&self) -> &[f32] {
425 &self.cached_depths
426 }
427
428 pub fn cached_bytes(&self) -> &[u8] {
429 bytemuck::cast_slice(&self.cached_depths)
430 }
431
432 pub fn ensure_dimensions(&mut self, device: &wgpu::Device, width: u32, height: u32) -> bool {
435 let w = width.max(1);
436 let h = height.max(1);
437 if self.staging.is_some() && self.width == w && self.height == h {
438 return false;
439 }
440 self.staging = Some(DepthReadbackBuffer::new(device, w, h));
441 self.cached_depths.resize((w * h) as usize, 1.0);
442 self.width = w;
443 self.height = h;
444 true
445 }
446
447 pub fn copy_from_texture(
449 &self,
450 encoder: &mut wgpu::CommandEncoder,
451 depth_texture: &wgpu::Texture,
452 ) -> Result<(), ReadbackError> {
453 let staging = self.staging.as_ref().ok_or(ReadbackError::NotInitialized)?;
454 staging.copy_from_texture(encoder, depth_texture);
455 Ok(())
456 }
457
458 pub fn map_and_repack(&mut self, device: &wgpu::Device) -> Result<&[f32], ReadbackError> {
460 let staging = self.staging.as_ref().ok_or(ReadbackError::NotInitialized)?;
461 let width = self.width;
462 let height = self.height;
463 let row_pitch = staging.row_pitch;
464 let options = self.options;
465 let cached = &mut self.cached_depths;
466
467 map_buffer_sync(device, &staging.buffer, |mapped| {
468 repack_depth_rows(mapped, cached, width, height, row_pitch, options);
469 })?;
470 Ok(&self.cached_depths)
471 }
472
473 pub fn readback_sync(
475 &mut self,
476 device: &wgpu::Device,
477 queue: &wgpu::Queue,
478 depth_texture: &wgpu::Texture,
479 ) -> Result<&[f32], ReadbackError> {
480 self.ensure_dimensions(device, depth_texture.width(), depth_texture.height());
481 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
482 label: Some("graphics_core_depth_readback_encoder"),
483 });
484 self.copy_from_texture(&mut encoder, depth_texture)?;
485 queue.submit(std::iter::once(encoder.finish()));
486 self.map_and_repack(device)
487 }
488}
489
490pub fn repack_depth_rows(
492 src_padded: &[u8],
493 dst: &mut [f32],
494 width: u32,
495 height: u32,
496 padded_row_pitch: u32,
497 options: DepthReadbackOptions,
498) {
499 let w = width as usize;
500 let h = height as usize;
501 let unpadded_bytes = w * std::mem::size_of::<f32>();
502 let padded = padded_row_pitch as usize;
503 debug_assert!(src_padded.len() >= h.saturating_sub(1) * padded + unpadded_bytes);
504 debug_assert!(dst.len() >= h * w);
505
506 for y in 0..h {
507 let dst_y = if options.y_flip { h - 1 - y } else { y };
508 let src_bytes = &src_padded[y * padded..y * padded + unpadded_bytes];
509 let dst_row = &mut dst[dst_y * w..dst_y * w + w];
510 bytemuck::cast_slice_mut(dst_row).copy_from_slice(src_bytes);
511 }
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517
518 #[test]
519 fn repack_unpads_swizzles_flips_and_unpremultiplies() {
520 let width = 2;
521 let height = 2;
522 let pitch = 256;
523 let mut padded = vec![0u8; pitch * height];
524
525 padded[0..4].copy_from_slice(&[64, 32, 0, 128]);
527 padded[4..8].copy_from_slice(&[10, 20, 30, 255]);
528 padded[pitch..pitch + 4].copy_from_slice(&[99, 88, 77, 0]);
530 padded[pitch + 4..pitch + 8].copy_from_slice(&[255, 128, 64, 255]);
531
532 let mut dst = vec![0u8; width * height * 4];
533 repack_rgba_rows(
534 &padded,
535 &mut dst,
536 width as u32,
537 height as u32,
538 pitch as u32,
539 ReadbackOptions {
540 swizzle: ChannelSwizzle::SwapRB,
541 y_flip: true,
542 unpremultiply: true,
543 },
544 );
545
546 assert_eq!(&dst[0..4], &[0, 0, 0, 0]);
549 assert_eq!(&dst[4..8], &[64, 128, 255, 255]);
551 assert_eq!(&dst[8..12], &[0, 64, 128, 128]);
553 assert_eq!(&dst[12..16], &[30, 20, 10, 255]);
555
556 let mut fast_dst = vec![0u8; width * height * 4];
558 repack_rgba_rows(
559 &padded,
560 &mut fast_dst,
561 width as u32,
562 height as u32,
563 pitch as u32,
564 ReadbackOptions {
565 swizzle: ChannelSwizzle::None,
566 y_flip: false,
567 unpremultiply: false,
568 },
569 );
570 assert_eq!(&fast_dst[0..4], &[64, 32, 0, 128]);
571 assert_eq!(&fast_dst[4..8], &[10, 20, 30, 255]);
572 assert_eq!(&fast_dst[8..12], &[99, 88, 77, 0]);
573 assert_eq!(&fast_dst[12..16], &[255, 128, 64, 255]);
574 }
575
576 #[test]
577 fn repack_depth_rows_unpads_and_flips() {
578 let width = 3;
579 let height = 2;
580 let pitch = 256;
581 let mut padded = vec![0u8; pitch * height];
582
583 let row0 = [0.1_f32, 0.25_f32, 0.5_f32];
584 let row1 = [0.75_f32, 0.9_f32, 1.0_f32];
585 padded[0..12].copy_from_slice(bytemuck::cast_slice(&row0));
586 padded[pitch..pitch + 12].copy_from_slice(bytemuck::cast_slice(&row1));
587
588 let mut dst_no_flip = vec![0.0_f32; width * height];
589 repack_depth_rows(
590 &padded,
591 &mut dst_no_flip,
592 width as u32,
593 height as u32,
594 pitch as u32,
595 DepthReadbackOptions { y_flip: false },
596 );
597 assert_eq!(dst_no_flip, vec![0.1, 0.25, 0.5, 0.75, 0.9, 1.0]);
598
599 let mut dst_flip = vec![0.0_f32; width * height];
600 repack_depth_rows(
601 &padded,
602 &mut dst_flip,
603 width as u32,
604 height as u32,
605 pitch as u32,
606 DepthReadbackOptions { y_flip: true },
607 );
608 assert_eq!(dst_flip, vec![0.75, 0.9, 1.0, 0.1, 0.25, 0.5]);
609 }
610}