use crate::config::Backend;
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct Gpu {
pub device: wgpu::Device,
pub queue: wgpu::Queue,
}
impl Gpu {
pub fn describe(&self) -> String {
let i = self.device.adapter_info();
format!("{:?} · {}", i.backend, i.name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PixelRect {
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
impl PixelRect {
pub fn is_empty(&self) -> bool {
self.width == 0 || self.height == 0
}
}
pub struct Target<'a> {
pub view: &'a wgpu::TextureView,
pub format: wgpu::TextureFormat,
pub size: (u32, u32),
pub region: PixelRect,
}
pub trait GpuView {
fn prepare(&mut self, gpu: &Gpu, format: wgpu::TextureFormat);
fn render(&mut self, gpu: &Gpu, encoder: &mut wgpu::CommandEncoder, target: &Target<'_>);
fn changed(&self) -> bool {
true
}
}
pub type SharedView = Rc<RefCell<dyn GpuView>>;
pub fn share<V: GpuView + 'static>(view: V) -> (Rc<RefCell<V>>, SharedView) {
let typed = Rc::new(RefCell::new(view));
let shared: SharedView = typed.clone();
(typed, shared)
}
pub fn instance(backend: Backend, desc: wgpu::InstanceDescriptor) -> wgpu::Instance {
let backends = match backend {
Backend::Auto if std::env::var_os("WGPU_BACKEND").is_some() => desc.backends,
other => other.backends(),
};
wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..desc })
}
pub fn headless(backend: Backend) -> Result<Gpu, String> {
let instance = instance(
backend,
wgpu::InstanceDescriptor::new_without_display_handle_from_env(),
);
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
..Default::default()
}))
.map_err(|e| format!("no GPU adapter: {e}"))?;
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("scopekit"),
required_limits: wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits()),
..Default::default()
}))
.map_err(|e| format!("no GPU device: {e}"))?;
Ok(Gpu { device, queue })
}
pub const OFFSCREEN_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
pub struct Offscreen {
gpu: Gpu,
texture: Option<wgpu::Texture>,
prepared: bool,
}
impl Offscreen {
pub fn new(gpu: Gpu) -> Offscreen {
Offscreen {
gpu,
texture: None,
prepared: false,
}
}
pub fn gpu(&self) -> &Gpu {
&self.gpu
}
pub fn render(
&mut self,
view: &mut dyn GpuView,
width: u32,
height: u32,
) -> Result<Vec<u8>, String> {
let (w, h) = (width.max(1), height.max(1));
if !self.prepared {
view.prepare(&self.gpu, OFFSCREEN_FORMAT);
self.prepared = true;
}
let fits = self
.texture
.as_ref()
.is_some_and(|t| (t.width(), t.height()) == (w, h));
if !fits {
self.texture = Some(self.gpu.device.create_texture(&wgpu::TextureDescriptor {
label: Some("scopekit offscreen"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: OFFSCREEN_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
}));
}
let Some(texture) = &self.texture else {
return Err("no offscreen texture".into());
};
let tv = texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.gpu
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("scopekit offscreen"),
});
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("scopekit clear"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &tv,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
let target = Target {
view: &tv,
format: OFFSCREEN_FORMAT,
size: (w, h),
region: PixelRect {
x: 0,
y: 0,
width: w,
height: h,
},
};
view.render(&self.gpu, &mut encoder, &target);
read_back(&self.gpu, encoder, texture, w, h)
}
}
#[cfg(feature = "window")]
pub(crate) fn capture(
gpu: &Gpu,
view: &mut dyn GpuView,
format: wgpu::TextureFormat,
width: u32,
height: u32,
) -> Result<Vec<u8>, String> {
let (w, h) = (width.max(1), height.max(1));
let texture = gpu.device.create_texture(&wgpu::TextureDescriptor {
label: Some("scopekit capture"),
size: wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let tv = texture.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = gpu
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("scopekit capture"),
});
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("scopekit capture clear"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &tv,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
let target = Target {
view: &tv,
format,
size: (w, h),
region: PixelRect {
x: 0,
y: 0,
width: w,
height: h,
},
};
view.render(gpu, &mut encoder, &target);
let mut rgba = read_back(gpu, encoder, &texture, w, h)?;
if matches!(
format,
wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb
) {
for px in rgba.chunks_exact_mut(4) {
px.swap(0, 2);
}
}
for px in rgba.chunks_exact_mut(4) {
px[3] = 255;
}
Ok(rgba)
}
fn read_back(
gpu: &Gpu,
mut encoder: wgpu::CommandEncoder,
texture: &wgpu::Texture,
w: u32,
h: u32,
) -> Result<Vec<u8>, String> {
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let padded = (w * 4).div_ceil(align) * align;
let buffer = gpu.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("scopekit read-back"),
size: u64::from(padded) * u64::from(h),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
texture.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded),
rows_per_image: Some(h),
},
},
wgpu::Extent3d {
width: w,
height: h,
depth_or_array_layers: 1,
},
);
gpu.queue.submit(std::iter::once(encoder.finish()));
let slice = buffer.slice(..);
let (tx, rx) = std::sync::mpsc::channel();
slice.map_async(wgpu::MapMode::Read, move |r| {
let _ = tx.send(r);
});
gpu.device
.poll(wgpu::PollType::wait_indefinitely())
.map_err(|e| format!("read-back poll: {e}"))?;
rx.recv()
.map_err(|e| format!("read-back: {e}"))?
.map_err(|e| format!("read-back map: {e}"))?;
let mapped = slice
.get_mapped_range()
.map_err(|e| format!("read-back range: {e}"))?;
let row = (w * 4) as usize;
let mut out = Vec::with_capacity(row * h as usize);
for chunk in mapped.chunks(padded as usize).take(h as usize) {
out.extend_from_slice(&chunk[..row]);
}
drop(mapped);
buffer.unmap();
Ok(out)
}
pub fn render_to_rgba(
view: &mut dyn GpuView,
width: u32,
height: u32,
backend: Backend,
) -> Result<Vec<u8>, String> {
Offscreen::new(headless(backend)?).render(view, width, height)
}
#[derive(Clone, Default)]
pub struct Views {
list: Vec<(String, SharedView)>,
}
impl Views {
pub fn new() -> Views {
Views::default()
}
pub fn with(mut self, name: &str, view: SharedView) -> Views {
self.add(name, view);
self
}
pub fn add(&mut self, name: &str, view: SharedView) {
self.list.retain(|(n, _)| n != name);
self.list.push((name.to_string(), view));
}
pub fn get(&self, name: &str) -> Option<&SharedView> {
self.list.iter().find(|(n, _)| n == name).map(|(_, v)| v)
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &SharedView)> {
self.list.iter().map(|(n, v)| (n.as_str(), v))
}
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
}