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
457        let mut khr_context_flags = 0;
458        let supports_khr_context = display_extensions.contains("EGL_KHR_create_context");
459
460        let mut context_attributes = vec![];
461        let mut gl_context_attributes = vec![];
462        let mut gles_context_attributes = vec![];
463        gl_context_attributes.push(khronos_egl::CONTEXT_MAJOR_VERSION);
464        gl_context_attributes.push(3);
465        gl_context_attributes.push(khronos_egl::CONTEXT_MINOR_VERSION);
466        gl_context_attributes.push(3);
467        if supports_opengl && force_gles_minor_version != wgt::Gles3MinorVersion::Automatic {
468            log::warn!("Ignoring specified GLES minor version as OpenGL is used");
469        }
470        gles_context_attributes.push(khronos_egl::CONTEXT_MAJOR_VERSION);
471        gles_context_attributes.push(3); // Request GLES 3.0 or higher
472        if force_gles_minor_version != wgt::Gles3MinorVersion::Automatic {
473            gles_context_attributes.push(khronos_egl::CONTEXT_MINOR_VERSION);
474            gles_context_attributes.push(match force_gles_minor_version {
475                wgt::Gles3MinorVersion::Automatic => unreachable!(),
476                wgt::Gles3MinorVersion::Version0 => 0,
477                wgt::Gles3MinorVersion::Version1 => 1,
478                wgt::Gles3MinorVersion::Version2 => 2,
479            });
480        }
481        if flags.contains(wgt::InstanceFlags::DEBUG) {
482            if version >= (1, 5) {
483                log::debug!("\tEGL context: +debug");
484                context_attributes.push(khronos_egl::CONTEXT_OPENGL_DEBUG);
485                context_attributes.push(khronos_egl::TRUE as _);
486            } else if supports_khr_context {
487                log::debug!("\tEGL context: +debug KHR");
488                khr_context_flags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR;
489            } else {
490                log::debug!("\tEGL context: -debug");
491            }
492        }
493
494        if khr_context_flags != 0 {
495            context_attributes.push(EGL_CONTEXT_FLAGS_KHR);
496            context_attributes.push(khr_context_flags);
497        }
498
499        gl_context_attributes.extend(&context_attributes);
500        gles_context_attributes.extend(&context_attributes);
501
502        let context = {
503            #[derive(Copy, Clone)]
504            enum Robustness {
505                Core,
506                Ext,
507            }
508
509            let robustness = if version >= (1, 5) {
510                Some(Robustness::Core)
511            } else if display_extensions.contains("EGL_EXT_create_context_robustness") {
512                Some(Robustness::Ext)
513            } else {
514                None
515            };
516
517            let create_context = |api, base_attributes: &[khronos_egl::Int]| {
518                egl.bind_api(api)?;
519
520                let mut robustness = robustness;
521                loop {
522                    let robustness_attributes = match robustness {
523                        Some(Robustness::Core) => {
524                            vec![
525                                khronos_egl::CONTEXT_OPENGL_ROBUST_ACCESS,
526                                khronos_egl::TRUE as _,
527                                khronos_egl::NONE,
528                            ]
529                        }
530                        Some(Robustness::Ext) => {
531                            vec![
532                                EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT,
533                                khronos_egl::TRUE as _,
534                                khronos_egl::NONE,
535                            ]
536                        }
537                        None => vec![khronos_egl::NONE],
538                    };
539
540                    let mut context_attributes = base_attributes.to_vec();
541                    context_attributes.extend(&robustness_attributes);
542
543                    match egl.create_context(display, config, None, &context_attributes) {
544                        Ok(context) => {
545                            match robustness {
546                                Some(Robustness::Core) => {
547                                    log::debug!("\tEGL context: +robust access");
548                                }
549                                Some(Robustness::Ext) => {
550                                    log::debug!("\tEGL context: +robust access EXT");
551                                }
552                                None => {
553                                    log::debug!("\tEGL context: -robust access");
554                                }
555                            }
556                            return Ok(context);
557                        }
558
559                        // Robust access context creation can fail with different error codes
560                        // depending on the EGL path. Retry with a lower robustness level.
561                        Err(
562                            khronos_egl::Error::BadAttribute
563                            | khronos_egl::Error::BadMatch
564                            | khronos_egl::Error::BadConfig,
565                        ) if robustness.is_some() => {
566                            robustness = match robustness {
567                                Some(Robustness::Core)
568                                    if display_extensions
569                                        .contains("EGL_EXT_create_context_robustness") =>
570                                {
571                                    Some(Robustness::Ext)
572                                }
573                                _ => None,
574                            };
575                            continue;
576                        }
577
578                        Err(e) => return Err(e),
579                    }
580                }
581            };
582
583            let result = if supports_opengl {
584                create_context(khronos_egl::OPENGL_API, &gl_context_attributes).or_else(
585                    |gl_error| {
586                        log::debug!("Failed to create desktop OpenGL context: {gl_error}, falling back to OpenGL ES");
587                        create_context(khronos_egl::OPENGL_ES_API, &gles_context_attributes)
588                    },
589                )
590            } else {
591                create_context(khronos_egl::OPENGL_ES_API, &gles_context_attributes)
592            };
593
594            result.map_err(|e| {
595                crate::InstanceError::with_source(
596                    String::from("unable to create OpenGL or GLES 3.x context"),
597                    e,
598                )
599            })
600        }?;
601
602        // Testing if context can be binded without surface
603        // and creating dummy pbuffer surface if not.
604        let pbuffer = if version >= (1, 5)
605            || display_extensions.contains("EGL_KHR_surfaceless_context")
606            || cfg!(Emscripten)
607        {
608            log::debug!("\tEGL context: +surfaceless");
609            None
610        } else {
611            let attributes = [
612                khronos_egl::WIDTH,
613                1,
614                khronos_egl::HEIGHT,
615                1,
616                khronos_egl::NONE,
617            ];
618            egl.create_pbuffer_surface(display, config, &attributes)
619                .map(Some)
620                .map_err(|e| {
621                    crate::InstanceError::with_source(
622                        String::from("error in create_pbuffer_surface"),
623                        e,
624                    )
625                })?
626        };
627
628        Ok(Self {
629            egl: EglContext {
630                instance: egl,
631                display,
632                raw: context,
633                pbuffer,
634                version,
635            },
636            version,
637            supports_native_window,
638            config,
639            srgb_kind,
640        })
641    }
642}
643
644impl Drop for Inner {
645    fn drop(&mut self) {
646        // ERROR: Since EglContext is erroneously Clone, these handles could be copied and
647        // accidentally used elsewhere outside of Inner, despite us assuming ownership and
648        // destroying the handles here.
649        if let Err(e) = self
650            .egl
651            .instance
652            .destroy_context(self.egl.display, self.egl.raw)
653        {
654            log::warn!("Error in destroy_context: {e:?}");
655        }
656
657        if let Err(e) = terminate_display(&self.egl.instance, self.egl.display) {
658            log::warn!("Error in terminate: {e:?}");
659        }
660    }
661}
662
663#[derive(Clone, Copy, Debug, PartialEq)]
664enum WindowKind {
665    Wayland,
666    X11,
667    AngleX11,
668    Unknown,
669}
670
671#[derive(Clone, Debug)]
672struct WindowSystemInterface {
673    kind: WindowKind,
674}
675
676pub struct Instance {
677    wsi: WindowSystemInterface,
678    flags: wgt::InstanceFlags,
679    options: wgt::GlBackendOptions,
680    inner: Mutex<Inner>,
681}
682
683impl Instance {
684    pub fn raw_display(&self) -> khronos_egl::Display {
685        self.inner
686            .try_lock()
687            .expect("Could not lock instance. This is most-likely a deadlock.")
688            .egl
689            .display
690    }
691
692    /// Returns the version of the EGL display.
693    pub fn egl_version(&self) -> (i32, i32) {
694        self.inner
695            .try_lock()
696            .expect("Could not lock instance. This is most-likely a deadlock.")
697            .version
698    }
699
700    pub fn egl_config(&self) -> khronos_egl::Config {
701        self.inner
702            .try_lock()
703            .expect("Could not lock instance. This is most-likely a deadlock.")
704            .config
705    }
706}
707
708unsafe impl Send for Instance {}
709unsafe impl Sync for Instance {}
710
711impl crate::Instance for Instance {
712    type A = super::Api;
713
714    unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
715        use raw_window_handle::RawDisplayHandle as Rdh;
716
717        profiling::scope!("Init OpenGL (EGL) Backend");
718        #[cfg(Emscripten)]
719        let egl_result: Result<EglInstance, khronos_egl::Error> =
720            Ok(khronos_egl::Instance::new(khronos_egl::Static));
721
722        #[cfg(not(Emscripten))]
723        let egl_result = if cfg!(windows) {
724            unsafe {
725                khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required_from_filename(
726                    "libEGL.dll",
727                )
728            }
729        } else if cfg!(target_vendor = "apple") {
730            unsafe {
731                khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required_from_filename(
732                    "libEGL.dylib",
733                )
734            }
735        } else {
736            unsafe { khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required() }
737        };
738        let egl = egl_result
739            .map(Arc::new)
740            .map_err(instance_err("unable to open libEGL"))?;
741
742        let client_extensions = egl.query_string(None, khronos_egl::EXTENSIONS);
743
744        let client_ext_str = match client_extensions {
745            Ok(ext) => ext.to_string_lossy().into_owned(),
746            Err(_) => String::new(),
747        };
748        log::debug!(
749            "Client extensions: {:#?}",
750            client_ext_str.split_whitespace().collect::<Vec<_>>()
751        );
752
753        #[cfg(not(Emscripten))]
754        let egl1_5 = egl.upcast::<khronos_egl::EGL1_5>();
755
756        #[cfg(Emscripten)]
757        let egl1_5: Option<&Arc<EglInstance>> = Some(&egl);
758
759        let (display, wsi_kind) = match (desc.display.map(|d| d.as_raw()), egl1_5) {
760            (Some(Rdh::Wayland(wayland_display_handle)), Some(egl))
761                if client_ext_str.contains("EGL_EXT_platform_wayland") =>
762            {
763                log::debug!("Using Wayland platform");
764                let display_attributes = [khronos_egl::ATTRIB_NONE];
765                let display = unsafe {
766                    egl.get_platform_display(
767                        EGL_PLATFORM_WAYLAND_KHR,
768                        wayland_display_handle.display.as_ptr(),
769                        &display_attributes,
770                    )
771                }
772                .map_err(instance_err("failed to get Wayland display"))?;
773                (display, WindowKind::Wayland)
774            }
775            (Some(Rdh::Xlib(xlib_display_handle)), Some(egl))
776                if client_ext_str.contains("EGL_EXT_platform_x11") =>
777            {
778                log::debug!("Using X11 platform");
779                let display_attributes = [khronos_egl::ATTRIB_NONE];
780                let display = unsafe {
781                    egl.get_platform_display(
782                        EGL_PLATFORM_X11_KHR,
783                        xlib_display_handle
784                            .display
785                            .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr),
786                        &display_attributes,
787                    )
788                }
789                .map_err(instance_err("failed to get X11 display"))?;
790                (display, WindowKind::X11)
791            }
792            (Some(Rdh::Xlib(xlib_display_handle)), Some(egl))
793                if client_ext_str.contains("EGL_ANGLE_platform_angle") =>
794            {
795                log::debug!("Using Angle platform with X11");
796                let display_attributes = [
797                    EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE as khronos_egl::Attrib,
798                    EGL_PLATFORM_X11_KHR as khronos_egl::Attrib,
799                    EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED as khronos_egl::Attrib,
800                    usize::from(desc.flags.contains(wgt::InstanceFlags::VALIDATION)),
801                    khronos_egl::ATTRIB_NONE,
802                ];
803                let display = unsafe {
804                    egl.get_platform_display(
805                        EGL_PLATFORM_ANGLE_ANGLE,
806                        xlib_display_handle
807                            .display
808                            .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr),
809                        &display_attributes,
810                    )
811                }
812                .map_err(instance_err("failed to get Angle display"))?;
813                (display, WindowKind::AngleX11)
814            }
815            (Some(Rdh::Xcb(_xcb_display_handle)), Some(_egl)) => todo!("xcb"),
816            x if client_ext_str.contains("EGL_MESA_platform_surfaceless") => {
817                log::debug!(
818                    "No (or unknown) windowing system ({x:?}) present. Using surfaceless platform"
819                );
820                #[allow(
821                    clippy::unnecessary_literal_unwrap,
822                    reason = "this is only a literal on Emscripten"
823                )]
824                // 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
825                let egl = egl1_5.expect("Failed to get EGL 1.5 for surfaceless");
826                let display = unsafe {
827                    egl.get_platform_display(
828                        EGL_PLATFORM_SURFACELESS_MESA,
829                        khronos_egl::DEFAULT_DISPLAY,
830                        &[khronos_egl::ATTRIB_NONE],
831                    )
832                }
833                .map_err(instance_err("failed to get MESA surfaceless display"))?;
834                (display, WindowKind::Unknown)
835            }
836            x => {
837                log::debug!(
838                    "No (or unknown) windowing system {x:?} and EGL_MESA_platform_surfaceless not available. Using default platform"
839                );
840                let display =
841                    unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.ok_or_else(|| {
842                        crate::InstanceError::new("Failed to get default display".into())
843                    })?;
844                (display, WindowKind::Unknown)
845            }
846        };
847
848        if desc.flags.contains(wgt::InstanceFlags::VALIDATION)
849            && client_ext_str.contains("EGL_KHR_debug")
850        {
851            log::debug!("Enabling EGL debug output");
852            let function: EglDebugMessageControlFun = {
853                let addr = egl
854                    .get_proc_address("eglDebugMessageControlKHR")
855                    .ok_or_else(|| {
856                        crate::InstanceError::new(
857                            "failed to get `eglDebugMessageControlKHR` proc address".into(),
858                        )
859                    })?;
860                unsafe { core::mem::transmute(addr) }
861            };
862            let attributes = [
863                EGL_DEBUG_MSG_CRITICAL_KHR as khronos_egl::Attrib,
864                1,
865                EGL_DEBUG_MSG_ERROR_KHR as khronos_egl::Attrib,
866                1,
867                EGL_DEBUG_MSG_WARN_KHR as khronos_egl::Attrib,
868                1,
869                EGL_DEBUG_MSG_INFO_KHR as khronos_egl::Attrib,
870                1,
871                khronos_egl::ATTRIB_NONE,
872            ];
873            unsafe { (function)(Some(egl_debug_proc), attributes.as_ptr()) };
874        }
875
876        let inner = Inner::create(
877            desc.flags,
878            egl,
879            display,
880            desc.backend_options.gl.gles_minor_version,
881        )?;
882
883        Ok(Instance {
884            wsi: WindowSystemInterface { kind: wsi_kind },
885            flags: desc.flags,
886            options: desc.backend_options.gl.clone(),
887            inner: Mutex::new(inner),
888        })
889    }
890
891    unsafe fn create_surface(
892        &self,
893        display_handle: raw_window_handle::RawDisplayHandle,
894        window_handle: raw_window_handle::RawWindowHandle,
895    ) -> Result<Surface, crate::InstanceError> {
896        use raw_window_handle::RawWindowHandle as Rwh;
897
898        let inner = self.inner.lock();
899
900        match (window_handle, display_handle) {
901            (Rwh::Xlib(_), _) => {}
902            (Rwh::Xcb(_), _) => {}
903            (Rwh::Win32(_), _) => {}
904            (Rwh::AppKit(_), _) => {}
905            (Rwh::OhosNdk(_), _) => {}
906            #[cfg(target_os = "android")]
907            (Rwh::AndroidNdk(handle), _) => {
908                let format = inner
909                    .egl
910                    .instance
911                    .get_config_attrib(
912                        inner.egl.display,
913                        inner.config,
914                        khronos_egl::NATIVE_VISUAL_ID,
915                    )
916                    .map_err(instance_err("failed to get config NATIVE_VISUAL_ID"))?;
917
918                let ret = unsafe {
919                    ndk_sys::ANativeWindow_setBuffersGeometry(
920                        handle
921                            .a_native_window
922                            .as_ptr()
923                            .cast::<ndk_sys::ANativeWindow>(),
924                        0,
925                        0,
926                        format,
927                    )
928                };
929
930                if ret != 0 {
931                    return Err(crate::InstanceError::new(format!(
932                        "error {ret} returned from ANativeWindow_setBuffersGeometry",
933                    )));
934                }
935            }
936            (Rwh::Wayland(_), _) => {}
937            #[cfg(Emscripten)]
938            (Rwh::Web(_), _) => {}
939            other => {
940                return Err(crate::InstanceError::new(format!(
941                    "unsupported window: {other:?}"
942                )));
943            }
944        };
945
946        inner.egl.unmake_current();
947
948        Ok(Surface {
949            egl: inner.egl.clone(),
950            wsi: self.wsi.clone(),
951            config: inner.config,
952            presentable: inner.supports_native_window,
953            raw_window_handle: window_handle,
954            swapchain: RwLock::new(None),
955            srgb_kind: inner.srgb_kind,
956        })
957    }
958
959    unsafe fn enumerate_adapters(
960        &self,
961        _surface_hint: Option<&Surface>,
962    ) -> Vec<crate::ExposedAdapter<super::Api>> {
963        let inner = self.inner.lock();
964        inner.egl.make_current();
965
966        let mut gl = unsafe {
967            glow::Context::from_loader_function(|name| {
968                inner
969                    .egl
970                    .instance
971                    .get_proc_address(name)
972                    .map_or(ptr::null(), |p| p as *const _)
973            })
974        };
975
976        // In contrast to OpenGL ES, OpenGL requires explicitly enabling sRGB conversions,
977        // as otherwise the user has to do the sRGB conversion.
978        if !matches!(inner.srgb_kind, SrgbFrameBufferKind::None) {
979            unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
980        }
981
982        if self.flags.contains(wgt::InstanceFlags::DEBUG) && gl.supports_debug() {
983            log::debug!("Max label length: {}", unsafe {
984                gl.get_parameter_i32(glow::MAX_LABEL_LENGTH)
985            });
986        }
987
988        if self.flags.contains(wgt::InstanceFlags::VALIDATION) && gl.supports_debug() {
989            log::debug!("Enabling GLES debug output");
990            unsafe { gl.enable(glow::DEBUG_OUTPUT) };
991            unsafe { gl.debug_message_callback(super::gl_debug_message_callback) };
992        }
993
994        // Wrap in ManuallyDrop to make it easier to "current" the GL context before dropping this
995        // GLOW context, which could also happen if a panic occurs after we uncurrent the context
996        // below but before AdapterContext is constructed.
997        let gl = ManuallyDrop::new(gl);
998        inner.egl.unmake_current();
999
1000        unsafe {
1001            super::Adapter::expose(
1002                AdapterContext {
1003                    glow: Mutex::new(gl),
1004                    // ERROR: Copying owned reference handles here, be careful to not drop them!
1005                    egl: Some(inner.egl.clone()),
1006                },
1007                self.options.clone(),
1008            )
1009        }
1010        .into_iter()
1011        .collect()
1012    }
1013}
1014
1015impl super::Adapter {
1016    /// Creates a new external adapter using the specified loader function.
1017    ///
1018    /// # Safety
1019    ///
1020    /// - The underlying OpenGL ES context must be current.
1021    /// - The underlying OpenGL ES context must be current when interfacing with any objects returned by
1022    ///   wgpu-hal from this adapter.
1023    /// - The underlying OpenGL ES context must be current when dropping this adapter and when
1024    ///   dropping any objects returned from this adapter.
1025    pub unsafe fn new_external(
1026        fun: impl FnMut(&str) -> *const ffi::c_void,
1027        options: wgt::GlBackendOptions,
1028    ) -> Option<crate::ExposedAdapter<super::Api>> {
1029        let context = unsafe { glow::Context::from_loader_function(fun) };
1030        unsafe {
1031            Self::expose(
1032                AdapterContext {
1033                    glow: Mutex::new(ManuallyDrop::new(context)),
1034                    egl: None,
1035                },
1036                options,
1037            )
1038        }
1039    }
1040
1041    pub fn adapter_context(&self) -> &AdapterContext {
1042        &self.shared.context
1043    }
1044}
1045
1046impl super::Device {
1047    /// Returns the underlying EGL context.
1048    pub fn context(&self) -> &AdapterContext {
1049        &self.shared.context
1050    }
1051}
1052
1053#[derive(Debug)]
1054pub struct Swapchain {
1055    surface: khronos_egl::Surface,
1056    wl_window: Option<*mut wayland_sys::egl::wl_egl_window>,
1057    framebuffer: glow::Framebuffer,
1058    renderbuffer: glow::Renderbuffer,
1059    /// Extent because the window lies
1060    extent: wgt::Extent3d,
1061    format: wgt::TextureFormat,
1062    format_desc: super::TextureFormatDesc,
1063    #[allow(unused)]
1064    sample_type: wgt::TextureSampleType,
1065}
1066
1067#[derive(Debug)]
1068pub struct Surface {
1069    egl: EglContext,
1070    wsi: WindowSystemInterface,
1071    config: khronos_egl::Config,
1072    pub(super) presentable: bool,
1073    raw_window_handle: raw_window_handle::RawWindowHandle,
1074    swapchain: RwLock<Option<Swapchain>>,
1075    srgb_kind: SrgbFrameBufferKind,
1076}
1077
1078unsafe impl Send for Surface {}
1079unsafe impl Sync for Surface {}
1080
1081impl Surface {
1082    pub(super) unsafe fn present(
1083        &self,
1084        _suf_texture: super::Texture,
1085        context: &AdapterContext,
1086    ) -> Result<(), crate::SurfaceError> {
1087        let gl = unsafe { context.get_without_egl_lock() };
1088        let swapchain = self.swapchain.read();
1089        let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other(
1090            "Surface has no swap-chain configured",
1091        ))?;
1092
1093        self.egl
1094            .instance
1095            .make_current(
1096                self.egl.display,
1097                Some(sc.surface),
1098                Some(sc.surface),
1099                Some(self.egl.raw),
1100            )
1101            .map_err(|e| {
1102                log::error!("make_current(surface) failed: {e}");
1103                crate::SurfaceError::Lost
1104            })?;
1105
1106        unsafe { gl.disable(glow::SCISSOR_TEST) };
1107        unsafe { gl.color_mask(true, true, true, true) };
1108
1109        unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
1110        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer)) };
1111
1112        if !matches!(self.srgb_kind, SrgbFrameBufferKind::None) {
1113            // Disable sRGB conversions for `glBlitFramebuffer` as behavior does diverge between
1114            // drivers and formats otherwise and we want to ensure no sRGB conversions happen.
1115            unsafe { gl.disable(glow::FRAMEBUFFER_SRGB) };
1116        }
1117
1118        // Note the Y-flipping here. GL's presentation is not flipped,
1119        // but main rendering is. Therefore, we Y-flip the output positions
1120        // in the shader, and also this blit.
1121        unsafe {
1122            gl.blit_framebuffer(
1123                0,
1124                sc.extent.height as i32,
1125                sc.extent.width as i32,
1126                0,
1127                0,
1128                0,
1129                sc.extent.width as i32,
1130                sc.extent.height as i32,
1131                glow::COLOR_BUFFER_BIT,
1132                glow::NEAREST,
1133            )
1134        };
1135
1136        if !matches!(self.srgb_kind, SrgbFrameBufferKind::None) {
1137            unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
1138        }
1139
1140        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
1141
1142        self.egl
1143            .instance
1144            .swap_buffers(self.egl.display, sc.surface)
1145            .map_err(|e| {
1146                log::error!("swap_buffers failed: {e}");
1147                crate::SurfaceError::Lost
1148                // TODO: should we unset the current context here?
1149            })?;
1150        self.egl
1151            .instance
1152            .make_current(self.egl.display, None, None, None)
1153            .map_err(|e| {
1154                log::error!("make_current(null) failed: {e}");
1155                crate::SurfaceError::Lost
1156            })?;
1157
1158        Ok(())
1159    }
1160
1161    unsafe fn unconfigure_impl(
1162        &self,
1163        device: &super::Device,
1164    ) -> Option<(
1165        khronos_egl::Surface,
1166        Option<*mut wayland_sys::egl::wl_egl_window>,
1167    )> {
1168        let gl = &device.shared.context.lock();
1169        match self.swapchain.write().take() {
1170            Some(sc) => {
1171                unsafe { gl.delete_renderbuffer(sc.renderbuffer) };
1172                unsafe { gl.delete_framebuffer(sc.framebuffer) };
1173                Some((sc.surface, sc.wl_window))
1174            }
1175            None => None,
1176        }
1177    }
1178
1179    pub fn supports_srgb(&self) -> bool {
1180        match self.srgb_kind {
1181            SrgbFrameBufferKind::None => false,
1182            _ => true,
1183        }
1184    }
1185}
1186
1187impl crate::Surface for Surface {
1188    type A = super::Api;
1189
1190    unsafe fn configure(
1191        &self,
1192        device: &super::Device,
1193        config: &crate::SurfaceConfiguration,
1194    ) -> Result<(), crate::SurfaceError> {
1195        use raw_window_handle::RawWindowHandle as Rwh;
1196
1197        let (surface, wl_window) = match unsafe { self.unconfigure_impl(device) } {
1198            Some((sc, wl_window)) => {
1199                if let Some(window) = wl_window {
1200                    wayland_sys::ffi_dispatch!(
1201                        wayland_sys::egl::wayland_egl_handle(),
1202                        wl_egl_window_resize,
1203                        window,
1204                        config.extent.width as i32,
1205                        config.extent.height as i32,
1206                        0,
1207                        0,
1208                    );
1209                }
1210
1211                (sc, wl_window)
1212            }
1213            None => {
1214                let mut wl_window = None;
1215                let (mut temp_xlib_handle, mut temp_xcb_handle);
1216                let native_window_ptr = match (self.wsi.kind, self.raw_window_handle) {
1217                    (WindowKind::Unknown | WindowKind::X11, Rwh::Xlib(handle)) => {
1218                        temp_xlib_handle = handle.window;
1219                        ptr::from_mut(&mut temp_xlib_handle).cast::<ffi::c_void>()
1220                    }
1221                    (WindowKind::AngleX11, Rwh::Xlib(handle)) => handle.window as *mut ffi::c_void,
1222                    (WindowKind::Unknown | WindowKind::X11, Rwh::Xcb(handle)) => {
1223                        temp_xcb_handle = handle.window;
1224                        ptr::from_mut(&mut temp_xcb_handle).cast::<ffi::c_void>()
1225                    }
1226                    (WindowKind::AngleX11, Rwh::Xcb(handle)) => {
1227                        handle.window.get() as *mut ffi::c_void
1228                    }
1229                    (WindowKind::Unknown, Rwh::AndroidNdk(handle)) => {
1230                        handle.a_native_window.as_ptr()
1231                    }
1232                    (WindowKind::Unknown, Rwh::OhosNdk(handle)) => handle.native_window.as_ptr(),
1233                    #[cfg(unix)]
1234                    (WindowKind::Wayland, Rwh::Wayland(handle)) => {
1235                        let window = wayland_sys::ffi_dispatch!(
1236                            wayland_sys::egl::wayland_egl_handle(),
1237                            wl_egl_window_create,
1238                            handle.surface.as_ptr().cast(),
1239                            config.extent.width as i32,
1240                            config.extent.height as i32,
1241                        );
1242                        wl_window = Some(window);
1243                        window.cast()
1244                    }
1245                    #[cfg(Emscripten)]
1246                    (WindowKind::Unknown, Rwh::Web(handle)) => handle.id as *mut ffi::c_void,
1247                    (WindowKind::Unknown, Rwh::Win32(handle)) => {
1248                        handle.hwnd.get() as *mut ffi::c_void
1249                    }
1250                    (WindowKind::Unknown, Rwh::AppKit(handle)) => {
1251                        #[cfg(not(target_os = "macos"))]
1252                        let window_ptr = handle.ns_view.as_ptr();
1253                        #[cfg(target_os = "macos")]
1254                        let window_ptr = {
1255                            use objc2::msg_send;
1256                            use objc2::runtime::AnyObject;
1257                            // ns_view always have a layer and don't need to verify that it exists.
1258                            let layer: *mut AnyObject =
1259                                msg_send![handle.ns_view.as_ptr().cast::<AnyObject>(), layer];
1260                            layer.cast::<ffi::c_void>()
1261                        };
1262                        window_ptr
1263                    }
1264                    _ => {
1265                        log::warn!(
1266                            "Initialized platform {:?} doesn't work with window {:?}",
1267                            self.wsi.kind,
1268                            self.raw_window_handle
1269                        );
1270                        return Err(crate::SurfaceError::Other("incompatible window kind"));
1271                    }
1272                };
1273
1274                let mut attributes = vec![
1275                    khronos_egl::RENDER_BUFFER,
1276                    // We don't want any of the buffering done by the driver, because we
1277                    // manage a swapchain on our side.
1278                    // Some drivers just fail on surface creation seeing `EGL_SINGLE_BUFFER`.
1279                    if cfg!(any(
1280                        target_os = "android",
1281                        target_os = "macos",
1282                        target_env = "ohos"
1283                    )) || cfg!(windows)
1284                        || self.wsi.kind == WindowKind::AngleX11
1285                    {
1286                        khronos_egl::BACK_BUFFER
1287                    } else {
1288                        khronos_egl::SINGLE_BUFFER
1289                    },
1290                ];
1291                if config.format.is_srgb() {
1292                    match self.srgb_kind {
1293                        SrgbFrameBufferKind::None => {}
1294                        SrgbFrameBufferKind::Core => {
1295                            attributes.push(khronos_egl::GL_COLORSPACE);
1296                            attributes.push(khronos_egl::GL_COLORSPACE_SRGB);
1297                        }
1298                        SrgbFrameBufferKind::Khr => {
1299                            attributes.push(EGL_GL_COLORSPACE_KHR as i32);
1300                            attributes.push(EGL_GL_COLORSPACE_SRGB_KHR as i32);
1301                        }
1302                    }
1303                }
1304                attributes.push(khronos_egl::ATTRIB_NONE as i32);
1305
1306                #[cfg(not(Emscripten))]
1307                let egl1_5 = self.egl.instance.upcast::<khronos_egl::EGL1_5>();
1308
1309                #[cfg(Emscripten)]
1310                let egl1_5: Option<&Arc<EglInstance>> = Some(&self.egl.instance);
1311
1312                // Careful, we can still be in 1.4 version even if `upcast` succeeds
1313                let raw_result = match egl1_5 {
1314                    Some(egl) if self.wsi.kind != WindowKind::Unknown => {
1315                        let attributes_usize = attributes
1316                            .into_iter()
1317                            .map(|v| v as usize)
1318                            .collect::<Vec<_>>();
1319                        unsafe {
1320                            egl.create_platform_window_surface(
1321                                self.egl.display,
1322                                self.config,
1323                                native_window_ptr,
1324                                &attributes_usize,
1325                            )
1326                        }
1327                    }
1328                    _ => unsafe {
1329                        self.egl.instance.create_window_surface(
1330                            self.egl.display,
1331                            self.config,
1332                            native_window_ptr,
1333                            Some(&attributes),
1334                        )
1335                    },
1336                };
1337
1338                match raw_result {
1339                    Ok(raw) => (raw, wl_window),
1340                    Err(e) => {
1341                        log::warn!("Error in create_window_surface: {e:?}");
1342                        return Err(crate::SurfaceError::Lost);
1343                    }
1344                }
1345            }
1346        };
1347
1348        let format_desc = device.shared.describe_texture_format(config.format);
1349        let gl = &device.shared.context.lock();
1350        let renderbuffer = unsafe { gl.create_renderbuffer() }.map_err(|error| {
1351            log::error!("Internal swapchain renderbuffer creation failed: {error}");
1352            crate::DeviceError::OutOfMemory
1353        })?;
1354        unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(renderbuffer)) };
1355        unsafe {
1356            gl.renderbuffer_storage(
1357                glow::RENDERBUFFER,
1358                format_desc.internal,
1359                config.extent.width as _,
1360                config.extent.height as _,
1361            )
1362        };
1363        let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| {
1364            log::error!("Internal swapchain framebuffer creation failed: {error}");
1365            crate::DeviceError::OutOfMemory
1366        })?;
1367        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) };
1368        unsafe {
1369            gl.framebuffer_renderbuffer(
1370                glow::READ_FRAMEBUFFER,
1371                glow::COLOR_ATTACHMENT0,
1372                glow::RENDERBUFFER,
1373                Some(renderbuffer),
1374            )
1375        };
1376        unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
1377        unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
1378
1379        let mut swapchain = self.swapchain.write();
1380        *swapchain = Some(Swapchain {
1381            surface,
1382            wl_window,
1383            renderbuffer,
1384            framebuffer,
1385            extent: config.extent,
1386            format: config.format,
1387            format_desc,
1388            sample_type: wgt::TextureSampleType::Float { filterable: false },
1389        });
1390
1391        Ok(())
1392    }
1393
1394    unsafe fn unconfigure(&self, device: &super::Device) {
1395        if let Some((surface, wl_window)) = unsafe { self.unconfigure_impl(device) } {
1396            self.egl
1397                .instance
1398                .destroy_surface(self.egl.display, surface)
1399                .unwrap();
1400            if let Some(window) = wl_window {
1401                wayland_sys::ffi_dispatch!(
1402                    wayland_sys::egl::wayland_egl_handle(),
1403                    wl_egl_window_destroy,
1404                    window,
1405                );
1406            }
1407        }
1408    }
1409
1410    unsafe fn acquire_texture(
1411        &self,
1412        _timeout_ms: Option<Duration>, //TODO
1413        _fence: &super::Fence,
1414    ) -> Result<crate::AcquiredSurfaceTexture<super::Api>, crate::SurfaceError> {
1415        let swapchain = self.swapchain.read();
1416        let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other(
1417            "Surface has no swap-chain configured",
1418        ))?;
1419        let texture = super::Texture {
1420            inner: super::TextureInner::Renderbuffer {
1421                raw: sc.renderbuffer,
1422            },
1423            drop_guard: None,
1424            array_layer_count: 1,
1425            mip_level_count: 1,
1426            format: sc.format,
1427            format_desc: sc.format_desc.clone(),
1428            copy_size: crate::CopyExtent {
1429                width: sc.extent.width,
1430                height: sc.extent.height,
1431                depth: 1,
1432            },
1433        };
1434        Ok(crate::AcquiredSurfaceTexture {
1435            texture,
1436            suboptimal: false,
1437        })
1438    }
1439    unsafe fn discard_texture(&self, _texture: super::Texture) {}
1440}