Skip to main content

alpha2_gpu/
adapter_pin.rs

1//! `ALPHA2_GPU_ADAPTER` and the order adapters are tried in without a pin.
2
3/// How the renderer's adapter is chosen (`ALPHA2_GPU_ADAPTER`).
4#[derive(Clone, Debug, Default, Eq, PartialEq)]
5pub enum AdapterPolicy {
6    /// Rank hardware adapters by GPU encode and decode, then high-performance order
7    /// ([`crate::rank_adapters`]); requests without video context rank by that order alone.
8    #[default]
9    Auto,
10    /// The first hardware adapter in the high-performance order, whatever it encodes or decodes.
11    Performance,
12    /// The adapter at this position of its backend's enumeration.
13    Index(usize),
14    /// The first whose name contains this, ignoring case.
15    Name(String),
16}
17
18impl AdapterPolicy {
19    /// The policy `value` names; unset and empty give `auto`. Any other text that is not a number
20    /// is a name pin.
21    #[must_use]
22    pub fn parse(value: Option<&str>) -> Self {
23        match value.map(str::trim) {
24            None | Some("" | "auto") => Self::Auto,
25            Some("performance") => Self::Performance,
26            Some(text) => text
27                .parse::<usize>()
28                .map_or_else(|_| Self::Name(text.to_owned()), Self::Index),
29        }
30    }
31
32    /// The policy `ALPHA2_GPU_ADAPTER` names, else `auto`.
33    #[must_use]
34    pub fn from_env() -> Self {
35        Self::parse(std::env::var("ALPHA2_GPU_ADAPTER").ok().as_deref())
36    }
37
38    /// Whether this policy names one adapter.
39    #[must_use]
40    pub const fn is_pin(&self) -> bool {
41        matches!(self, Self::Index(_) | Self::Name(_))
42    }
43
44    /// Whether this pin names the adapter at enumeration position `index` called `name`.
45    #[must_use]
46    pub fn names(&self, index: usize, name: &str) -> bool {
47        match self {
48            Self::Index(pinned) => index == *pinned,
49            Self::Name(pinned) => name.to_lowercase().contains(&pinned.to_lowercase()),
50            Self::Auto | Self::Performance => false,
51        }
52    }
53
54    /// The setting as `ALPHA2_GPU_ADAPTER` spells it.
55    #[must_use]
56    pub fn setting(&self) -> String {
57        match self {
58            Self::Auto => "ALPHA2_GPU_ADAPTER=auto".to_owned(),
59            Self::Performance => "ALPHA2_GPU_ADAPTER=performance".to_owned(),
60            Self::Index(index) => format!("ALPHA2_GPU_ADAPTER={index}"),
61            Self::Name(name) => format!("ALPHA2_GPU_ADAPTER={name}"),
62        }
63    }
64
65    /// The policy as a capability report names it: `auto`, `performance`, `index:<n>` or
66    /// `name:<text>`.
67    #[must_use]
68    pub fn report_name(&self) -> String {
69        match self {
70            Self::Auto => "auto".to_owned(),
71            Self::Performance => "performance".to_owned(),
72            Self::Index(index) => format!("index:{index}"),
73            Self::Name(name) => format!("name:{name}"),
74        }
75    }
76}
77
78/// Rank in wgpu-core's high-performance order: discrete, integrated, other, virtual, CPU.
79#[must_use]
80pub fn high_performance_rank(device_type: wgpu::DeviceType) -> u8 {
81    match device_type {
82        wgpu::DeviceType::DiscreteGpu => 1,
83        wgpu::DeviceType::IntegratedGpu => 2,
84        wgpu::DeviceType::Other => 3,
85        wgpu::DeviceType::VirtualGpu => 4,
86        wgpu::DeviceType::Cpu => 5,
87    }
88}
89
90/// Enumeration positions of `kinds` sorted by [`high_performance_rank`].
91#[must_use]
92pub fn product_order(kinds: &[(usize, wgpu::DeviceType)]) -> Vec<usize> {
93    let mut ordered = kinds.to_vec();
94    // Stable, so adapters of one kind keep the backend's order.
95    ordered.sort_by_key(|(_, kind)| high_performance_rank(*kind));
96    ordered.into_iter().map(|(index, _)| index).collect()
97}
98
99/// Whether a GL adapter's `GL_VERSION` meets desktop GL 4.3 or GLES 3.1. Unparseable versions are
100/// accepted and left to the device request.
101///
102/// # Errors
103/// The reason the version is too old.
104pub fn gl_version_supported(version: &str) -> Result<(), String> {
105    let (es, rest) = match version.trim().strip_prefix("OpenGL ES") {
106        Some(rest) => (true, rest.trim_start()),
107        None => (false, version.trim()),
108    };
109    let mut numbers = rest
110        .split(|c: char| !c.is_ascii_digit())
111        .filter(|part| !part.is_empty())
112        .map(str::parse::<u32>);
113    let (Some(Ok(major)), Some(Ok(minor))) = (numbers.next(), numbers.next()) else {
114        return Ok(());
115    };
116    let (needed, name) = if es {
117        ((3, 1), "OpenGL ES")
118    } else {
119        ((4, 3), "OpenGL")
120    };
121    if (major, minor) >= needed {
122        Ok(())
123    } else {
124        Err(format!(
125            "{name} {major}.{minor} cannot run alpha2's shaders (needs desktop GL 4.3 or GLES 3.1)"
126        ))
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other, VirtualGpu};
134
135    #[test]
136    fn a_policy_is_auto_performance_an_index_or_a_name_and_unset_is_auto() {
137        assert_eq!(AdapterPolicy::default(), AdapterPolicy::Auto);
138        for (value, policy) in [
139            (None, AdapterPolicy::Auto),
140            (Some(""), AdapterPolicy::Auto),
141            (Some(" auto "), AdapterPolicy::Auto),
142            (Some("performance"), AdapterPolicy::Performance),
143            (Some("1"), AdapterPolicy::Index(1)),
144            (Some("NVIDIA"), AdapterPolicy::Name("NVIDIA".to_owned())),
145            // Unknown policy words are name pins.
146            (Some("encoder"), AdapterPolicy::Name("encoder".to_owned())),
147            (Some("default"), AdapterPolicy::Name("default".to_owned())),
148        ] {
149            assert_eq!(AdapterPolicy::parse(value), policy, "{value:?}");
150        }
151        assert!(!AdapterPolicy::Performance.is_pin());
152        assert!(AdapterPolicy::Index(0).is_pin());
153        assert!(AdapterPolicy::Name("intel".to_owned()).names(3, "Intel(R) Iris(R) Xe Graphics"));
154        assert!(!AdapterPolicy::Name("intel".to_owned()).names(0, "NVIDIA GeForce MX450"));
155        assert!(AdapterPolicy::Index(2).names(2, "any"));
156        assert_eq!(AdapterPolicy::Index(2).setting(), "ALPHA2_GPU_ADAPTER=2");
157        assert_eq!(AdapterPolicy::Index(2).report_name(), "index:2");
158        assert_eq!(
159            AdapterPolicy::Name("Iris".to_owned()).report_name(),
160            "name:Iris"
161        );
162    }
163
164    #[test]
165    fn gl_versions_below_desktop_4_3_and_gles_3_1_are_refused() {
166        let refused = gl_version_supported("3.3.0 NVIDIA 580.105.08").expect_err("GL 3.3");
167        assert!(refused.contains("OpenGL 3.3"), "{refused}");
168        assert!(
169            refused.contains("needs desktop GL 4.3 or GLES 3.1"),
170            "{refused}"
171        );
172        assert_eq!(
173            gl_version_supported("4.5 (Core Profile) Mesa 23.2.1"),
174            Ok(())
175        );
176        assert_eq!(gl_version_supported("OpenGL ES 3.2 Mesa"), Ok(()));
177        let es = gl_version_supported("OpenGL ES 3.0 ANGLE").expect_err("GLES 3.0");
178        assert!(es.contains("OpenGL ES 3.0"), "{es}");
179        assert_eq!(gl_version_supported("unknown"), Ok(()));
180    }
181
182    #[test]
183    fn product_order_follows_the_high_performance_rank_and_keeps_enumeration_order_within_a_rank() {
184        assert_eq!(
185            product_order(&[
186                (0, Cpu),
187                (1, IntegratedGpu),
188                (2, DiscreteGpu),
189                (3, VirtualGpu),
190                (4, IntegratedGpu),
191                (5, Other),
192                (6, DiscreteGpu),
193            ]),
194            [2, 6, 1, 4, 5, 3, 0]
195        );
196    }
197}