Skip to main content

alpha2_gpu/
error.rs

1use std::fmt;
2
3/// Failure while acquiring a GPU context, with the platform reason as its
4/// [`source`](std::error::Error::source).
5#[derive(Debug)]
6pub struct GpuError(Cause, Vec<(String, String)>);
7
8/// The step of acquiring a GPU context that failed.
9#[derive(Copy, Clone, Debug, Eq, PartialEq)]
10#[non_exhaustive]
11pub enum GpuAcquisitionStep {
12    /// No suitable adapter was found.
13    Adapter,
14    /// The adapter could not create a device.
15    Device,
16    /// A backend's instance did not start (on Windows, DX12 with its shader compiler).
17    Instance,
18    /// `ALPHA2_GPU_ADAPTER` names no adapter.
19    Pin,
20    /// No hardware adapter made a device, and software adapters were not wanted.
21    NoHardwareAdapter,
22}
23
24// Browser WebGPU has one instance, one adapter and no pin, so wasm uses only the first two.
25#[derive(Debug)]
26#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
27enum Cause {
28    Adapter(wgpu::RequestAdapterError),
29    Device(wgpu::RequestDeviceError),
30    Instance {
31        backend: &'static str,
32        compiler: String,
33    },
34    Pin(String),
35    NoHardwareAdapter {
36        software: Vec<String>,
37        refusals: Vec<(String, String)>,
38        seen: Vec<crate::AdapterRecord>,
39    },
40}
41
42impl GpuError {
43    pub(crate) const fn adapter(error: wgpu::RequestAdapterError) -> Self {
44        Self(Cause::Adapter(error), Vec::new())
45    }
46
47    pub(crate) const fn device(error: wgpu::RequestDeviceError) -> Self {
48        Self(Cause::Device(error), Vec::new())
49    }
50
51    #[cfg(not(target_arch = "wasm32"))]
52    pub(crate) const fn instance(backend: &'static str, compiler: String) -> Self {
53        Self(Cause::Instance { backend, compiler }, Vec::new())
54    }
55
56    /// A DX12 backend that lists no adapter because its shader compiler did not load. Reported
57    /// as [`GpuAcquisitionStep::Instance`].
58    #[cfg(not(target_arch = "wasm32"))]
59    #[must_use]
60    pub fn no_dx12_adapter() -> Self {
61        Self::instance("DX12", crate::dx12_shader_compiler().to_string())
62    }
63
64    #[cfg(not(target_arch = "wasm32"))]
65    pub(crate) const fn pin(reason: String) -> Self {
66        Self(Cause::Pin(reason), Vec::new())
67    }
68
69    #[cfg(not(target_arch = "wasm32"))]
70    pub(crate) const fn no_hardware(
71        software: Vec<String>,
72        refusals: Vec<(String, String)>,
73        seen: Vec<crate::AdapterRecord>,
74    ) -> Self {
75        Self(
76            Cause::NoHardwareAdapter {
77                software,
78                refusals,
79                seen,
80            },
81            Vec::new(),
82        )
83    }
84
85    /// Every adapter a request under [`crate::SoftwareAdapters::Refuse`] listed, with why none
86    /// rendered; empty for other errors.
87    #[must_use]
88    pub fn adapters_seen(&self) -> &[crate::AdapterRecord] {
89        match &self.0 {
90            Cause::NoHardwareAdapter { seen, .. } => seen,
91            _ => &[],
92        }
93    }
94
95    /// This error, also naming every adapter a request tried and why each failed.
96    #[cfg(not(target_arch = "wasm32"))]
97    pub(crate) fn tried(mut self, attempts: Vec<(String, String)>) -> Self {
98        self.1 = attempts;
99        self
100    }
101
102    /// The step that failed.
103    #[must_use]
104    pub const fn step(&self) -> GpuAcquisitionStep {
105        match self.0 {
106            Cause::Adapter(_) => GpuAcquisitionStep::Adapter,
107            Cause::Device(_) => GpuAcquisitionStep::Device,
108            Cause::Instance { .. } => GpuAcquisitionStep::Instance,
109            Cause::Pin(_) => GpuAcquisitionStep::Pin,
110            Cause::NoHardwareAdapter { .. } => GpuAcquisitionStep::NoHardwareAdapter,
111        }
112    }
113}
114
115impl std::error::Error for GpuError {
116    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
117        match &self.0 {
118            Cause::Adapter(error) => Some(error),
119            Cause::Device(error) => Some(error),
120            Cause::Instance { .. } | Cause::Pin(_) | Cause::NoHardwareAdapter { .. } => None,
121        }
122    }
123}
124
125impl fmt::Display for GpuError {
126    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
127        self.fmt_cause(formatter)?;
128        if self.1.len() > 1 {
129            for (adapter, reason) in &self.1 {
130                write!(formatter, "; tried {adapter}: {reason}")?;
131            }
132        }
133        Ok(())
134    }
135}
136
137impl GpuError {
138    fn fmt_cause(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
139        match &self.0 {
140            Cause::Adapter(error) => write!(formatter, "could not acquire a GPU adapter: {error}"),
141            Cause::Device(error) => write!(formatter, "could not acquire a GPU device: {error}"),
142            Cause::Instance { backend, compiler } if compiler.is_empty() => {
143                write!(formatter, "the {backend} backend did not start")
144            }
145            Cause::Instance { backend, compiler } => write!(
146                formatter,
147                "the {backend} backend did not start (shader compiler: {compiler}): is the file there?"
148            ),
149            Cause::Pin(reason) => formatter.write_str(reason),
150            Cause::NoHardwareAdapter {
151                software, refusals, ..
152            } => {
153                formatter.write_str("no hardware GPU")?;
154                if !software.is_empty() {
155                    write!(
156                        formatter,
157                        "; only software adapters ({}), which are not used here",
158                        software.join(", ")
159                    )?;
160                }
161                if refusals.is_empty() && software.is_empty() {
162                    formatter.write_str(": no GPU adapter was found")?;
163                }
164                for (adapter, reason) in refusals {
165                    write!(formatter, "; {adapter}: {reason}")?;
166                }
167                Ok(())
168            }
169        }
170    }
171}