use std::sync::{Arc, RwLock};
use super::pipeline_cache::{PipelineCache, PipelineCacheStore};
use super::{Renderer, RendererOptions};
use crate::cameras::Camera;
use crate::gpu::GpuContext;
use crate::scene::Scene;
pub struct SurfaceGpu {
gpu: GpuContext,
frames: Arc<RwLock<()>>,
cache: Option<PipelineCache>,
}
impl SurfaceGpu {
pub fn new() -> Result<Self, String> {
Ok(Self::from_context(GpuContext::headless_blocking()?))
}
pub fn from_context(gpu: GpuContext) -> Self {
Self {
gpu,
frames: Arc::new(RwLock::new(())),
cache: None,
}
}
pub fn with_pipeline_cache(mut self, store: impl PipelineCacheStore + 'static) -> Self {
self.cache = PipelineCache::open(&self.gpu.device, &self.gpu.adapter.get_info(), store);
self
}
pub fn with_opened_pipeline_cache(mut self, cache: Option<PipelineCache>) -> Self {
self.cache = cache;
self
}
pub fn save_pipeline_cache(&self) -> std::io::Result<bool> {
match &self.cache {
Some(cache) => cache.save(),
None => Ok(false),
}
}
pub fn pipeline_cache(&self) -> Option<&PipelineCache> {
self.cache.as_ref()
}
pub fn context(&self) -> &GpuContext {
&self.gpu
}
pub fn device(&self) -> &Arc<wgpu::Device> {
&self.gpu.device
}
pub fn queue(&self) -> &Arc<wgpu::Queue> {
&self.gpu.queue
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct SurfaceOptions {
pub msaa: u32,
pub lazy: bool,
pub present_mode: wgpu::PresentMode,
pub transparent: bool,
}
impl Default for SurfaceOptions {
fn default() -> Self {
Self {
msaa: 4,
lazy: false,
present_mode: wgpu::PresentMode::AutoVsync,
transparent: false,
}
}
}
impl SurfaceOptions {
pub fn msaa(mut self, samples: u32) -> Self {
self.msaa = samples;
self
}
pub fn lazy(mut self, lazy: bool) -> Self {
self.lazy = lazy;
self
}
pub fn present_mode(mut self, mode: wgpu::PresentMode) -> Self {
self.present_mode = mode;
self
}
pub fn transparent(mut self, transparent: bool) -> Self {
self.transparent = transparent;
self
}
}
enum Target {
Safe(Box<dyn Fn() -> wgpu::SurfaceTarget<'static> + Send>),
Raw(RawHandles),
}
struct RawHandles {
display: Option<wgpu::rwh::RawDisplayHandle>,
window: wgpu::rwh::RawWindowHandle,
}
unsafe impl Send for RawHandles {}
pub struct SurfaceRenderer {
renderer: Renderer,
surface: wgpu::Surface<'static>,
target: Target,
config: wgpu::SurfaceConfiguration,
gpu: GpuContext,
frames: Arc<RwLock<()>>,
unconfigured: bool,
warming: Option<super::PipelineWarmup>,
}
impl SurfaceRenderer {
pub fn new<W>(
gpu: &SurfaceGpu,
window: W,
width: u32,
height: u32,
options: SurfaceOptions,
) -> Result<Self, String>
where
W: wgpu::WindowHandle + wgpu::rwh::HasDisplayHandle + Clone + 'static,
{
let make = move || wgpu::SurfaceTarget::from(window.clone());
let surface = gpu
.gpu
.instance
.create_surface(make())
.map_err(|e| format!("window surface: {e}"))?;
Self::finish(
gpu,
surface,
Target::Safe(Box::new(make)),
width,
height,
options,
)
}
pub unsafe fn from_raw(
gpu: &SurfaceGpu,
display: Option<wgpu::rwh::RawDisplayHandle>,
window: wgpu::rwh::RawWindowHandle,
width: u32,
height: u32,
options: SurfaceOptions,
) -> Result<Self, String> {
let target = wgpu::SurfaceTargetUnsafe::RawHandle {
raw_display_handle: display,
raw_window_handle: window,
};
let surface = unsafe { gpu.gpu.instance.create_surface_unsafe(target) }
.map_err(|e| format!("window surface: {e}"))?;
Self::finish(
gpu,
surface,
Target::Raw(RawHandles { display, window }),
width,
height,
options,
)
}
fn finish(
gpu: &SurfaceGpu,
surface: wgpu::Surface<'static>,
target: Target,
width: u32,
height: u32,
options: SurfaceOptions,
) -> Result<Self, String> {
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "visionos"
))]
let _pool = super::layer::Pool::new();
let (width, height) = (width.max(1), height.max(1));
let caps = surface.get_capabilities(&gpu.gpu.adapter);
if caps.formats.is_empty() {
return Err(format!(
"the adapter ({}) cannot present to this window — open a GpuContext with a \
compatible surface and use SurfaceGpu::from_context",
gpu.gpu.adapter.get_info().name
));
}
let format = caps
.formats
.iter()
.copied()
.find(|f| f.is_srgb())
.unwrap_or(caps.formats[0]);
let alpha_preference: &[wgpu::CompositeAlphaMode] = if options.transparent {
&[
wgpu::CompositeAlphaMode::PreMultiplied,
wgpu::CompositeAlphaMode::PostMultiplied,
]
} else {
&[wgpu::CompositeAlphaMode::Opaque]
};
let alpha_mode = alpha_preference
.iter()
.chain(&[wgpu::CompositeAlphaMode::Auto])
.copied()
.find(|m| caps.alpha_modes.contains(m))
.unwrap_or(caps.alpha_modes[0]);
let present_mode = if caps.present_modes.contains(&options.present_mode)
|| matches!(
options.present_mode,
wgpu::PresentMode::AutoVsync | wgpu::PresentMode::AutoNoVsync
) {
options.present_mode
} else {
wgpu::PresentMode::Fifo
};
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format,
width,
height,
present_mode,
alpha_mode,
view_formats: vec![],
desired_maximum_frame_latency: 2,
color_space: wgpu::SurfaceColorSpace::Srgb,
};
let renderer_options = RendererOptions::default()
.lazy(options.lazy)
.pipeline_cache(&gpu.cache);
let mut renderer = Renderer::with_options(
Arc::clone(&gpu.gpu.device),
Arc::clone(&gpu.gpu.queue),
format,
width,
height,
renderer_options,
);
renderer.set_msaa(options.msaa);
let mut this = Self {
renderer,
surface,
target,
config,
gpu: GpuContext {
instance: gpu.gpu.instance.clone(),
adapter: gpu.gpu.adapter.clone(),
device: Arc::clone(&gpu.gpu.device),
queue: Arc::clone(&gpu.gpu.queue),
},
frames: gpu.frames.clone(),
unconfigured: true,
warming: None,
};
this.configure();
Ok(this)
}
pub fn resize(&mut self, width: u32, height: u32) {
let (width, height) = (width.max(1), height.max(1));
if (width, height) == (self.config.width, self.config.height) {
return;
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "visionos"
))]
let _pool = super::layer::Pool::new();
self.config.width = width;
self.config.height = height;
self.configure();
self.renderer.resize(width, height);
}
fn configure(&mut self) -> bool {
let _alone = self.frames.write().unwrap_or_else(|e| e.into_inner());
let scope = self
.gpu
.device
.push_error_scope(wgpu::ErrorFilter::Validation);
self.surface.configure(&self.gpu.device, &self.config);
self.unconfigured = pollster::block_on(scope.pop()).is_some();
!self.unconfigured
}
pub fn size(&self) -> (u32, u32) {
(self.config.width, self.config.height)
}
pub fn format(&self) -> wgpu::TextureFormat {
self.config.format
}
#[cfg(not(target_arch = "wasm32"))]
pub fn warm_in_background(
&mut self,
threads: usize,
states: &[crate::materials::RenderState],
) -> super::PipelineWarmup {
let warmup = self.renderer.warm_up_states(states);
warmup.spawn(threads);
self.warming = (!warmup.is_ready()).then(|| warmup.clone());
warmup
}
pub fn is_warming(&self) -> bool {
self.warming.as_ref().is_some_and(|w| !w.is_ready())
}
pub fn stop_waiting_for_warm_up(&mut self) {
self.warming = None;
}
pub fn render(&mut self, scene: &mut Scene, camera: &dyn Camera) -> bool {
use wgpu::CurrentSurfaceTexture as Acquired;
if self.is_warming() {
return false;
}
self.warming = None;
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "visionos"
))]
let _pool = super::layer::Pool::new();
if self.unconfigured && !self.configure() {
return false;
}
match self.surface.get_current_texture() {
Acquired::Success(frame) => {
self.draw(scene, camera, frame);
true
}
Acquired::Suboptimal(frame) => {
self.draw(scene, camera, frame);
self.unconfigured = true;
true
}
Acquired::Timeout | Acquired::Occluded => false,
Acquired::Outdated => {
self.configure();
false
}
Acquired::Lost => {
self.remake();
self.configure();
false
}
_ => false,
}
}
fn remake(&mut self) {
if cfg!(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "visionos"
)) {
return;
}
let surface = match &self.target {
Target::Safe(make) => self.gpu.instance.create_surface(make()),
Target::Raw(raw) => {
let target = wgpu::SurfaceTargetUnsafe::RawHandle {
raw_display_handle: raw.display,
raw_window_handle: raw.window,
};
unsafe { self.gpu.instance.create_surface_unsafe(target) }
}
};
if let Ok(surface) = surface {
self.surface = surface;
}
}
fn draw(&mut self, scene: &mut Scene, camera: &dyn Camera, frame: wgpu::SurfaceTexture) {
let _frame = self.frames.read().unwrap_or_else(|e| e.into_inner());
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
self.renderer.render(scene, camera, &view, false);
self.gpu.queue.present(frame);
}
pub fn renderer(&mut self) -> &mut Renderer {
&mut self.renderer
}
}
const _: () = {
const fn send_sync<T: Send + Sync>() {}
const fn send<T: Send>() {}
send_sync::<SurfaceGpu>();
send::<SurfaceRenderer>();
};