|
| 1 | +use std::{num::NonZeroU32, path::Path}; |
| 2 | + |
| 3 | +use bevy_ecs::prelude::*; |
| 4 | +use bevy_log::info_span; |
| 5 | +use bevy_tasks::AsyncComputeTaskPool; |
| 6 | +use bevy_utils::HashMap; |
| 7 | +use bevy_window::WindowId; |
| 8 | +use parking_lot::Mutex; |
| 9 | +use thiserror::Error; |
| 10 | +use wgpu::{ |
| 11 | + CommandEncoder, Extent3d, ImageDataLayout, TextureFormat, COPY_BYTES_PER_ROW_ALIGNMENT, |
| 12 | +}; |
| 13 | + |
| 14 | +use crate::{prelude::Image, texture::TextureFormatPixelInfo}; |
| 15 | + |
| 16 | +use super::ExtractedWindows; |
| 17 | + |
| 18 | +pub type ScreenshotFn = Box<dyn FnOnce(Image) + Send + Sync>; |
| 19 | + |
| 20 | +/// A resource which allows for taking screenshots of the window. |
| 21 | +#[derive(Resource, Default)] |
| 22 | +pub struct ScreenshotManager { |
| 23 | + // this is in a mutex to enable extraction with only an immutable reference |
| 24 | + pub(crate) callbacks: Mutex<HashMap<WindowId, ScreenshotFn>>, |
| 25 | +} |
| 26 | + |
| 27 | +#[derive(Error, Debug)] |
| 28 | +#[error("A screenshot for this window has already been requested.")] |
| 29 | +pub struct ScreenshotAlreadyRequestedError; |
| 30 | + |
| 31 | +impl ScreenshotManager { |
| 32 | + /// Signals the renderer to take a screenshot of this frame. |
| 33 | + /// |
| 34 | + /// The given callback will eventually be called on one of the [`AsyncComputeTaskPool`]s threads. |
| 35 | + pub fn screenshot( |
| 36 | + &mut self, |
| 37 | + window: WindowId, |
| 38 | + callback: impl FnOnce(Image) + Send + Sync + 'static, |
| 39 | + ) -> Result<(), ScreenshotAlreadyRequestedError> { |
| 40 | + self.callbacks |
| 41 | + .get_mut() |
| 42 | + .try_insert(window, Box::new(callback)) |
| 43 | + .map(|_| ()) |
| 44 | + .map_err(|_| ScreenshotAlreadyRequestedError) |
| 45 | + } |
| 46 | + |
| 47 | + /// Signals the renderer to take a screenshot of this frame. |
| 48 | + /// |
| 49 | + /// The screenshot will eventually be saved to the given path, and the format will be derived from the extension. |
| 50 | + pub fn save_screenshot_to_disk( |
| 51 | + &mut self, |
| 52 | + window: WindowId, |
| 53 | + path: impl AsRef<Path>, |
| 54 | + ) -> Result<(), ScreenshotAlreadyRequestedError> { |
| 55 | + let path = path.as_ref().to_owned(); |
| 56 | + self.screenshot(window, |image| { |
| 57 | + image.try_into_dynamic().unwrap().save(path).unwrap(); |
| 58 | + }) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +pub(crate) fn align_byte_size(value: u32) -> u32 { |
| 63 | + value + (COPY_BYTES_PER_ROW_ALIGNMENT - (value % COPY_BYTES_PER_ROW_ALIGNMENT)) |
| 64 | +} |
| 65 | + |
| 66 | +pub(crate) fn get_aligned_size(width: u32, height: u32, pixel_size: u32) -> u32 { |
| 67 | + height * align_byte_size(width * pixel_size) |
| 68 | +} |
| 69 | + |
| 70 | +pub(crate) fn layout_data(width: u32, height: u32, format: TextureFormat) -> ImageDataLayout { |
| 71 | + ImageDataLayout { |
| 72 | + bytes_per_row: if height > 1 { |
| 73 | + // 1 = 1 row |
| 74 | + NonZeroU32::new(get_aligned_size(width, 1, format.pixel_size() as u32)) |
| 75 | + } else { |
| 76 | + None |
| 77 | + }, |
| 78 | + rows_per_image: None, |
| 79 | + ..Default::default() |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +pub(crate) fn submit_screenshot_commands(windows: &ExtractedWindows, encoder: &mut CommandEncoder) { |
| 84 | + for (window, texture) in windows |
| 85 | + .values() |
| 86 | + .filter_map(|w| w.swap_chain_texture.as_ref().map(|t| (w, t))) |
| 87 | + { |
| 88 | + if let Some(screenshot_buffer) = &window.screenshot_buffer { |
| 89 | + let width = window.physical_width; |
| 90 | + let height = window.physical_height; |
| 91 | + let texture_format = window.swap_chain_texture_format.unwrap(); |
| 92 | + let texture = &texture.get_surface_texture().unwrap().texture; |
| 93 | + |
| 94 | + encoder.copy_texture_to_buffer( |
| 95 | + texture.as_image_copy(), |
| 96 | + wgpu::ImageCopyBuffer { |
| 97 | + buffer: &screenshot_buffer, |
| 98 | + layout: crate::view::screenshot::layout_data(width, height, texture_format), |
| 99 | + }, |
| 100 | + Extent3d { |
| 101 | + width, |
| 102 | + height, |
| 103 | + ..Default::default() |
| 104 | + }, |
| 105 | + ); |
| 106 | + } |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +pub(crate) fn collect_screenshots(world: &mut World) { |
| 111 | + let _span = info_span!("collect_screenshots"); |
| 112 | + |
| 113 | + let mut windows = world.resource_mut::<ExtractedWindows>(); |
| 114 | + for window in windows.values_mut() { |
| 115 | + if let Some(screenshot_func) = window.screenshot_func.take() { |
| 116 | + let width = window.physical_width; |
| 117 | + let height = window.physical_height; |
| 118 | + let texture_format = window.swap_chain_texture_format.unwrap(); |
| 119 | + let pixel_size = texture_format.pixel_size(); |
| 120 | + let buffer = window.screenshot_buffer.take().unwrap(); |
| 121 | + |
| 122 | + let finish = async move { |
| 123 | + let (tx, rx) = async_channel::bounded(1); |
| 124 | + let buffer_slice = buffer.slice(..); |
| 125 | + // The polling for this map call is done every frame when the command queue is submitted. |
| 126 | + buffer_slice.map_async(wgpu::MapMode::Read, move |result| { |
| 127 | + let err = result.err(); |
| 128 | + if err.is_some() { |
| 129 | + panic!("{}", err.unwrap().to_string()); |
| 130 | + } |
| 131 | + tx.try_send(()).unwrap(); |
| 132 | + }); |
| 133 | + rx.recv().await.unwrap(); |
| 134 | + let data = buffer_slice.get_mapped_range(); |
| 135 | + // we immediately move the data to CPU memory to avoid holding the mapped view for long |
| 136 | + let mut result = Vec::from(&*data); |
| 137 | + drop(data); |
| 138 | + drop(buffer_slice); |
| 139 | + drop(buffer); |
| 140 | + |
| 141 | + if result.len() != ((width * height) as usize * pixel_size) { |
| 142 | + // Our buffer has been padded because we needed to align to a multiple of 256. |
| 143 | + // We remove this padding here |
| 144 | + let initial_row_bytes = width as usize * pixel_size; |
| 145 | + let buffered_row_bytes = align_byte_size(width * pixel_size as u32) as usize; |
| 146 | + |
| 147 | + let mut take_offset = buffered_row_bytes; |
| 148 | + let mut place_offset = initial_row_bytes; |
| 149 | + for _ in 1..height { |
| 150 | + result.copy_within( |
| 151 | + take_offset..take_offset + buffered_row_bytes, |
| 152 | + place_offset, |
| 153 | + ); |
| 154 | + take_offset += buffered_row_bytes; |
| 155 | + place_offset += initial_row_bytes; |
| 156 | + } |
| 157 | + result.truncate(initial_row_bytes * height as usize); |
| 158 | + } |
| 159 | + |
| 160 | + screenshot_func(Image::new( |
| 161 | + Extent3d { |
| 162 | + width, |
| 163 | + height, |
| 164 | + depth_or_array_layers: 1, |
| 165 | + }, |
| 166 | + wgpu::TextureDimension::D2, |
| 167 | + result, |
| 168 | + texture_format, |
| 169 | + )); |
| 170 | + }; |
| 171 | + |
| 172 | + AsyncComputeTaskPool::get().spawn(finish).detach(); |
| 173 | + } |
| 174 | + } |
| 175 | +} |
0 commit comments