Skip to main content

cubecl_wgpu/
graphics.rs

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