use wgpu::util::{TextureBlitter, TextureBlitterBuilder};
use wgpu::{
self, Adapter, BlendComponent, BlendFactor, BlendState, CompositeAlphaMode, CreateSurfaceError,
Device, Features, Instance, MemoryBudgetThresholds, MemoryHints, PresentMode, Queue, Surface,
SurfaceConfiguration, Texture, TextureFormat, TextureUsages, TextureView,
};
use winit::event_loop::OwnedDisplayHandle;
use crate::app_driver::WgpuLimits;
#[derive(Debug)]
pub(crate) struct RenderContext {
pub(crate) instance: Instance,
pub(crate) requested_features: Features,
pub(crate) requested_limits: WgpuLimits,
}
#[derive(Debug, Clone)]
pub(crate) struct DeviceHandle {
pub(crate) adapter: Adapter,
pub(crate) device: Device,
pub(crate) queue: Queue,
}
#[derive(Debug)]
pub(crate) struct RenderSurface {
pub(crate) surface: Surface<'static>,
pub(crate) config: SurfaceConfiguration,
pub(crate) target_texture: Texture,
pub(crate) target_view: TextureView,
pub(crate) blitter: TextureBlitter,
#[cfg(target_os = "macos")]
pub(crate) resizing: bool,
}
#[derive(Debug)]
pub(crate) enum RenderSurfaceError {
CreateSurface(CreateSurfaceError),
NoCompatibleDevice,
UnsupportedSurfaceFormat,
}
impl RenderContext {
pub(crate) fn new(display: OwnedDisplayHandle) -> Self {
let backends = wgpu::Backends::from_env().unwrap_or_default();
let flags = wgpu::InstanceFlags::from_build_config().with_env();
let backend_options = wgpu::BackendOptions::from_env_or_default();
let instance = Instance::new(wgpu::InstanceDescriptor {
backends,
flags,
backend_options,
memory_budget_thresholds: MemoryBudgetThresholds::default(),
display: Some(Box::new(display)),
});
Self {
instance,
requested_features: Features::empty(),
requested_limits: WgpuLimits::Default,
}
}
pub(crate) fn set_wgpu_device_options(&mut self, features: Features, limits: WgpuLimits) {
self.requested_features = features;
self.requested_limits = limits;
}
pub(crate) fn add_wgpu_features(&mut self, features: Features) {
self.requested_features |= features;
}
pub(crate) fn set_wgpu_limits(&mut self, limits: WgpuLimits) {
self.requested_limits = limits;
}
pub(crate) async fn create_surface(
&mut self,
device_handle: &DeviceHandle,
window: impl Into<wgpu::SurfaceTarget<'static>>,
width: u32,
height: u32,
present_mode: PresentMode,
) -> Result<RenderSurface, RenderSurfaceError> {
self.create_render_surface(
device_handle,
self.instance
.create_surface(window.into())
.map_err(RenderSurfaceError::CreateSurface)?,
width,
height,
present_mode,
)
.await
}
pub(crate) async fn create_render_surface(
&mut self,
device_handle: &DeviceHandle,
surface: Surface<'static>,
width: u32,
height: u32,
present_mode: PresentMode,
) -> Result<RenderSurface, RenderSurfaceError> {
let capabilities = surface.get_capabilities(&device_handle.adapter);
let format = capabilities
.formats
.into_iter()
.find(|it| matches!(it, TextureFormat::Rgba8Unorm | TextureFormat::Bgra8Unorm))
.ok_or(RenderSurfaceError::UnsupportedSurfaceFormat)?;
const PREMUL_BLEND_STATE: BlendState = BlendState {
alpha: BlendComponent::REPLACE,
color: BlendComponent {
src_factor: BlendFactor::SrcAlpha,
dst_factor: BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
};
let (alpha_mode, blitter) = if capabilities
.alpha_modes
.contains(&CompositeAlphaMode::PostMultiplied)
{
(
CompositeAlphaMode::PostMultiplied,
TextureBlitter::new(&device_handle.device, format),
)
} else if capabilities
.alpha_modes
.contains(&CompositeAlphaMode::PreMultiplied)
{
(
CompositeAlphaMode::PreMultiplied,
TextureBlitterBuilder::new(&device_handle.device, format)
.blend_state(PREMUL_BLEND_STATE)
.build(),
)
} else {
let texture_blitter =
if cfg!(windows) && device_handle.adapter.get_info().name.contains("AMD") {
tracing::info!(
"on Windows with AMD GPUs use premultiplied blitting even on opaque surface"
);
TextureBlitterBuilder::new(&device_handle.device, format)
.blend_state(PREMUL_BLEND_STATE)
.build()
} else {
TextureBlitter::new(&device_handle.device, format)
};
(CompositeAlphaMode::Auto, texture_blitter)
};
let config = SurfaceConfiguration {
usage: TextureUsages::RENDER_ATTACHMENT,
format,
width,
height,
present_mode,
desired_maximum_frame_latency: 2,
alpha_mode,
view_formats: vec![],
color_space: wgpu::SurfaceColorSpace::Auto,
};
let (target_texture, target_view) = create_targets(width, height, &device_handle.device);
let surface = RenderSurface {
surface,
config,
target_texture,
target_view,
blitter,
#[cfg(target_os = "macos")]
resizing: false,
};
self.configure_surface(device_handle, &surface);
Ok(surface)
}
pub(crate) fn resize_surface(
&self,
device_handle: &DeviceHandle,
surface: &mut RenderSurface,
width: u32,
height: u32,
) {
let (texture, view) = create_targets(width, height, &device_handle.device);
surface.target_texture = texture;
surface.target_view = view;
surface.config.width = width;
surface.config.height = height;
self.configure_surface(device_handle, surface);
}
#[cfg(target_os = "macos")]
pub(crate) fn on_window_resize_state_change(
&self,
device_handle: &DeviceHandle,
surface: &mut RenderSurface,
resizing: bool,
) {
if surface.resizing == resizing {
return;
}
#[allow(
unsafe_code,
reason = "We only mutate a backend-specific flag on the Metal HAL surface when the runtime backend matches Metal"
)]
unsafe {
if let Some(hal_surface) = surface.surface.as_hal::<::wgpu::hal::api::Metal>() {
let guard = hal_surface.render_layer().lock();
guard.setPresentsWithTransaction(resizing);
}
}
self.configure_surface(device_handle, surface);
surface.resizing = resizing;
}
pub(crate) fn set_present_mode(
&self,
device_handle: &DeviceHandle,
surface: &mut RenderSurface,
present_mode: PresentMode,
) {
surface.config.present_mode = present_mode;
self.configure_surface(device_handle, surface);
}
fn configure_surface(&self, device_handle: &DeviceHandle, surface: &RenderSurface) {
let device = &device_handle.device;
surface.surface.configure(device, &surface.config);
}
pub(crate) async fn create_device(
&mut self,
window: impl Into<wgpu::SurfaceTarget<'static>>,
) -> Result<DeviceHandle, RenderSurfaceError> {
let surface = self
.instance
.create_surface(window.into())
.map_err(RenderSurfaceError::CreateSurface)?;
let compatible_surface = Some(&surface);
let adapter =
wgpu::util::initialize_adapter_from_env_or_default(&self.instance, compatible_surface)
.await
.map_err(|_| RenderSurfaceError::NoCompatibleDevice)?;
let supported_features = adapter.features();
let required_limits = match &self.requested_limits {
WgpuLimits::Default => wgpu::Limits::default(),
WgpuLimits::Adapter => adapter.limits(),
WgpuLimits::Custom(limits) => *limits.clone(),
};
let requested_features = Features::CLEAR_TEXTURE | self.requested_features;
let required_features = supported_features & requested_features;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features,
required_limits,
memory_hints: MemoryHints::default(),
trace: wgpu::Trace::Off,
experimental_features: wgpu::ExperimentalFeatures::disabled(),
})
.await
.map_err(|_| RenderSurfaceError::NoCompatibleDevice)?;
drop(surface);
let device_handle = DeviceHandle {
adapter,
device,
queue,
};
Ok(device_handle)
}
}
fn create_targets(width: u32, height: u32, device: &Device) -> (Texture, TextureView) {
let target_texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
usage: TextureUsages::STORAGE_BINDING
| TextureUsages::TEXTURE_BINDING
| TextureUsages::COPY_DST
| TextureUsages::RENDER_ATTACHMENT,
format: TextureFormat::Rgba8Unorm,
view_formats: &[],
});
let target_view = target_texture.create_view(&wgpu::TextureViewDescriptor::default());
(target_texture, target_view)
}
impl core::fmt::Display for RenderSurfaceError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::CreateSurface(err) => write!(f, "creating surface failed: {err}"),
Self::NoCompatibleDevice => write!(f, "no compatible WGPU device found"),
Self::UnsupportedSurfaceFormat => write!(f, "unsupported surface format"),
}
}
}
impl std::error::Error for RenderSurfaceError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn requested_features_are_intersected_with_adapter_features() {
let supported = Features::CLEAR_TEXTURE;
let options_features = Features::TIMESTAMP_QUERY;
let requested_features = Features::CLEAR_TEXTURE | options_features;
let required_features = supported & requested_features;
assert_eq!(required_features, Features::CLEAR_TEXTURE);
}
}