cubecl_wgpu/
graphics.rs

1/// The basic trait to specify which graphics API to use as Backend.
2///
3/// Options are:
4///   - [Vulkan](Vulkan)
5///   - [Metal](Metal)
6///   - [OpenGL](OpenGl)
7///   - [DirectX 12](Dx12)
8///   - [WebGpu](WebGpu)
9pub trait GraphicsApi: Send + Sync + core::fmt::Debug + Default + Clone + 'static {
10    /// The wgpu backend.
11    fn backend() -> wgpu::Backend;
12}
13
14/// Vulkan graphics API.
15#[derive(Default, Debug, Clone)]
16pub struct Vulkan;
17
18/// Metal graphics API.
19#[derive(Default, Debug, Clone)]
20pub struct Metal;
21
22/// OpenGL graphics API.
23#[derive(Default, Debug, Clone)]
24pub struct OpenGl;
25
26/// DirectX 12 graphics API.
27#[derive(Default, Debug, Clone)]
28pub struct Dx12;
29
30/// WebGpu graphics API.
31#[derive(Default, Debug, Clone)]
32pub struct WebGpu;
33
34/// Automatic graphics API based on OS.
35#[derive(Default, Debug, Clone)]
36pub struct AutoGraphicsApi;
37
38impl GraphicsApi for Vulkan {
39    fn backend() -> wgpu::Backend {
40        wgpu::Backend::Vulkan
41    }
42}
43
44impl GraphicsApi for Metal {
45    fn backend() -> wgpu::Backend {
46        wgpu::Backend::Metal
47    }
48}
49
50impl GraphicsApi for OpenGl {
51    fn backend() -> wgpu::Backend {
52        wgpu::Backend::Gl
53    }
54}
55
56impl GraphicsApi for Dx12 {
57    fn backend() -> wgpu::Backend {
58        wgpu::Backend::Dx12
59    }
60}
61
62impl GraphicsApi for WebGpu {
63    fn backend() -> wgpu::Backend {
64        wgpu::Backend::BrowserWebGpu
65    }
66}
67
68impl GraphicsApi for AutoGraphicsApi {
69    fn backend() -> wgpu::Backend {
70        // Allow overriding AutoGraphicsApi backend with ENV var in std test environments
71        #[cfg(feature = "std")]
72        #[cfg(test)]
73        if let Ok(backend_str) = std::env::var("AUTO_GRAPHICS_BACKEND") {
74            match backend_str.to_lowercase().as_str() {
75                "metal" => return wgpu::Backend::Metal,
76                "vulkan" => return wgpu::Backend::Vulkan,
77                "dx12" => return wgpu::Backend::Dx12,
78                "opengl" => return wgpu::Backend::Gl,
79                "webgpu" => return wgpu::Backend::BrowserWebGpu,
80                _ => {
81                    eprintln!(
82                        "Invalid graphics backend specified in GRAPHICS_BACKEND environment \
83                         variable"
84                    );
85                    std::process::exit(1);
86                }
87            }
88        }
89
90        // In a no_std environment or if the environment variable is not set
91        cfg_if::cfg_if! {
92            if #[cfg(target_family = "wasm")] {
93                wgpu::Backend::BrowserWebGpu
94            } else if #[cfg(target_os = "macos")] {
95                 wgpu::Backend::Metal
96            } else {
97                wgpu::Backend::Vulkan
98            }
99        }
100    }
101}