Skip to main content

rouge_render/
gpu.rs

1use thiserror::Error;
2use wgpu::{
3    Adapter, BlendState, Color as ClearColor, ColorTargetState, ColorWrites, CommandEncoder,
4    Device, DeviceDescriptor, Extent3d, FragmentState, Instance, Limits, LoadOp, MultisampleState,
5    Operations, PipelineCompilationOptions, PipelineLayout, PowerPreference, PrimitiveState,
6    PrimitiveTopology, Queue, RenderPass, RenderPassColorAttachment, RenderPassDescriptor,
7    RenderPipeline, RenderPipelineDescriptor, RequestAdapterError, RequestAdapterOptions,
8    RequestDeviceError, ShaderModule, StoreOp, Surface, Texture, TextureDescriptor,
9    TextureDimension, TextureFormat, TextureUsages, TextureView, VertexBufferLayout, VertexState,
10};
11
12#[cfg(not(target_arch = "wasm32"))]
13use wgpu::{MapRangeError, PollError, PollType};
14
15#[derive(Clone)]
16pub struct Gpu {
17    pub adapter: Adapter,
18    pub device: Device,
19    pub queue: Queue,
20}
21
22#[derive(Debug, Error)]
23pub enum GpuError {
24    #[error("no suitable GPU adapter found: {0}")]
25    NoAdapter(#[from] RequestAdapterError),
26    #[error("failed to create GPU device: {0}")]
27    NoDevice(#[from] RequestDeviceError),
28    #[cfg(not(target_arch = "wasm32"))]
29    #[error("failed to wait for the GPU: {0}")]
30    Poll(#[from] PollError),
31    #[cfg(not(target_arch = "wasm32"))]
32    #[error("failed to read back the rendered frame: {0}")]
33    Readback(#[from] MapRangeError),
34}
35
36impl Gpu {
37    #[cfg(not(target_arch = "wasm32"))]
38    pub fn wait(&self) -> Result<(), GpuError> {
39        self.device.poll(PollType::wait_indefinitely())?;
40        Ok(())
41    }
42
43    pub async fn new(
44        instance: Instance,
45        compatible_surface: Option<&Surface<'_>>,
46    ) -> Result<Gpu, GpuError> {
47        let adapter = instance
48            .request_adapter(&RequestAdapterOptions {
49                compatible_surface,
50                power_preference: PowerPreference::from_env().unwrap_or_default(),
51                ..Default::default()
52            })
53            .await?;
54        let (device, queue) = adapter
55            .request_device(&DeviceDescriptor {
56                label: Some("rouge device"),
57                required_limits: Limits::default().or_worse_values_from(&adapter.limits()),
58                ..Default::default()
59            })
60            .await?;
61        Ok(Gpu {
62            adapter,
63            device,
64            queue,
65        })
66    }
67}
68
69pub(crate) fn create_texture(
70    device: &Device,
71    label: &str,
72    (width, height): (u32, u32),
73    format: TextureFormat,
74    usage: TextureUsages,
75) -> Texture {
76    device.create_texture(&TextureDescriptor {
77        label: Some(label),
78        size: Extent3d {
79            width,
80            height,
81            depth_or_array_layers: 1,
82        },
83        mip_level_count: 1,
84        sample_count: 1,
85        dimension: TextureDimension::D2,
86        format,
87        usage,
88        view_formats: &[],
89    })
90}
91
92pub(crate) fn begin_pass(
93    encoder: &mut CommandEncoder,
94    view: &TextureView,
95    load: LoadOp<ClearColor>,
96) -> RenderPass<'static> {
97    encoder
98        .begin_render_pass(&RenderPassDescriptor {
99            label: Some("rouge pass"),
100            color_attachments: &[Some(RenderPassColorAttachment {
101                view,
102                depth_slice: None,
103                resolve_target: None,
104                ops: Operations {
105                    load,
106                    store: StoreOp::Store,
107                },
108            })],
109            depth_stencil_attachment: None,
110            timestamp_writes: None,
111            occlusion_query_set: None,
112            multiview_mask: None,
113        })
114        .forget_lifetime()
115}
116
117pub(crate) struct PipelineDesc<'a> {
118    pub layout: &'a PipelineLayout,
119    pub module: &'a ShaderModule,
120    pub fragment: &'a str,
121    pub format: TextureFormat,
122    pub blend: Option<BlendState>,
123    pub buffers: &'a [Option<VertexBufferLayout<'a>>],
124}
125
126pub(crate) fn create_pipeline(device: &Device, desc: &PipelineDesc<'_>) -> RenderPipeline {
127    device.create_render_pipeline(&RenderPipelineDescriptor {
128        label: Some(desc.fragment),
129        layout: Some(desc.layout),
130        vertex: VertexState {
131            module: desc.module,
132            entry_point: Some("vs_main"),
133            compilation_options: PipelineCompilationOptions::default(),
134            buffers: desc.buffers,
135        },
136        primitive: PrimitiveState {
137            topology: PrimitiveTopology::TriangleStrip,
138            ..Default::default()
139        },
140        depth_stencil: None,
141        multisample: MultisampleState::default(),
142        fragment: Some(FragmentState {
143            module: desc.module,
144            entry_point: Some(desc.fragment),
145            compilation_options: PipelineCompilationOptions::default(),
146            targets: &[Some(ColorTargetState {
147                format: desc.format,
148                blend: desc.blend,
149                write_mask: ColorWrites::ALL,
150            })],
151        }),
152        multiview_mask: None,
153        cache: None,
154    })
155}