summaryrefslogtreecommitdiffstats
path: root/wgpu/src/renderer/target.rs
blob: 569f3c623fea72ffae3bed8751f37bdd14909e98 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use crate::{Renderer, Transformation};

use raw_window_handle::HasRawWindowHandle;

/// A rendering target.
#[derive(Debug)]
pub struct Target {
    surface: wgpu::Surface,
    width: u16,
    height: u16,
    dpi: f32,
    transformation: Transformation,
    swap_chain: wgpu::SwapChain,
}

impl Target {
    pub(crate) fn dimensions(&self) -> (u16, u16) {
        (self.width, self.height)
    }

    pub(crate) fn dpi(&self) -> f32 {
        self.dpi
    }

    pub(crate) fn transformation(&self) -> Transformation {
        self.transformation
    }

    pub(crate) fn next_frame(&mut self) -> wgpu::SwapChainOutput<'_> {
        self.swap_chain.get_next_texture()
    }
}

impl iced_native::renderer::Target for Target {
    type Renderer = Renderer;

    fn new<W: HasRawWindowHandle>(
        window: &W,
        width: u16,
        height: u16,
        dpi: f32,
        renderer: &Renderer,
    ) -> Target {
        let surface = wgpu::Surface::create(window);
        let swap_chain =
            new_swap_chain(&surface, width, height, &renderer.device);

        Target {
            surface,
            width,
            height,
            dpi,
            transformation: Transformation::orthographic(width, height),
            swap_chain,
        }
    }

    fn resize(
        &mut self,
        width: u16,
        height: u16,
        dpi: f32,
        renderer: &Renderer,
    ) {
        self.width = width;
        self.height = height;
        self.dpi = dpi;
        self.transformation = Transformation::orthographic(width, height);
        self.swap_chain =
            new_swap_chain(&self.surface, width, height, &renderer.device);
    }
}

fn new_swap_chain(
    surface: &wgpu::Surface,
    width: u16,
    height: u16,
    device: &wgpu::Device,
) -> wgpu::SwapChain {
    device.create_swap_chain(
        &surface,
        &wgpu::SwapChainDescriptor {
            usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
            format: wgpu::TextureFormat::Bgra8UnormSrgb,
            width: u32::from(width),
            height: u32::from(height),
            present_mode: wgpu::PresentMode::Vsync,
        },
    )
}