wgpu_hal/gles/
egl.rs

1use alloc::{string::String, sync::Arc, vec::Vec};
2use core::{ffi, mem::ManuallyDrop, ptr, time::Duration};
3use std::sync::LazyLock;
4
5use glow::HasContext;
6use hashbrown::HashMap;
7use parking_lot::{MappedMutexGuard, Mutex, MutexGuard, RwLock};
8
9/// The amount of time to wait while trying to obtain a lock to the adapter context
10const CONTEXT_LOCK_TIMEOUT_SECS: u64 = 6;
11
12const EGL_CONTEXT_FLAGS_KHR: i32 = 0x30FC;
13const EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR: i32 = 0x0001;
14const EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT: i32 = 0x30BF;
15const EGL_PLATFORM_WAYLAND_KHR: u32 = 0x31D8;
16const EGL_PLATFORM_X11_KHR: u32 = 0x31D5;
17const EGL_PLATFORM_ANGLE_ANGLE: u32 = 0x3202;
18const EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE: u32 = 0x348F;
19const EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED: u32 = 0x3451;
20const EGL_PLATFORM_SURFACELESS_MESA: u32 = 0x31DD;
21const EGL_GL_COLORSPACE_KHR: u32 = 0x309D;
22const EGL_GL_COLORSPACE_SRGB_KHR: u32 = 0x3089;
23
24#[cfg(not(Emscripten))]
25type EglInstance = khronos_egl::DynamicInstance<khronos_egl::EGL1_4>;
26
27#[cfg(Emscripten)]
28type EglInstance = khronos_egl::Instance<khronos_egl::Static>;
29
30type EglLabel = *const ffi::c_void;
31
32#[allow(clippy::upper_case_acronyms)]
33type EGLDEBUGPROCKHR = Option<
34    unsafe extern "system" fn(
35        error: khronos_egl::Enum,
36        command: *const ffi::c_char,
37        message_type: u32,
38        thread_label: EglLabel,
39        object_label: EglLabel,
40        message: *const ffi::c_char,
41    ),
42>;
43
44const EGL_DEBUG_MSG_CRITICAL_KHR: u32 = 0x33B9;
45const EGL_DEBUG_MSG_ERROR_KHR: u32 = 0x33BA;
46const EGL_DEBUG_MSG_WARN_KHR: u32 = 0x33BB;
47const EGL_DEBUG_MSG_INFO_KHR: u32 = 0x33BC;
48
49type EglDebugMessageControlFun = unsafe extern "system" fn(
50    proc: EGLDEBUGPROCKHR,
51    attrib_list: *const khronos_egl::Attrib,
52) -> ffi::c_int;
53
54unsafe extern "system" fn egl_debug_proc(
55    error: khronos_egl::Enum,
56    command_raw: *const ffi::c_char,
57    message_type: u32,
58    _thread_label: EglLabel,
59    _object_label: EglLabel,
60    message_raw: *const ffi::c_char,
61) {
62    let log_severity = match message_type {
63        EGL_DEBUG_MSG_CRITICAL_KHR | EGL_DEBUG_MSG_ERROR_KHR => log::Level::Error,
64        EGL_DEBUG_MSG_WARN_KHR => log::Level::Warn,
65        // We intentionally suppress info messages down to debug
66        // so that users are not inundated with info messages from
67        // the runtime.
68        EGL_DEBUG_MSG_INFO_KHR => log::Level::Debug,
69        _ => log::Level::Trace,
70    };
71    let command = unsafe { ffi::CStr::from_ptr(command_raw) }.to_string_lossy();
72    let message = if message_raw.is_null() {
73        "".into()
74    } else {
75        unsafe { ffi::CStr::from_ptr(message_raw) }.to_string_lossy()
76    };
77
78    log::log!(log_severity, "EGL '{command}' code 0x{error:x}: {message}",);
79}
80
81#[derive(Clone, Copy, Debug)]
82enum SrgbFrameBufferKind {
83    /// No support for SRGB surface
84    None,
85    /// Using EGL 1.5's support for colorspaces
86    Core,
87    /// Using EGL_KHR_gl_colorspace
88    Khr,
89}
90
91/// Choose GLES framebuffer configuration.
92fn choose_config(
93    egl: &EglInstance,
94    display: khronos_egl::Display,
95    srgb_kind: SrgbFrameBufferKind,
96) -> Result<(khronos_egl::Config, bool), crate::InstanceError> {
97    //TODO: EGL_SLOW_CONFIG
98    let tiers = [
99        (
100            "off-screen",
101            &[
102                khronos_egl::SURFACE_TYPE,
103                khronos_egl::PBUFFER_BIT,
104                khronos_egl::RENDERABLE_TYPE,
105                khronos_egl::OPENGL_ES2_BIT,
106            ][..],
107        ),
108        (
109            "presentation",
110            &[khronos_egl::SURFACE_TYPE, khronos_egl::WINDOW_BIT][..],
111        ),
112        #[cfg(not(target_os = "android"))]
113        (
114            "native-render",
115            &[khronos_egl::NATIVE_RENDERABLE, khronos_egl::TRUE as _][..],
116        ),
117    ];
118
119    let mut attributes = Vec::with_capacity(9);
120    for tier_max in (0..tiers.len()).rev() {
121        let name = tiers[tier_max].0;
122        log::debug!("\tTrying {name}");
123
124        attributes.clear();
125        for &(_, tier_attr) in tiers[..=tier_max].iter() {
126            attributes.extend_from_slice(tier_attr);
127        }
128        // make sure the Alpha is enough to support sRGB
129        match srgb_kind {
130            SrgbFrameBufferKind::None => {}
131            _ => {
132                attributes.push(khronos_egl::ALPHA_SIZE);
133                attributes.push(8);
134            }
135        }
136        attributes.push(khronos_egl::NONE);
137
138        match egl.choose_first_config(display, &attributes) {
139            Ok(Some(config)) => {
140                if tier_max == 1 {
141                    //Note: this has been confirmed to malfunction on Intel+NV laptops,
142                    // but also on Angle.
143                    log::info!("EGL says it can present to the window but not natively",);
144                }
145                // Android emulator can't natively present either.
146                let tier_threshold =
147                    if cfg!(target_os = "android") || cfg!(windows) || cfg!(target_env = "ohos") {
148                        1
149                    } else {
150                        2
151                    };
152                return Ok((config, tier_max >= tier_threshold));
153            }
154            Ok(None) => {
155                log::debug!("No config found!");
156            }
157            Err(e) => {
158                log::error!("error in choose_first_config: {e:?}");
159            }
160        }
161    }
162
163    // TODO: include diagnostic details that are currently logged
164    Err(crate::InstanceError::new(String::from(
165        "unable to find an acceptable EGL framebuffer configuration",
166    )))
167}
168
169#[derive(Clone, Debug)]
170struct EglContext {
171    instance: Arc<EglInstance>,
172    version: (i32, i32),
173    display: khronos_egl::Display,
174    raw: khronos_egl::Context,
175    pbuffer: Option<khronos_egl::Surface>,
176}
177
178impl EglContext {
179    fn make_current(&self) {
180        self.instance
181            .make_current(self.display, self.pbuffer, self.pbuffer, Some(self.raw))
182            .unwrap();
183    }
184
185    fn unmake_current(&self) {
186        self.instance
187            .make_current(self.display, None, None, None)
188            .unwrap();
189    }
190}
191
192/// A wrapper around a [`glow::Context`] and the required EGL context that uses locking to guarantee
193/// exclusive access when shared with multiple threads.
194pub struct AdapterContext {
195    glow: Mutex<ManuallyDrop<glow::Context>>,
196    egl: Option<EglContext>,
197}
198
199unsafe impl Sync for AdapterContext {}
200unsafe impl Send for AdapterContext {}
201
202impl AdapterContext {
203    pub fn is_owned(&self) -> bool {
204        self.egl.is_some()
205    }
206
207    /// Returns the EGL instance.
208    ///
209    /// This provides access to EGL functions and the ability to load GL and EGL extension functions.
210    pub fn egl_instance(&self) -> Option<&EglInstance> {
211        self.egl.as_ref().map(|egl| &*egl.instance)
212    }
213
214    /// Returns the EGLDisplay corresponding to the adapter context.
215    ///
216    /// Returns [`None`] if the adapter was externally created.
217    pub fn raw_display(&self) -> Option<&khronos_egl::Display> {
218        self.egl.as_ref().map(|egl| &egl.display)
219    }
220
221    /// Returns the EGL version the adapter context was created with.
222    ///
223    /// Returns [`None`] if the adapter was externally created.
224    pub fn egl_version(&self) -> Option<(i32, i32)> {
225        self.egl.as_ref().map(|egl| egl.version)
226    }
227
228    pub fn raw_context(&self) -> *mut ffi::c_void {
229        match self.egl {
230            Some(ref egl) => egl.raw.as_ptr(),
231            None => ptr::null_mut(),
232        }
233    }
234}
235
236impl Drop for AdapterContext {
237    fn drop(&mut self) {
238        struct CurrentGuard<'a>(&'a EglContext);
239        impl Drop for CurrentGuard<'_> {
240            fn drop(&mut self) {
241                self.0.unmake_current();
242            }
243        }
244
245        // Context must be current when dropped. See safety docs on
246        // `glow::HasContext`.
247        //
248        // NOTE: This is only set to `None` by `Adapter::new_external` which
249        // requires the context to be current when anything that may be holding
250        // the `Arc<AdapterShared>` is dropped.
251        let _guard = self.egl.as_ref().map(|egl| {
252            egl.make_current();
253            CurrentGuard(egl)
254        });
255        let glow = self.glow.get_mut();
256        // SAFETY: Field not used after this.
257        unsafe { ManuallyDrop::drop(glow) };
258    }
259}
260
261struct EglContextLock<'a> {
262    instance: &'a Arc<EglInstance>,
263    display: khronos_egl::Display,
264}
265
266/// A guard containing a lock to an [`AdapterContext`], while the GL context is kept current.
267pub struct AdapterContextLock<'a> {
268    glow: MutexGuard<'a, ManuallyDrop<glow::Context>>,
269    egl: Option<EglContextLock<'a>>,
270}
271
272impl<'a> core::ops::Deref for AdapterContextLock<'a> {
273    type Target = glow::Context;
274
275    fn deref(&self) -> &Self::Target {
276        &self.glow
277    }
278}
279
280impl<'a> Drop for AdapterContextLock<'a> {
281    fn drop(&mut self) {
282        if let Some(egl) = self.egl.take() {
283            if let Err(err) = egl.instance.make_current(egl.display, None, None, None) {
284                log::error!("Failed to make EGL context current: {err:?}");
285            }
286        }
287    }
288}
289
290impl AdapterContext {
291    /// Get's the [`glow::Context`] without waiting for a lock
292    ///
293    /// # Safety
294    ///
295    /// This should only be called when you have manually made sure that the current thread has made
296    /// the EGL context current and that no other thread also has the EGL context current.
297    /// Additionally, you must manually make the EGL context **not** current after you are done with
298    /// it, so that future calls to `lock()` will not fail.
299    ///
300    /// > **Note:** Calling this function **will** still lock the [`glow::Context`] which adds an
301    /// > extra safe-guard against accidental concurrent access to the context.
302    pub unsafe fn get_without_egl_lock(&self) -> MappedMutexGuard<'_, glow::Context> {
303        let guard = self
304            .glow
305            .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
306            .expect("Could not lock adapter context. This is most-likely a deadlock.");
307        MutexGuard::map(guard, |glow| &mut **glow)
308    }
309
310    /// Obtain a lock to the EGL context and get handle to the [`glow::Context`] that can be used to
311    /// do rendering.
312    #[track_caller]
313    pub fn lock<'a>(&'a self) -> AdapterContextLock<'a> {
314        let glow = self
315            .glow
316            // Don't lock forever. If it takes longer than 1 second to get the lock we've got a
317            // deadlock and should panic to show where we got stuck
318            .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
319            .expect("Could not lock adapter context. This is most-likely a deadlock.");
320
321        let egl = self.egl.as_ref().map(|egl| {
322            egl.make_current();
323            EglContextLock {
324                instance: &egl.instance,
325                display: egl.display,
326            }
327        });
328
329        AdapterContextLock { glow, egl }
330    }
331}
332
333#[derive(Debug)]
334struct Inner {
335    /// Note: the context contains a dummy pbuffer (1x1).
336    /// Required for `eglMakeCurrent` on platforms that doesn't supports `EGL_KHR_surfaceless_context`.
337    egl: EglContext,
338    version: (i32, i32),
339    supports_native_window: bool,
340    config: khronos_egl::Config,
341    /// Method by which the framebuffer should support srgb
342    srgb_kind: SrgbFrameBufferKind,
343}
344
345// Different calls to `eglGetPlatformDisplay` may return the same `Display`, making it a global
346// state of all our `EglContext`s. This forces us to track the number of such context to prevent
347// terminating the display if it's currently used by another `EglContext`.
348static DISPLAYS_REFERENCE_COUNT: LazyLock<Mutex<HashMap<usize, usize>>> =
349    LazyLock::new(Default::default);
350
351fn initialize_display(
352    egl: &EglInstance,
353    display: khronos_egl::Display,
354) -> Result<(i32, i32), khronos_egl::Error> {
355    let mut guard = DISPLAYS_REFERENCE_COUNT.lock();
356    *guard.entry(display.as_ptr() as usize).or_default() += 1;
357
358    // We don't need to check the reference count here since according to the `eglInitialize`
359    // documentation, initializing an already initialized EGL display connection has no effect
360    // besides returning the version numbers.
361    egl.initialize(display)
362}
363
364fn terminate_display(
365    egl: &EglInstance,
366    display: khronos_egl::Display,
367) -> Result<(), khronos_egl::Error> {
368    let key = &(display.as_ptr() as usize);
369    let mut guard = DISPLAYS_REFERENCE_COUNT.lock();
370    let count_ref = guard
371        .get_mut(key)
372        .expect("Attempted to decref a display before incref was called");
373
374    if *count_ref > 1 {
375        *count_ref -= 1;
376
377        Ok(())
378    } else {
379        guard.remove(key);
380
381        egl.terminate(display)
382    }
383}
384
385fn instance_err<E: core::error::Error + Send + Sync + 'static>(
386    message: impl Into<String>,
387) -> impl FnOnce(E) -> crate::InstanceError {
388    move |e| crate::InstanceError::with_source(message.into(), e)
389}
390
391impl Inner {
392    fn create(
393        flags: wgt::InstanceFlags,
394        egl: Arc<EglInstance>,
395        display: khronos_egl::Display,
396        force_gles_minor_version: wgt::Gles3MinorVersion,
397    ) -> Result<Self, crate::InstanceError> {
398        let version = initialize_display(&egl, display)
399            .map_err(instance_err("failed to initialize EGL display connection"))?;
400        let vendor = egl
401            .query_string(Some(display), khronos_egl::VENDOR)
402            .map_err(instance_err("failed to query EGL vendor"))?;
403        let display_extensions = egl
404            .query_string(Some(display), khronos_egl::EXTENSIONS)
405            .map_err(instance_err("failed to query EGL display extensions"))?
406            .to_string_lossy();
407        log::debug!("Display vendor {vendor:?}, version {version:?}",);
408        log::debug!(
409            "Display extensions: {:#?}",
410            display_extensions.split_whitespace().collect::<Vec<_>>()
411        );
412
413        let srgb_kind = if version >= (1, 5) {
414            log::debug!("\tEGL surface: +srgb");
415            SrgbFrameBufferKind::Core
416        } else if display_extensions.contains("EGL_KHR_gl_colorspace") {
417            log::debug!("\tEGL surface: +srgb khr");
418            SrgbFrameBufferKind::Khr
419        } else {
420            log::debug!("\tEGL surface: -srgb");
421            SrgbFrameBufferKind::None
422        };
423
424        if log::max_level() >= log::LevelFilter::Trace {
425            log::trace!("Configurations:");
426            let config_count = egl
427                .get_config_count(display)
428                .map_err(instance_err("failed to get config count"))?;
429            let mut configurations = Vec::with_capacity(config_count);
430            egl.get_configs(display, &mut configurations)
431                .map_err(instance_err("failed to get configs"))?;
432            for &config in configurations.iter() {
433                log::trace!("\tCONFORMANT=0x{:X?}, RENDERABLE=0x{:X?}, NATIVE_RENDERABLE=0x{:X?}, SURFACE_TYPE=0x{:X?}, ALPHA_SIZE={:?}",
434                    egl.get_config_attrib(display, config, khronos_egl::CONFORMANT),
435                    egl.get_config_attrib(display, config, khronos_egl::RENDERABLE_TYPE),
436                    egl.get_config_attrib(display, config, khronos_egl::NATIVE_RENDERABLE),
437                    egl.get_config_attrib(display, config, khronos_egl::SURFACE_TYPE),
438                    egl.get_config_attrib(display, config, khronos_egl::ALPHA_SIZE),
439                );
440            }
441        }
442
443        let (config, supports_native_window) = choose_config(&egl, display, srgb_kind)?;
444
445        let supports_opengl = if version >= (1, 4) {
446            let client_apis = egl
447                .query_string(Some(display), khronos_egl::CLIENT_APIS)
448                .map_err(instance_err("failed to query EGL client APIs string"))?
449                .to_string_lossy();
450            client_apis
451                .split(' ')
452                .any(|client_api| client_api == "OpenGL")
453        } else {
454            false
455        };
456        egl.bind_api(if supports_opengl {
457            khronos_egl::OPENGL_API
458        } else {
459            khronos_egl::OPENGL_ES_API
460        })
461        .map_err(instance_err("failed to bind API"))?;
462
463        let mut khr_context_flags = 0;
464        let supports_khr_context = display_extensions.contains("EGL_KHR_create_context");
465
466        let mut context_attributes = vec![];
467        let mut gl_context_attributes = vec![];
468        let mut gles_context_attributes = vec![];
469        gl_context_attributes.push(khronos_egl::CONTEXT_MAJOR_VERSION);
470        gl_context_attributes.push(3);
471        gl_context_attributes.push(khronos_egl::CONTEXT_MINOR_VERSION);
472        gl_context_attributes.push(3);
473        if supports_opengl && force_gles_minor_version != wgt::Gles3MinorVersion::Automatic {
474            log::warn!("Ignoring specified GLES minor version as OpenGL is used");
475        }
476        gles_context_attributes.push(khronos_egl::CONTEXT_MAJOR_VERSION);
477        gles_context_attributes.push(3); // Request GLES 3.0 or higher
478        if force_gles_minor_version != wgt::Gles3MinorVersion::Automatic {
479            gles_context_attributes.push(khronos_egl::CONTEXT_MINOR_VERSION);
480            gles_context_attributes.push(match force_gles_minor_version {
481                wgt::Gles3MinorVersion::Automatic => unreachable!(),
482                wgt::Gles3MinorVersion::Version0 => 0,
483                wgt::Gles3MinorVersion::Version1 => 1,
484                wgt::Gles3MinorVersion::Version2 => 2,
485            });
486        }
487        if flags.contains(wgt::InstanceFlags::DEBUG) {
488            if version >= (1, 5) {
489                log::debug!("\tEGL context: +debug");
490                context_attributes.push(khronos_egl::CONTEXT_OPENGL_DEBUG);
491                context_attributes.push(khronos_egl::TRUE as _);
492            } else if supports_khr_context {
493                log::debug!("\tEGL context: +debug KHR");
494                khr_context_flags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR;
495            } else {
496                log::debug!("\tEGL context: -debug");
497            }
498        }
499
500        if khr_context_flags != 0 {
501            context_attributes.push(EGL_CONTEXT_FLAGS_KHR);
502            context_attributes.push(khr_context_flags);
503        }
504
505        gl_context_attributes.extend(&context_attributes);
506        gles_context_attributes.extend(&context_attributes);
507
508        let context = {
509            enum Robustness {
510                Core,
511                Ext,
512            }
513
514            let mut robustness = if version >= (1, 5) {
515                Some(Robustness::Core)
516            } else if display_extensions.contains("EGL_EXT_create_context_robustness") {
517                Some(Robustness::Ext)
518            } else {
519                None
520            };
521
522            loop {
523                let robustness_attributes = match robustness {
524                    Some(Robustness::Core) => {
525                        vec![
526                            khronos_egl::CONTEXT_OPENGL_ROBUST_ACCESS,
527                            khronos_egl::TRUE as _,
528                            khronos_egl::NONE,
529                        ]
530                    }
531                    Some(Robustness::Ext) => {
532                        vec![
533                            EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT,
534                            khronos_egl::TRUE as _,
535                            khronos_egl::NONE,
536                        ]
537                    }
538                    None => vec![khronos_egl::NONE],
539                };
540
541                let mut gl_context_attributes = gl_context_attributes.clone();
542                gl_context_attributes.extend(&robustness_attributes);
543
544                let mut gles_context_attributes = gles_context_attributes.clone();
545                gles_context_attributes.extend(&robustness_attributes);
546
547                let result = if supports_opengl {
548                    egl.create_context(display, config, None, &gl_context_attributes)
549                        .or_else(|_| {
550                            egl.bind_api(khronos_egl::OPENGL_ES_API)?;
551                            egl.create_context(display, config, None, &gles_context_attributes)
552                        })
553                } else {
554                    egl.create_context(display, config, None, &gles_context_attributes)
555                };
556
557                match (result, robustness) {
558                    // We have a context at the requested robustness level
559                    (Ok(_), robustness) => {
560                        match robustness {
561                            Some(Robustness::Core) => {
562                                log::debug!("\tEGL context: +robust access");
563                            }
564                            Some(Robustness::Ext) => {
565                                log::debug!("\tEGL context: +robust access EXT");
566                            }
567                            None => {
568                                log::debug!("\tEGL context: -robust access");
569                            }
570                        }
571
572                        break result;
573                    }
574
575                    // BadAttribute could mean that context creation is not supported at the requested robustness level
576                    // We try the next robustness level.
577                    (Err(khronos_egl::Error::BadAttribute), Some(r)) => {
578                        // Trying EXT robustness if Core robustness is not working
579                        // and EXT robustness is supported.
580                        robustness = if matches!(r, Robustness::Core)
581                            && display_extensions.contains("EGL_EXT_create_context_robustness")
582                        {
583                            Some(Robustness::Ext)
584                        } else {
585                            None
586                        };
587
588                        continue;
589                    }
590
591                    // Any other error, or depleted robustness levels, we give up.
592                    _ => break result,
593                }
594            }
595            .map_err(|e| {
596                crate::InstanceError::with_source(
597                    String::from("unable to create OpenGL or GLES 3.x context"),
598                    e,
599                )
600            })
601        }?;
602
603        // Testing if context can be binded without surface
604        // and creating dummy pbuffer surface if not.
605        let pbuffer = if version >= (1, 5)
606            || display_extensions.contains("EGL_KHR_surfaceless_context")
607            || cfg!(Emscripten)
608        {
609            log::debug!("\tEGL context: +surfaceless");
610            None
611        } else {
612            let attributes = [
613                khronos_egl::WIDTH,
614                1,
615                khronos_egl::HEIGHT,
616                1,
617                khronos_egl::NONE,
618            ];
619            egl.create_pbuffer_surface(display, config, &attributes)
620                .map(Some)
621                .map_err(|e| {
622                    crate::InstanceError::with_source(
623                        String::from("error in create_pbuffer_surface"),
624                        e,
625                    )
626                })?
627        };
628
629        Ok(Self {
630            egl: EglContext {
631                instance: egl,
632                display,
633                raw: context,
634                pbuffer,
635                version,
636            },
637            version,
638            supports_native_window,
639            config,
640            srgb_kind,
641        })
642    }
643}
644
645impl Drop for Inner {
646    fn drop(&mut self) {
647        // ERROR: Since EglContext is erroneously Clone, these handles could be copied and
648        // accidentally used elsewhere outside of Inner, despite us assuming ownership and
649        // destroying the handles here.
650        if let Err(e) = self
651            .egl
652            .instance
653            .destroy_context(self.egl.display, self.egl.raw)
654        {
655            log::warn!("Error in destroy_context: {e:?}");
656        }
657
658        if let Err(e) = terminate_display(&self.egl.instance, self.egl.display) {
659            log::warn!("Error in terminate: {e:?}");
660        }
661    }
662}
663
664#[derive(Clone, Copy, Debug, PartialEq)]
665enum WindowKind {
666    Wayland,
667    X11,
668    AngleX11,
669    Unknown,
670}
671
672#[derive(Clone, Debug)]
673struct WindowSystemInterface {
674    kind: WindowKind,
675}
676
677pub struct Instance {
678    wsi: WindowSystemInterface,
679    flags: wgt::InstanceFlags,
680    options: wgt::GlBackendOptions,
681    inner: Mutex<Inner>,
682}
683
684impl Instance {
685    pub fn raw_display(&self) -> khronos_egl::Display {
686        self.inner
687            .try_lock()
688            .expect("Could not lock instance. This is most-likely a deadlock.")
689            .egl
690            .display
691    }
692
693    /// Returns the version of the EGL display.
694    pub fn egl_version(&self) -> (i32, i32) {
695        self.inner
696            .try_lock()
697            .expect("Could not lock instance. This is most-likely a deadlock.")
698            .version
699    }
700
701    pub fn egl_config(&self) -> khronos_egl::Config {
702        self.inner
703            .try_lock()
704            .expect("Could not lock instance. This is most-likely a deadlock.")
705            .config
706    }
707}
708
709unsafe impl Send for Instance {}
710unsafe impl Sync for Instance {}
711
712impl crate::Instance for Instance {
713    type A = super::Api;
714
715    unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
716        use raw_window_handle::RawDisplayHandle as Rdh;
717
718        profiling::scope!("Init OpenGL (EGL) Backend");
719        #[cfg(Emscripten)]
720        let egl_result: Result<EglInstance, khronos_egl::Error> =
721            Ok(khronos_egl::Instance::new(khronos_egl::Static));
722
723        #[cfg(not(Emscripten))]
724        let egl_result = if cfg!(windows) {
725            unsafe {
726                khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required_from_filename(
727                    "libEGL.dll",
728                )
729            }
730        } else if cfg!(target_vendor = "apple") {
731            unsafe {
732                khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required_from_filename(
733                    "libEGL.dylib",
734                )
735            }
736        } else {
737            unsafe { khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required() }
738        };
739        let egl = egl_result
740            .map(Arc::new)
741            .map_err(instance_err("unable to open libEGL"))?;
742
743        let client_extensions = egl.query_string(None, khronos_egl::EXTENSIONS);
744
745        let client_ext_str = match client_extensions {
746            Ok(ext) => ext.to_string_lossy().into_owned(),
747            Err(_) => String::new(),
748        };
749        log::debug!(
750            "Client extensions: {:#?}",
751            client_ext_str.split_whitespace().collect::<Vec<_>>()
752        );
753
754        #[cfg(not(Emscripten))]
755        let egl1_5 = egl.upcast::<khronos_egl::EGL1_5>();
756
757        #[cfg(Emscripten)]
758        let egl1_5: Option<&Arc<EglInstance>> = Some(&egl);
759
760        let (display, wsi_kind) = match (desc.display.map(|d| d.as_raw()), egl1_5) {
761            (Some(Rdh::Wayland(wayland_display_handle)), Some(egl))
762                if client_ext_str.contains("EGL_EXT_platform_wayland") =>
763            {
764                log::debug!("Using Wayland platform");
765                let display_attributes = [khronos_egl::ATTRIB_NONE];
766                let display = unsafe {
767                    egl.get_platform_display(
768                        EGL_PLATFORM_WAYLAND_KHR,
769                        wayland_display_handle.display.as_ptr(),
770                        &display_attributes,
771                    )
772                }
773                .map_err(instance_err("failed to get Wayland display"))?;
774                (display, WindowKind::Wayland)
775            }
776            (Some(Rdh::Xlib(xlib_display_handle)), Some(egl))
777                if client_ext_str.contains("EGL_EXT_platform_x11") =>
778            {
779                log::debug!("Using X11 platform");
780                let display_attributes = [khronos_egl::ATTRIB_NONE];
781                let display = unsafe {
782                    egl.get_platform_display(
783                        EGL_PLATFORM_X11_KHR,
784                        xlib_display_handle
785                            .display
786                            .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr),
787                        &display_attributes,
788                    )
789                }
790                .map_err(instance_err("failed to get X11 display"))?;
791                (display, WindowKind::X11)
792            }
793            (Some(Rdh::Xlib(xlib_display_handle)), Some(egl))
794                if client_ext_str.contains("EGL_ANGLE_platform_angle") =>
795            {
796                log::debug!("Using Angle platform with X11");
797                let display_attributes = [
798                    EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE as khronos_egl::Attrib,
799                    EGL_PLATFORM_X11_KHR as khronos_egl::Attrib,
800                    EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED as khronos_egl::Attrib,
801                    usize::from(desc.flags.contains(wgt::InstanceFlags::VALIDATION)),
802                    khronos_egl::ATTRIB_NONE,
803                ];
804                let display = unsafe {
805                    egl.get_platform_display(
806                        EGL_PLATFORM_ANGLE_ANGLE,
807                        xlib_display_handle
808                            .display
809                            .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr),
810                        &display_attributes,
811                    )
812                }
813                .map_err(instance_err("failed to get Angle display"))?;
814                (display, WindowKind::AngleX11)
815            }
816            (Some(Rdh::Xcb(_xcb_display_handle)), Some(_egl)) => todo!("xcb"),
817            x if client_ext_str.contains("EGL_MESA_platform_surfaceless") => {
818                log::debug!(
819                    "No (or unknown) windowing system ({x:?}) present. Using surfaceless platform"
820                );
821                #[allow(clippy::unnecessary_literal_unwrap)]
822                // This is only a literal on Emscripten
823                // TODO: This extension is also supported on EGL 1.4 with EGL_EXT_platform_base: https://registry.khronos.org/EGL/extensions/MESA/EGL_MESA_platform_surfaceless.txt
824                let egl = egl1_5.expect("Failed to get EGL 1.5 for surfaceless");
825                let display = unsafe {
826                    egl.get_platform_display(
827                        EGL_PLATFORM_SURFACELESS_MESA,
828                        khronos_egl::DEFAULT_DISPLAY,
829                        &[khronos_egl::ATTRIB_NONE],
830                    )
831                }
832                .map_err(instance_err("failed to get MESA surfaceless display"))?;
833                (display, WindowKind::Unknown)
834            }
835            x => {
836                log::debug!(
837                    "No (or unknown) windowing system {x:?} and EGL_MESA_platform_surfaceless not available. Using default platform"
838                );
839                let display =
840                    unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.ok_or_else(|| {
841                        crate::InstanceError::new("Failed to get default display".into())
842                    })?;
843                (display, WindowKind::Unknown)
844            }
845        };
846
847        if desc.flags.contains(wgt::InstanceFlags::VALIDATION)
848            && client_ext_str.contains("EGL_KHR_debug")
849        {
850            log::debug!("Enabling EGL debug output");
851            let function: EglDebugMessageControlFun = {
852                let addr = egl
853                    .get_proc_address("eglDebugMessageControlKHR")
854                    .ok_or_else(|| {
855                        crate::InstanceError::new(
856                            "failed to get `eglDebugMessageControlKHR` proc address".into(),
857                        )
858                    })?;
859                unsafe { core::mem::transmute(addr) }
860            };
861            let attributes = [
862                EGL_DEBUG_MSG_CRITICAL_KHR as khronos_egl::Attrib,
863                1,
864                EGL_DEBUG_MSG_ERROR_KHR as khronos_egl::Attrib,
865                1,
866                EGL_DEBUG_MSG_WARN_KHR as khronos_egl::Attrib,
867                1,
868                EGL_DEBUG_MSG_INFO_KHR as khronos_egl::Attrib,
869                1,
870                khronos_egl::ATTRIB_NONE,
871            ];
872            unsafe { (function)(Some(egl_debug_proc), attributes.as_ptr()) };
873        }
874
875        let inner = Inner::create(
876            desc.flags,
877            egl,
878            display,
879            desc.backend_options.gl.gles_minor_version,
880        )?;
881
882        Ok(Instance {
883            wsi: WindowSystemInterface { kind: wsi_kind },
884            flags: desc.flags,
885            options: desc.backend_options.gl.clone(),
886            inner: Mutex::new(inner),
887        })
888    }
889
890    unsafe fn create_surface(
891        &self,
892        display_handle: raw_window_handle::RawDisplayHandle,
893        window_handle: raw_window_handle::RawWindowHandle,
894    ) -> Result<Surface, crate::InstanceError> {
895        use raw_window_handle::RawWindowHandle as Rwh;
896
897        let inner = self.inner.lock();
898
899        match (window_handle, display_handle) {
900            (Rwh::Xlib(_), _) => {}
901            (Rwh::Xcb(_), _) => {}
902            (Rwh::Win32(_), _) => {}
903            (Rwh::AppKit(_), _) => {}
904            (Rwh::OhosNdk(_), _) => {}
905            #[cfg(target_os = "android")]
906            (Rwh::AndroidNdk(handle), _) => {
907                let format = inner
908                    .egl
909                    .instance
910                    .get_config_attrib(
911                        inner.egl.display,
912                        inner.config,
913                        khronos_egl::NATIVE_VISUAL_ID,
914                    )
915                    .map_err(instance_err("failed to get config NATIVE_VISUAL_ID"))?;
916
917                let ret = unsafe {
918                    ndk_sys::ANativeWindow_setBuffersGeometry(
919                        handle
920                            .a_native_window
921                            .as_ptr()
922                            .cast::<ndk_sys::ANativeWindow>(),
923                        0,
924                        0,
925                        format,
926                    )
927                };
928
929                if ret != 0 {
930                    return Err(crate::InstanceError::new(format!(
931                        "error {ret} returned from ANativeWindow_setBuffersGeometry",
932                    )));
933                }
934            }
935            (Rwh::Wayland(_), _) => {}
936            #[cfg(Emscripten)]
937            (Rwh::Web(_), _) => {}
938            other => {
939                return Err(crate::InstanceError::new(format!(
940                    "unsupported window: {other:?}"
941                )));
942            }
943        };
944
945        inner.egl.unmake_current();
946
947        Ok(Surface {
948            egl: inner.egl.clone(),
949            wsi: self.wsi.clone(),
950            config: inner.config,
951            presentable: inner.supports_native_window,
952            raw_window_handle: window_handle,
953            swapchain: RwLock::new(None),
954            srgb_kind: inner.srgb_kind,
955        })
956    }
957
958    unsafe fn enumerate_adapters(
959        &self,
960        _surface_hint: Option<&Surface>,
961    ) -> Vec<crate::ExposedAdapter<super::Api>> {
962        let inner = self.inner.lock();
963        inner.egl.make_current();
964
965        let mut gl = unsafe {
966            glow::Context::from_loader_function(|name| {
967                inner
968                    .egl
969                    .instance
970                    .get_proc_address(name)
971                    .map_or(ptr::null(), |p| p as *const _)
972            })
973        };
974
975        // In contrast to OpenGL ES, OpenGL requires explicitly enabling sRGB conversions,
976        // as otherwise the user has to do the sRGB conversion.
977        if !matches!(inner.srgb_kind, SrgbFrameBufferKind::None) {
978            unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
979        }
980
981        if self.flags.contains(wgt::InstanceFlags::DEBUG) && gl.supports_debug() {
982            log::debug!("Max label length: {}", unsafe {
983                gl.get_parameter_i32(glow::MAX_LABEL_LENGTH)
984            });
985        }
986
987        if self.flags.contains(wgt::InstanceFlags::VALIDATION) && gl.supports_debug() {
988            log::debug!("Enabling GLES debug output");
989            unsafe { gl.enable(glow::DEBUG_OUTPUT) };
990            unsafe { gl.debug_message_callback(super::gl_debug_message_callback) };
991        }
992
993        // Wrap in ManuallyDrop to make it easier to "current" the GL context before dropping this
994        // GLOW context, which could also happen if a panic occurs after we uncurrent the context
995        // below but before AdapterContext is constructed.
996        let gl = ManuallyDrop::new(gl);
997        inner.egl.unmake_current();
998
999        unsafe {
1000            super::Adapter::expose(
1001                AdapterContext {
1002                    glow: Mutex::new(gl),
1003                    // ERROR: Copying owned reference handles here, be careful to not drop them!
1004                    egl: Some(inner.egl.clone()),
1005                },
1006                self.options.clone(),
1007            )
1008        }
1009        .into_iter()
1010        .collect()
1011    }
1012}
1013
1014impl super::Adapter {
1015    /// Creates a new external adapter using the specified loader function.
1016    ///
1017    /// # Safety
1018    ///
1019    /// - The underlying OpenGL ES context must be current.
1020    /// - The underlying OpenGL ES context must be current when interfacing with any objects returned by
1021    ///   wgpu-hal from this adapter.
1022    /// - The underlying OpenGL ES context must be current when dropping this adapter and when
1023    ///   dropping any objects returned from this adapter.
1024    pub unsafe fn new_external(
1025        fun: impl FnMut(&str) -> *const ffi::c_void,
1026        options: wgt::GlBackendOptions,
1027    ) -> Option<crate::ExposedAdapter<super::Api>> {
1028        let context = unsafe { glow::Context::from_loader_function(fun) };
1029        unsafe {
1030            Self::expose(
1031                AdapterContext {
1032                    glow: Mutex::new(ManuallyDrop::new(context)),
1033                    egl: None,
1034                },
1035                options,
1036            )
1037        }
1038    }
1039
1040    pub fn adapter_context(&self) -> &AdapterContext {
1041        &self.shared.context
1042    }
1043}
1044
1045impl super::Device {
1046    /// Returns the underlying EGL context.
1047    pub fn context(&self) -> &AdapterContext {
1048        &self.shared.context
1049    }
1050}
1051
1052#[derive(Debug)]
1053pub struct Swapchain {
1054    surface: khronos_egl::Surface,
1055    wl_window: Option<*mut wayland_sys::egl::wl_egl_window>,
1056    framebuffer: glow::Framebuffer,
1057    renderbuffer: glow::Renderbuffer,
1058    /// Extent because the window lies
1059    extent: wgt::Extent3d,
1060    format: wgt::TextureFormat,
1061    format_desc: super::TextureFormatDesc,
1062    #[allow(unused)]
1063    sample_type: wgt::TextureSampleType,
1064}
1065
1066#[derive(Debug)]
1067pub struct Surface {
1068    egl: EglContext,
1069    wsi: WindowSystemInterface,
1070    config: khronos_egl::Config,
1071    pub(super) presentable: bool,
1072    raw_window_handle: raw_window_handle::RawWindowHandle,
1073    swapchain: RwLock<Option<Swapchain>>,
1074    srgb_kind: SrgbFrameBufferKind,
1075}
1076
1077unsafe impl Send for Surface {}
1078unsafe impl Sync for Surface {}
1079
1080impl Surface {
1081    pub(super) unsafe fn present(
1082        &self,
1083        _suf_texture: super::Texture,
1084        context: &AdapterContext,
1085    ) -> Result<(), crate::SurfaceError> {
1086        let gl = unsafe { context.get_without_egl_lock() };
1087        let swapchain = self.swapchain.read();
1088        let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other(
1089            "Surface has no swap-chain configured",
1090        ))?;
1091
1092        self.egl
1093            .instance
1094            .make_current(
1095                self.egl.display,
1096                Some(sc.surface),
1097                Some(sc.surface),
1098                Some(self.egl.raw),
1099            )
1100            .map_err(|e| {
1101                log::error!("make_current(surface) failed: {e}");
1102                crate::SurfaceError::Lost
1103            })?;
1104
1105        unsafe { gl.disable(glow::SCISSOR_TEST) };
1106        unsafe { gl.color_mask(true, true, true, true) };
1107
1108        unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
1109        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer)) };
1110
1111        if !matches!(self.srgb_kind, SrgbFrameBufferKind::None) {
1112            // Disable sRGB conversions for `glBlitFramebuffer` as behavior does diverge between
1113            // drivers and formats otherwise and we want to ensure no sRGB conversions happen.
1114            unsafe { gl.disable(glow::FRAMEBUFFER_SRGB) };
1115        }
1116
1117        // Note the Y-flipping here. GL's presentation is not flipped,
1118        // but main rendering is. Therefore, we Y-flip the output positions
1119        // in the shader, and also this blit.
1120        unsafe {
1121            gl.blit_framebuffer(
1122                0,
1123                sc.extent.height as i32,
1124                sc.extent.width as i32,
1125                0,
1126                0,
1127                0,
1128                sc.extent.width as i32,
1129                sc.extent.height as i32,
1130                glow::COLOR_BUFFER_BIT,
1131                glow::NEAREST,
1132            )
1133        };
1134
1135        if !matches!(self.srgb_kind, SrgbFrameBufferKind::None) {
1136            unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
1137        }
1138
1139        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
1140
1141        self.egl
1142            .instance
1143            .swap_buffers(self.egl.display, sc.surface)
1144            .map_err(|e| {
1145                log::error!("swap_buffers failed: {e}");
1146                crate::SurfaceError::Lost
1147                // TODO: should we unset the current context here?
1148            })?;
1149        self.egl
1150            .instance
1151            .make_current(self.egl.display, None, None, None)
1152            .map_err(|e| {
1153                log::error!("make_current(null) failed: {e}");
1154                crate::SurfaceError::Lost
1155            })?;
1156
1157        Ok(())
1158    }
1159
1160    unsafe fn unconfigure_impl(
1161        &self,
1162        device: &super::Device,
1163    ) -> Option<(
1164        khronos_egl::Surface,
1165        Option<*mut wayland_sys::egl::wl_egl_window>,
1166    )> {
1167        let gl = &device.shared.context.lock();
1168        match self.swapchain.write().take() {
1169            Some(sc) => {
1170                unsafe { gl.delete_renderbuffer(sc.renderbuffer) };
1171                unsafe { gl.delete_framebuffer(sc.framebuffer) };
1172                Some((sc.surface, sc.wl_window))
1173            }
1174            None => None,
1175        }
1176    }
1177
1178    pub fn supports_srgb(&self) -> bool {
1179        match self.srgb_kind {
1180            SrgbFrameBufferKind::None => false,
1181            _ => true,
1182        }
1183    }
1184}
1185
1186impl crate::Surface for Surface {
1187    type A = super::Api;
1188
1189    unsafe fn configure(
1190        &self,
1191        device: &super::Device,
1192        config: &crate::SurfaceConfiguration,
1193    ) -> Result<(), crate::SurfaceError> {
1194        use raw_window_handle::RawWindowHandle as Rwh;
1195
1196        let (surface, wl_window) = match unsafe { self.unconfigure_impl(device) } {
1197            Some((sc, wl_window)) => {
1198                if let Some(window) = wl_window {
1199                    wayland_sys::ffi_dispatch!(
1200                        wayland_sys::egl::wayland_egl_handle(),
1201                        wl_egl_window_resize,
1202                        window,
1203                        config.extent.width as i32,
1204                        config.extent.height as i32,
1205                        0,
1206                        0,
1207                    );
1208                }
1209
1210                (sc, wl_window)
1211            }
1212            None => {
1213                let mut wl_window = None;
1214                let (mut temp_xlib_handle, mut temp_xcb_handle);
1215                let native_window_ptr = match (self.wsi.kind, self.raw_window_handle) {
1216                    (WindowKind::Unknown | WindowKind::X11, Rwh::Xlib(handle)) => {
1217                        temp_xlib_handle = handle.window;
1218                        ptr::from_mut(&mut temp_xlib_handle).cast::<ffi::c_void>()
1219                    }
1220                    (WindowKind::AngleX11, Rwh::Xlib(handle)) => handle.window as *mut ffi::c_void,
1221                    (WindowKind::Unknown | WindowKind::X11, Rwh::Xcb(handle)) => {
1222                        temp_xcb_handle = handle.window;
1223                        ptr::from_mut(&mut temp_xcb_handle).cast::<ffi::c_void>()
1224                    }
1225                    (WindowKind::AngleX11, Rwh::Xcb(handle)) => {
1226                        handle.window.get() as *mut ffi::c_void
1227                    }
1228                    (WindowKind::Unknown, Rwh::AndroidNdk(handle)) => {
1229                        handle.a_native_window.as_ptr()
1230                    }
1231                    (WindowKind::Unknown, Rwh::OhosNdk(handle)) => handle.native_window.as_ptr(),
1232                    #[cfg(unix)]
1233                    (WindowKind::Wayland, Rwh::Wayland(handle)) => {
1234                        let window = wayland_sys::ffi_dispatch!(
1235                            wayland_sys::egl::wayland_egl_handle(),
1236                            wl_egl_window_create,
1237                            handle.surface.as_ptr().cast(),
1238                            config.extent.width as i32,
1239                            config.extent.height as i32,
1240                        );
1241                        wl_window = Some(window);
1242                        window.cast()
1243                    }
1244                    #[cfg(Emscripten)]
1245                    (WindowKind::Unknown, Rwh::Web(handle)) => handle.id as *mut ffi::c_void,
1246                    (WindowKind::Unknown, Rwh::Win32(handle)) => {
1247                        handle.hwnd.get() as *mut ffi::c_void
1248                    }
1249                    (WindowKind::Unknown, Rwh::AppKit(handle)) => {
1250                        #[cfg(not(target_os = "macos"))]
1251                        let window_ptr = handle.ns_view.as_ptr();
1252                        #[cfg(target_os = "macos")]
1253                        let window_ptr = {
1254                            use objc2::msg_send;
1255                            use objc2::runtime::AnyObject;
1256                            // ns_view always have a layer and don't need to verify that it exists.
1257                            let layer: *mut AnyObject =
1258                                msg_send![handle.ns_view.as_ptr().cast::<AnyObject>(), layer];
1259                            layer.cast::<ffi::c_void>()
1260                        };
1261                        window_ptr
1262                    }
1263                    _ => {
1264                        log::warn!(
1265                            "Initialized platform {:?} doesn't work with window {:?}",
1266                            self.wsi.kind,
1267                            self.raw_window_handle
1268                        );
1269                        return Err(crate::SurfaceError::Other("incompatible window kind"));
1270                    }
1271                };
1272
1273                let mut attributes = vec![
1274                    khronos_egl::RENDER_BUFFER,
1275                    // We don't want any of the buffering done by the driver, because we
1276                    // manage a swapchain on our side.
1277                    // Some drivers just fail on surface creation seeing `EGL_SINGLE_BUFFER`.
1278                    if cfg!(any(
1279                        target_os = "android",
1280                        target_os = "macos",
1281                        target_env = "ohos"
1282                    )) || cfg!(windows)
1283                        || self.wsi.kind == WindowKind::AngleX11
1284                    {
1285                        khronos_egl::BACK_BUFFER
1286                    } else {
1287                        khronos_egl::SINGLE_BUFFER
1288                    },
1289                ];
1290                if config.format.is_srgb() {
1291                    match self.srgb_kind {
1292                        SrgbFrameBufferKind::None => {}
1293                        SrgbFrameBufferKind::Core => {
1294                            attributes.push(khronos_egl::GL_COLORSPACE);
1295                            attributes.push(khronos_egl::GL_COLORSPACE_SRGB);
1296                        }
1297                        SrgbFrameBufferKind::Khr => {
1298                            attributes.push(EGL_GL_COLORSPACE_KHR as i32);
1299                            attributes.push(EGL_GL_COLORSPACE_SRGB_KHR as i32);
1300                        }
1301                    }
1302                }
1303                attributes.push(khronos_egl::ATTRIB_NONE as i32);
1304
1305                #[cfg(not(Emscripten))]
1306                let egl1_5 = self.egl.instance.upcast::<khronos_egl::EGL1_5>();
1307
1308                #[cfg(Emscripten)]
1309                let egl1_5: Option<&Arc<EglInstance>> = Some(&self.egl.instance);
1310
1311                // Careful, we can still be in 1.4 version even if `upcast` succeeds
1312                let raw_result = match egl1_5 {
1313                    Some(egl) if self.wsi.kind != WindowKind::Unknown => {
1314                        let attributes_usize = attributes
1315                            .into_iter()
1316                            .map(|v| v as usize)
1317                            .collect::<Vec<_>>();
1318                        unsafe {
1319                            egl.create_platform_window_surface(
1320                                self.egl.display,
1321                                self.config,
1322                                native_window_ptr,
1323                                &attributes_usize,
1324                            )
1325                        }
1326                    }
1327                    _ => unsafe {
1328                        self.egl.instance.create_window_surface(
1329                            self.egl.display,
1330                            self.config,
1331                            native_window_ptr,
1332                            Some(&attributes),
1333                        )
1334                    },
1335                };
1336
1337                match raw_result {
1338                    Ok(raw) => (raw, wl_window),
1339                    Err(e) => {
1340                        log::warn!("Error in create_window_surface: {e:?}");
1341                        return Err(crate::SurfaceError::Lost);
1342                    }
1343                }
1344            }
1345        };
1346
1347        let format_desc = device.shared.describe_texture_format(config.format);
1348        let gl = &device.shared.context.lock();
1349        let renderbuffer = unsafe { gl.create_renderbuffer() }.map_err(|error| {
1350            log::error!("Internal swapchain renderbuffer creation failed: {error}");
1351            crate::DeviceError::OutOfMemory
1352        })?;
1353        unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(renderbuffer)) };
1354        unsafe {
1355            gl.renderbuffer_storage(
1356                glow::RENDERBUFFER,
1357                format_desc.internal,
1358                config.extent.width as _,
1359                config.extent.height as _,
1360            )
1361        };
1362        let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| {
1363            log::error!("Internal swapchain framebuffer creation failed: {error}");
1364            crate::DeviceError::OutOfMemory
1365        })?;
1366        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) };
1367        unsafe {
1368            gl.framebuffer_renderbuffer(
1369                glow::READ_FRAMEBUFFER,
1370                glow::COLOR_ATTACHMENT0,
1371                glow::RENDERBUFFER,
1372                Some(renderbuffer),
1373            )
1374        };
1375        unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
1376        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
1377
1378        let mut swapchain = self.swapchain.write();
1379        *swapchain = Some(Swapchain {
1380            surface,
1381            wl_window,
1382            renderbuffer,
1383            framebuffer,
1384            extent: config.extent,
1385            format: config.format,
1386            format_desc,
1387            sample_type: wgt::TextureSampleType::Float { filterable: false },
1388        });
1389
1390        Ok(())
1391    }
1392
1393    unsafe fn unconfigure(&self, device: &super::Device) {
1394        if let Some((surface, wl_window)) = unsafe { self.unconfigure_impl(device) } {
1395            self.egl
1396                .instance
1397                .destroy_surface(self.egl.display, surface)
1398                .unwrap();
1399            if let Some(window) = wl_window {
1400                wayland_sys::ffi_dispatch!(
1401                    wayland_sys::egl::wayland_egl_handle(),
1402                    wl_egl_window_destroy,
1403                    window,
1404                );
1405            }
1406        }
1407    }
1408
1409    unsafe fn acquire_texture(
1410        &self,
1411        _timeout_ms: Option<Duration>, //TODO
1412        _fence: &super::Fence,
1413    ) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
1414        let swapchain = self.swapchain.read();
1415        let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other(
1416            "Surface has no swap-chain configured",
1417        ))?;
1418        let texture = super::Texture {
1419            inner: super::TextureInner::Renderbuffer {
1420                raw: sc.renderbuffer,
1421            },
1422            drop_guard: None,
1423            array_layer_count: 1,
1424            mip_level_count: 1,
1425            format: sc.format,
1426            format_desc: sc.format_desc.clone(),
1427            copy_size: crate::CopyExtent {
1428                width: sc.extent.width,
1429                height: sc.extent.height,
1430                depth: 1,
1431            },
1432        };
1433        Ok(Some(crate::AcquiredSurfaceTexture {
1434            texture,
1435            suboptimal: false,
1436        }))
1437    }
1438    unsafe fn discard_texture(&self, _texture: super::Texture) {}
1439}