masonry_winit 0.5.0

Data-oriented Rust UI design toolkit.
Documentation
// Copyright 2025 the Xilem Authors
// SPDX-License-Identifier: Apache-2.0

//! Simple helpers for managing wgpu state and surfaces.
//!
//! This module is based on [`vello::util`](https://docs.rs/vello/latest/vello/util/index.html) module with modifications
//! for transparent surfaces.

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;

/// Simple render context that maintains wgpu state for rendering the pipeline.
#[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,
}

/// Combination of surface and its configuration.
#[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 {
    /// Creates a render context for windows on the given `display`.
    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(),
            // Some backends require the display to be present, like GLES.
            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;
    }

    /// Creates a new surface for the specified window and dimensions.
    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
    }

    /// Creates a new render surface for the specified window and dimensions.
    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,
            },
        };
        // TODO: check if the window is transparent then set alpha_mode accordingly
        // also, Opaque mode may help in saving power.
        // blocked on winit not exposing a way to check for transparency
        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 {
            // TODO: check if the only available mode is Inherit then log info that postmultipled blit is being used
            // TODO: check if non-opaque base color is used on unsupported device then warn
            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)
    }

    /// Resizes the surface to the new dimensions.
    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);
        // TODO: Use clever resize semantics to avoid thrashing the memory allocator during a resize
        // especially important on metal.
        surface.target_texture = texture;
        surface.target_view = view;
        surface.config.width = width;
        surface.config.height = height;
        self.configure_surface(device_handle, surface);
    }

    /// Handles changes of the window resizing state for a surface.
    ///
    /// On macOS/Metal, interactive window resizing is driven by `CoreAnimation` transactions. During
    /// that phase, enabling `present_with_transaction` avoids visible jitter.
    #[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);
            }
        }

        // The flag affects presentation behavior and must be applied via reconfigure.
        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);
    }

    /// Creates a compatible device handle id.
    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)?;

        // We created a disposable surface to specify our wgpu device,
        // and now we immediately drop it.
        drop(surface);

        let device_handle = DeviceHandle {
            adapter,
            device,
            queue,
        };
        Ok(device_handle)
    }
}

/// Masonry renders into an intermediate texture because surface textures are not suitable for all
/// backend paths directly.
///
/// The Vello path needs storage binding for compute-based rendering, while the Vello Hybrid path
/// renders through a color attachment. We therefore provision one intermediate texture that
/// supports both backends and then blit to the surface.
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);
    }
}