1use alloc::{string::String, sync::Arc, vec::Vec};
2use core::{ffi, mem::ManuallyDrop, ptr, time::Duration};
3
4use glow::HasContext;
5use hashbrown::HashMap;
6use wgpu_sync::{Lazy, MappedMutexGuard, Mutex, MutexGuard, RwLock};
7
8const CONTEXT_LOCK_TIMEOUT_SECS: u64 = 6;
10
11const EGL_CONTEXT_FLAGS_KHR: i32 = 0x30FC;
12const EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR: i32 = 0x0001;
13const EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT: i32 = 0x30BF;
14const EGL_PLATFORM_WAYLAND_KHR: u32 = 0x31D8;
15const EGL_PLATFORM_X11_KHR: u32 = 0x31D5;
16const EGL_PLATFORM_XCB_EXT: u32 = 0x31DC;
17const EGL_PLATFORM_XCB_SCREEN_EXT: u32 = 0x31DE;
18const EGL_PLATFORM_ANGLE_ANGLE: u32 = 0x3202;
19const EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE: u32 = 0x348F;
20const EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED: u32 = 0x3451;
21const EGL_PLATFORM_SURFACELESS_MESA: u32 = 0x31DD;
22const EGL_GL_COLORSPACE_KHR: u32 = 0x309D;
23const EGL_GL_COLORSPACE_SRGB_KHR: u32 = 0x3089;
24
25#[cfg(not(Emscripten))]
26type EglInstance = khronos_egl::DynamicInstance<khronos_egl::EGL1_4>;
27
28#[cfg(Emscripten)]
29type EglInstance = khronos_egl::Instance<khronos_egl::Static>;
30
31type EglLabel = *const ffi::c_void;
32
33#[allow(clippy::upper_case_acronyms)]
34type EGLDEBUGPROCKHR = Option<
35 unsafe extern "system" fn(
36 error: khronos_egl::Enum,
37 command: *const ffi::c_char,
38 message_type: u32,
39 thread_label: EglLabel,
40 object_label: EglLabel,
41 message: *const ffi::c_char,
42 ),
43>;
44
45const EGL_DEBUG_MSG_CRITICAL_KHR: u32 = 0x33B9;
46const EGL_DEBUG_MSG_ERROR_KHR: u32 = 0x33BA;
47const EGL_DEBUG_MSG_WARN_KHR: u32 = 0x33BB;
48const EGL_DEBUG_MSG_INFO_KHR: u32 = 0x33BC;
49
50type EglDebugMessageControlFun = unsafe extern "system" fn(
51 proc: EGLDEBUGPROCKHR,
52 attrib_list: *const khronos_egl::Attrib,
53) -> ffi::c_int;
54
55type EglSwapBuffersWithDamageFun = unsafe extern "system" fn(
56 display: *const ffi::c_void,
57 surface: *const ffi::c_void,
58 rects: *const ffi::c_int,
59 n_rects: ffi::c_int,
60) -> ffi::c_uint;
61
62unsafe extern "system" fn egl_debug_proc(
63 error: khronos_egl::Enum,
64 command_raw: *const ffi::c_char,
65 message_type: u32,
66 _thread_label: EglLabel,
67 _object_label: EglLabel,
68 message_raw: *const ffi::c_char,
69) {
70 let log_severity = match message_type {
71 EGL_DEBUG_MSG_CRITICAL_KHR | EGL_DEBUG_MSG_ERROR_KHR => log::Level::Error,
72 EGL_DEBUG_MSG_WARN_KHR => log::Level::Warn,
73 EGL_DEBUG_MSG_INFO_KHR => log::Level::Debug,
77 _ => log::Level::Trace,
78 };
79 let command = unsafe { ffi::CStr::from_ptr(command_raw) }.to_string_lossy();
80 let message = if message_raw.is_null() {
81 "".into()
82 } else {
83 unsafe { ffi::CStr::from_ptr(message_raw) }.to_string_lossy()
84 };
85
86 log::log!(log_severity, "EGL '{command}' code 0x{error:x}: {message}",);
87}
88
89#[derive(Clone, Copy, Debug)]
90enum SrgbFrameBufferKind {
91 None,
93 Core,
95 Khr,
97}
98
99fn choose_config(
101 egl: &EglInstance,
102 display: khronos_egl::Display,
103 srgb_kind: SrgbFrameBufferKind,
104) -> Result<(khronos_egl::Config, bool), crate::InstanceError> {
105 let tiers = [
107 (
108 "off-screen",
109 &[
110 khronos_egl::SURFACE_TYPE,
111 khronos_egl::PBUFFER_BIT,
112 khronos_egl::RENDERABLE_TYPE,
113 khronos_egl::OPENGL_ES2_BIT,
114 ][..],
115 ),
116 (
117 "presentation",
118 &[khronos_egl::SURFACE_TYPE, khronos_egl::WINDOW_BIT][..],
119 ),
120 #[cfg(not(target_os = "android"))]
121 (
122 "native-render",
123 &[khronos_egl::NATIVE_RENDERABLE, khronos_egl::TRUE as _][..],
124 ),
125 ];
126
127 let mut attributes = Vec::with_capacity(9);
128 for tier_max in (0..tiers.len()).rev() {
129 let name = tiers[tier_max].0;
130 log::debug!("\tTrying {name}");
131
132 attributes.clear();
133 let mut surface_type = 0;
134 for &(_, tier_attr) in tiers[..=tier_max].iter() {
135 for attribute in tier_attr.chunks_exact(2) {
136 if attribute[0] == khronos_egl::SURFACE_TYPE {
137 surface_type |= attribute[1];
138 } else {
139 attributes.extend_from_slice(attribute);
140 }
141 }
142 }
143 attributes.extend_from_slice(&[khronos_egl::SURFACE_TYPE, surface_type]);
145 match srgb_kind {
147 SrgbFrameBufferKind::None => {}
148 _ => {
149 attributes.push(khronos_egl::ALPHA_SIZE);
150 attributes.push(8);
151 }
152 }
153 attributes.push(khronos_egl::NONE);
154
155 match egl.choose_first_config(display, &attributes) {
156 Ok(Some(config)) => {
157 if tier_max == 1 {
158 log::info!("EGL says it can present to the window but not natively",);
161 }
162 let tier_threshold =
164 if cfg!(target_os = "android") || cfg!(windows) || cfg!(target_env = "ohos") {
165 1
166 } else {
167 2
168 };
169 return Ok((config, tier_max >= tier_threshold));
170 }
171 Ok(None) => {
172 log::debug!("No config found!");
173 }
174 Err(e) => {
175 log::error!("error in choose_first_config: {e:?}");
176 }
177 }
178 }
179
180 Err(crate::InstanceError::new(String::from(
182 "unable to find an acceptable EGL framebuffer configuration",
183 )))
184}
185
186#[derive(Clone, Debug)]
187struct EglContext {
188 instance: Arc<EglInstance>,
189 version: (i32, i32),
190 display: khronos_egl::Display,
191 raw: khronos_egl::Context,
192 pbuffer: Option<khronos_egl::Surface>,
193}
194
195impl EglContext {
196 fn make_current(&self) {
197 self.instance
198 .make_current(self.display, self.pbuffer, self.pbuffer, Some(self.raw))
199 .unwrap();
200 }
201
202 fn unmake_current(&self) {
203 self.instance
204 .make_current(self.display, None, None, None)
205 .unwrap();
206 }
207}
208
209#[derive(Debug)]
212pub struct AdapterContext {
213 glow: Mutex<ManuallyDrop<glow::Context>>,
214 egl: Option<EglContext>,
215}
216
217unsafe impl Sync for AdapterContext {}
218unsafe impl Send for AdapterContext {}
219
220impl AdapterContext {
221 pub fn is_owned(&self) -> bool {
222 self.egl.is_some()
223 }
224
225 pub fn egl_instance(&self) -> Option<&EglInstance> {
229 self.egl.as_ref().map(|egl| &*egl.instance)
230 }
231
232 pub fn raw_display(&self) -> Option<&khronos_egl::Display> {
236 self.egl.as_ref().map(|egl| &egl.display)
237 }
238
239 pub fn egl_version(&self) -> Option<(i32, i32)> {
243 self.egl.as_ref().map(|egl| egl.version)
244 }
245
246 pub fn raw_context(&self) -> *mut ffi::c_void {
247 match self.egl {
248 Some(ref egl) => egl.raw.as_ptr(),
249 None => ptr::null_mut(),
250 }
251 }
252}
253
254impl Drop for AdapterContext {
255 fn drop(&mut self) {
256 struct CurrentGuard<'a>(&'a EglContext);
257 impl Drop for CurrentGuard<'_> {
258 fn drop(&mut self) {
259 self.0.unmake_current();
260 }
261 }
262
263 let _guard = self.egl.as_ref().map(|egl| {
270 egl.make_current();
271 CurrentGuard(egl)
272 });
273 let glow = self.glow.get_mut();
274 unsafe { ManuallyDrop::drop(glow) };
276 }
277}
278
279struct EglContextLock<'a> {
280 instance: &'a Arc<EglInstance>,
281 display: khronos_egl::Display,
282}
283
284#[expect(missing_debug_implementations)]
286pub struct AdapterContextLock<'a> {
287 glow: MutexGuard<'a, ManuallyDrop<glow::Context>>,
288 egl: Option<EglContextLock<'a>>,
289}
290
291impl<'a> core::ops::Deref for AdapterContextLock<'a> {
292 type Target = glow::Context;
293
294 fn deref(&self) -> &Self::Target {
295 &self.glow
296 }
297}
298
299impl<'a> Drop for AdapterContextLock<'a> {
300 fn drop(&mut self) {
301 if let Some(egl) = self.egl.take() {
302 if let Err(err) = egl.instance.make_current(egl.display, None, None, None) {
303 log::error!("Failed to make EGL context current: {err:?}");
304 }
305 }
306 }
307}
308
309impl AdapterContext {
310 pub unsafe fn get_without_egl_lock(&self) -> MappedMutexGuard<'_, glow::Context> {
322 let guard = self
323 .glow
324 .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
325 .expect("Could not lock adapter context. This is most-likely a deadlock.");
326 MutexGuard::map(guard, |glow| &mut **glow)
327 }
328
329 #[track_caller]
332 pub fn lock<'a>(&'a self) -> AdapterContextLock<'a> {
333 let glow = self
334 .glow
335 .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
338 .expect("Could not lock adapter context. This is most-likely a deadlock.");
339
340 let egl = self.egl.as_ref().map(|egl| {
341 egl.make_current();
342 EglContextLock {
343 instance: &egl.instance,
344 display: egl.display,
345 }
346 });
347
348 AdapterContextLock { glow, egl }
349 }
350}
351
352#[derive(Debug)]
353struct Inner {
354 egl: EglContext,
357 version: (i32, i32),
358 supports_native_window: bool,
359 config: khronos_egl::Config,
360 srgb_kind: SrgbFrameBufferKind,
362 swap_buffers_with_damage: Option<EglSwapBuffersWithDamageFun>,
363}
364
365#[cfg(send_sync)]
366unsafe impl Send for Inner {}
367#[cfg(send_sync)]
368unsafe impl Sync for Inner {}
369
370static DISPLAYS_REFERENCE_COUNT: Lazy<Mutex<HashMap<usize, usize>>> = Lazy::new(Default::default);
374
375fn initialize_display(
376 egl: &EglInstance,
377 display: khronos_egl::Display,
378) -> Result<(i32, i32), khronos_egl::Error> {
379 let mut guard = DISPLAYS_REFERENCE_COUNT.lock();
380 *guard.entry(display.as_ptr() as usize).or_default() += 1;
381
382 egl.initialize(display)
386}
387
388fn terminate_display(
389 egl: &EglInstance,
390 display: khronos_egl::Display,
391) -> Result<(), khronos_egl::Error> {
392 let key = &(display.as_ptr() as usize);
393 let mut guard = DISPLAYS_REFERENCE_COUNT.lock();
394 let count_ref = guard
395 .get_mut(key)
396 .expect("Attempted to decref a display before incref was called");
397
398 if *count_ref > 1 {
399 *count_ref -= 1;
400
401 Ok(())
402 } else {
403 guard.remove(key);
404
405 egl.terminate(display)
406 }
407}
408
409fn instance_err<E: core::error::Error + Send + Sync + 'static>(
410 message: impl Into<String>,
411) -> impl FnOnce(E) -> crate::InstanceError {
412 move |e| crate::InstanceError::with_source(message.into(), e)
413}
414
415impl Inner {
416 fn create(
417 flags: wgt::InstanceFlags,
418 egl: Arc<EglInstance>,
419 display: khronos_egl::Display,
420 force_gles_minor_version: wgt::Gles3MinorVersion,
421 ) -> Result<Self, crate::InstanceError> {
422 let version = initialize_display(&egl, display)
423 .map_err(instance_err("failed to initialize EGL display connection"))?;
424 let vendor = egl
425 .query_string(Some(display), khronos_egl::VENDOR)
426 .map_err(instance_err("failed to query EGL vendor"))?;
427 let display_extensions = egl
428 .query_string(Some(display), khronos_egl::EXTENSIONS)
429 .map_err(instance_err("failed to query EGL display extensions"))?
430 .to_string_lossy();
431 log::debug!("Display vendor {vendor:?}, version {version:?}",);
432 log::debug!(
433 "Display extensions: {:#?}",
434 display_extensions.split_whitespace().collect::<Vec<_>>()
435 );
436
437 let srgb_kind = if version >= (1, 5) {
438 log::debug!("\tEGL surface: +srgb");
439 SrgbFrameBufferKind::Core
440 } else if display_extensions.contains("EGL_KHR_gl_colorspace") {
441 log::debug!("\tEGL surface: +srgb khr");
442 SrgbFrameBufferKind::Khr
443 } else {
444 log::debug!("\tEGL surface: -srgb");
445 SrgbFrameBufferKind::None
446 };
447
448 let swap_buffers_with_damage =
449 if display_extensions.contains("EGL_KHR_swap_buffers_with_damage") {
450 egl.get_proc_address("eglSwapBuffersWithDamageKHR")
451 } else if display_extensions.contains("EGL_EXT_swap_buffers_with_damage") {
452 egl.get_proc_address("eglSwapBuffersWithDamageEXT")
453 } else {
454 None
455 }
456 .map(|address| unsafe {
457 core::mem::transmute::<extern "system" fn(), EglSwapBuffersWithDamageFun>(address)
458 });
459 if swap_buffers_with_damage.is_some() {
460 log::debug!("\tEGL surface: +swap_buffers_with_damage");
461 } else {
462 log::debug!("\tEGL surface: -swap_buffers_with_damage");
463 }
464
465 if log::max_level() >= log::LevelFilter::Trace {
466 log::trace!("Configurations:");
467 let config_count = egl
468 .get_config_count(display)
469 .map_err(instance_err("failed to get config count"))?;
470 let mut configurations = Vec::with_capacity(config_count);
471 egl.get_configs(display, &mut configurations)
472 .map_err(instance_err("failed to get configs"))?;
473 for &config in configurations.iter() {
474 log::trace!("\tCONFORMANT=0x{:X?}, RENDERABLE=0x{:X?}, NATIVE_RENDERABLE=0x{:X?}, SURFACE_TYPE=0x{:X?}, ALPHA_SIZE={:?}",
475 egl.get_config_attrib(display, config, khronos_egl::CONFORMANT),
476 egl.get_config_attrib(display, config, khronos_egl::RENDERABLE_TYPE),
477 egl.get_config_attrib(display, config, khronos_egl::NATIVE_RENDERABLE),
478 egl.get_config_attrib(display, config, khronos_egl::SURFACE_TYPE),
479 egl.get_config_attrib(display, config, khronos_egl::ALPHA_SIZE),
480 );
481 }
482 }
483
484 let (config, supports_native_window) = choose_config(&egl, display, srgb_kind)?;
485
486 let supports_opengl = if version >= (1, 4) {
487 let client_apis = egl
488 .query_string(Some(display), khronos_egl::CLIENT_APIS)
489 .map_err(instance_err("failed to query EGL client APIs string"))?
490 .to_string_lossy();
491 client_apis
492 .split(' ')
493 .any(|client_api| client_api == "OpenGL")
494 } else {
495 false
496 };
497
498 let mut khr_context_flags = 0;
499 let supports_khr_context = display_extensions.contains("EGL_KHR_create_context");
500
501 let mut context_attributes = vec![];
502 let mut gl_context_attributes = vec![];
503 let mut gles_context_attributes = vec![];
504 gl_context_attributes.push(khronos_egl::CONTEXT_MAJOR_VERSION);
505 gl_context_attributes.push(3);
506 gl_context_attributes.push(khronos_egl::CONTEXT_MINOR_VERSION);
507 gl_context_attributes.push(3);
508 if supports_opengl && force_gles_minor_version != wgt::Gles3MinorVersion::Automatic {
509 log::warn!("Ignoring specified GLES minor version as OpenGL is used");
510 }
511 gles_context_attributes.push(khronos_egl::CONTEXT_MAJOR_VERSION);
512 gles_context_attributes.push(3); if force_gles_minor_version != wgt::Gles3MinorVersion::Automatic {
514 gles_context_attributes.push(khronos_egl::CONTEXT_MINOR_VERSION);
515 gles_context_attributes.push(match force_gles_minor_version {
516 wgt::Gles3MinorVersion::Automatic => unreachable!(),
517 wgt::Gles3MinorVersion::Version0 => 0,
518 wgt::Gles3MinorVersion::Version1 => 1,
519 wgt::Gles3MinorVersion::Version2 => 2,
520 });
521 }
522 if flags.contains(wgt::InstanceFlags::DEBUG) {
523 if version >= (1, 5) {
524 log::debug!("\tEGL context: +debug");
525 context_attributes.push(khronos_egl::CONTEXT_OPENGL_DEBUG);
526 context_attributes.push(khronos_egl::TRUE as _);
527 } else if supports_khr_context {
528 log::debug!("\tEGL context: +debug KHR");
529 khr_context_flags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR;
530 } else {
531 log::debug!("\tEGL context: -debug");
532 }
533 }
534
535 if khr_context_flags != 0 {
536 context_attributes.push(EGL_CONTEXT_FLAGS_KHR);
537 context_attributes.push(khr_context_flags);
538 }
539
540 gl_context_attributes.extend(&context_attributes);
541 gles_context_attributes.extend(&context_attributes);
542
543 let context = {
544 #[derive(Copy, Clone)]
545 enum Robustness {
546 Core,
547 Ext,
548 }
549
550 let robustness = if version >= (1, 5) {
551 Some(Robustness::Core)
552 } else if display_extensions.contains("EGL_EXT_create_context_robustness") {
553 Some(Robustness::Ext)
554 } else {
555 None
556 };
557
558 let create_context = |api, base_attributes: &[khronos_egl::Int]| {
559 egl.bind_api(api)?;
560
561 let mut robustness = robustness;
562 loop {
563 let robustness_attributes = match robustness {
564 Some(Robustness::Core) => {
565 vec![
566 khronos_egl::CONTEXT_OPENGL_ROBUST_ACCESS,
567 khronos_egl::TRUE as _,
568 khronos_egl::NONE,
569 ]
570 }
571 Some(Robustness::Ext) => {
572 vec![
573 EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT,
574 khronos_egl::TRUE as _,
575 khronos_egl::NONE,
576 ]
577 }
578 None => vec![khronos_egl::NONE],
579 };
580
581 let mut context_attributes = base_attributes.to_vec();
582 context_attributes.extend(&robustness_attributes);
583
584 match egl.create_context(display, config, None, &context_attributes) {
585 Ok(context) => {
586 match robustness {
587 Some(Robustness::Core) => {
588 log::debug!("\tEGL context: +robust access");
589 }
590 Some(Robustness::Ext) => {
591 log::debug!("\tEGL context: +robust access EXT");
592 }
593 None => {
594 log::debug!("\tEGL context: -robust access");
595 }
596 }
597 return Ok(context);
598 }
599
600 Err(
603 khronos_egl::Error::BadAttribute
604 | khronos_egl::Error::BadMatch
605 | khronos_egl::Error::BadConfig,
606 ) if robustness.is_some() => {
607 robustness = match robustness {
608 Some(Robustness::Core)
609 if display_extensions
610 .contains("EGL_EXT_create_context_robustness") =>
611 {
612 Some(Robustness::Ext)
613 }
614 _ => None,
615 };
616 continue;
617 }
618
619 Err(e) => return Err(e),
620 }
621 }
622 };
623
624 let result = if supports_opengl {
625 create_context(khronos_egl::OPENGL_API, &gl_context_attributes).or_else(
626 |gl_error| {
627 log::debug!("Failed to create desktop OpenGL context: {gl_error}, falling back to OpenGL ES");
628 create_context(khronos_egl::OPENGL_ES_API, &gles_context_attributes)
629 },
630 )
631 } else {
632 create_context(khronos_egl::OPENGL_ES_API, &gles_context_attributes)
633 };
634
635 result.map_err(|e| {
636 crate::InstanceError::with_source(
637 String::from("unable to create OpenGL or GLES 3.x context"),
638 e,
639 )
640 })
641 }?;
642
643 let pbuffer = if version >= (1, 5)
646 || display_extensions.contains("EGL_KHR_surfaceless_context")
647 || cfg!(Emscripten)
648 {
649 log::debug!("\tEGL context: +surfaceless");
650 None
651 } else {
652 let attributes = [
653 khronos_egl::WIDTH,
654 1,
655 khronos_egl::HEIGHT,
656 1,
657 khronos_egl::NONE,
658 ];
659 egl.create_pbuffer_surface(display, config, &attributes)
660 .map(Some)
661 .map_err(|e| {
662 crate::InstanceError::with_source(
663 String::from("error in create_pbuffer_surface"),
664 e,
665 )
666 })?
667 };
668
669 Ok(Self {
670 egl: EglContext {
671 instance: egl,
672 display,
673 raw: context,
674 pbuffer,
675 version,
676 },
677 version,
678 supports_native_window,
679 config,
680 srgb_kind,
681 swap_buffers_with_damage,
682 })
683 }
684}
685
686impl Drop for Inner {
687 fn drop(&mut self) {
688 if let Err(e) = self
692 .egl
693 .instance
694 .destroy_context(self.egl.display, self.egl.raw)
695 {
696 log::warn!("Error in destroy_context: {e:?}");
697 }
698
699 if let Err(e) = terminate_display(&self.egl.instance, self.egl.display) {
700 log::warn!("Error in terminate: {e:?}");
701 }
702 }
703}
704
705#[derive(Clone, Copy, Debug, PartialEq)]
706enum WindowKind {
707 Wayland,
708 X11,
709 AngleX11,
710 Unknown,
711}
712
713#[derive(Clone, Debug)]
714struct WindowSystemInterface {
715 kind: WindowKind,
716}
717
718#[derive(Debug)]
719pub struct Instance {
720 wsi: WindowSystemInterface,
721 flags: wgt::InstanceFlags,
722 options: wgt::GlBackendOptions,
723 inner: Mutex<Inner>,
724}
725
726impl Instance {
727 pub fn raw_display(&self) -> khronos_egl::Display {
728 self.inner
729 .try_lock()
730 .expect("Could not lock instance. This is most-likely a deadlock.")
731 .egl
732 .display
733 }
734
735 pub fn egl_version(&self) -> (i32, i32) {
737 self.inner
738 .try_lock()
739 .expect("Could not lock instance. This is most-likely a deadlock.")
740 .version
741 }
742}
743
744#[cfg(send_sync)]
745static_assertions::assert_impl_all!(Instance: Send, Sync);
746
747impl crate::Instance for Instance {
748 type A = super::Api;
749
750 unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
751 use raw_window_handle::RawDisplayHandle as Rdh;
752
753 profiling::scope!("Init OpenGL (EGL) Backend");
754 #[cfg(Emscripten)]
755 let egl_result: Result<EglInstance, khronos_egl::Error> =
756 Ok(khronos_egl::Instance::new(khronos_egl::Static));
757
758 #[cfg(not(Emscripten))]
759 let egl_result = if cfg!(windows) {
760 unsafe {
761 khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required_from_filename(
762 "libEGL.dll",
763 )
764 }
765 } else if cfg!(target_vendor = "apple") {
766 unsafe {
767 khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required_from_filename(
768 "libEGL.dylib",
769 )
770 }
771 } else {
772 unsafe { khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required() }
773 };
774 let egl = egl_result
775 .map(Arc::new)
776 .map_err(instance_err("unable to open libEGL"))?;
777
778 let client_extensions = egl.query_string(None, khronos_egl::EXTENSIONS);
779
780 let client_ext_str = match client_extensions {
781 Ok(ext) => ext.to_string_lossy().into_owned(),
782 Err(_) => String::new(),
783 };
784 log::debug!(
785 "Client extensions: {:#?}",
786 client_ext_str.split_whitespace().collect::<Vec<_>>()
787 );
788
789 #[cfg(not(Emscripten))]
790 let egl1_5 = egl.upcast::<khronos_egl::EGL1_5>();
791
792 #[cfg(Emscripten)]
793 let egl1_5: Option<&Arc<EglInstance>> = Some(&egl);
794
795 let (display, wsi_kind) = match (desc.display.map(|d| d.as_raw()), egl1_5) {
796 (Some(Rdh::Windows(_)) | None, Some(egl))
797 if cfg!(windows)
798 && client_ext_str.contains("EGL_ANGLE_platform_angle")
799 && client_ext_str.contains("EGL_ANGLE_platform_angle_d3d") =>
800 {
801 log::debug!("Using Angle platform with D3D11");
802 const EGL_PLATFORM_ANGLE_TYPE_ANGLE: u32 = 0x3203;
803 const EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE: u32 = 0x3208;
804 let display_attributes = [
805 EGL_PLATFORM_ANGLE_TYPE_ANGLE as khronos_egl::Attrib,
806 EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE as khronos_egl::Attrib,
807 EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED as khronos_egl::Attrib,
808 usize::from(desc.flags.contains(wgt::InstanceFlags::VALIDATION)),
809 khronos_egl::ATTRIB_NONE,
810 ];
811 let display = unsafe {
812 egl.get_platform_display(
813 EGL_PLATFORM_ANGLE_ANGLE,
814 khronos_egl::DEFAULT_DISPLAY,
815 &display_attributes,
816 )
817 }
818 .map_err(instance_err("failed to get Angle D3D11 display"))?;
819 (display, WindowKind::Unknown)
820 }
821 (Some(Rdh::Wayland(wayland_display_handle)), Some(egl))
822 if client_ext_str.contains("EGL_EXT_platform_wayland") =>
823 {
824 log::debug!("Using Wayland platform");
825 let display_attributes = [khronos_egl::ATTRIB_NONE];
826 let display = unsafe {
827 egl.get_platform_display(
828 EGL_PLATFORM_WAYLAND_KHR,
829 wayland_display_handle.display.as_ptr(),
830 &display_attributes,
831 )
832 }
833 .map_err(instance_err("failed to get Wayland display"))?;
834 (display, WindowKind::Wayland)
835 }
836 (Some(Rdh::Xlib(xlib_display_handle)), Some(egl))
837 if client_ext_str.contains("EGL_EXT_platform_x11") =>
838 {
839 log::debug!("Using X11 platform");
840 let display_attributes = [khronos_egl::ATTRIB_NONE];
841 let display = unsafe {
842 egl.get_platform_display(
843 EGL_PLATFORM_X11_KHR,
844 xlib_display_handle
845 .display
846 .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr),
847 &display_attributes,
848 )
849 }
850 .map_err(instance_err("failed to get X11 display"))?;
851 (display, WindowKind::X11)
852 }
853 (Some(Rdh::Xlib(xlib_display_handle)), Some(egl))
854 if client_ext_str.contains("EGL_ANGLE_platform_angle") =>
855 {
856 log::debug!("Using Angle platform with X11");
857 let display_attributes = [
858 EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE as khronos_egl::Attrib,
859 EGL_PLATFORM_X11_KHR as khronos_egl::Attrib,
860 EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED as khronos_egl::Attrib,
861 usize::from(desc.flags.contains(wgt::InstanceFlags::VALIDATION)),
862 khronos_egl::ATTRIB_NONE,
863 ];
864 let display = unsafe {
865 egl.get_platform_display(
866 EGL_PLATFORM_ANGLE_ANGLE,
867 xlib_display_handle
868 .display
869 .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr),
870 &display_attributes,
871 )
872 }
873 .map_err(instance_err("failed to get Angle display"))?;
874 (display, WindowKind::AngleX11)
875 }
876 (Some(Rdh::Xcb(xcb_display_handle)), Some(egl))
877 if client_ext_str.contains("EGL_EXT_platform_xcb") =>
878 {
879 log::debug!("Using XCB platform");
880 let display_attributes = [
881 EGL_PLATFORM_XCB_SCREEN_EXT as khronos_egl::Attrib,
882 xcb_display_handle.screen as khronos_egl::Attrib,
883 khronos_egl::ATTRIB_NONE,
884 ];
885 let display = unsafe {
886 egl.get_platform_display(
887 EGL_PLATFORM_XCB_EXT,
888 xcb_display_handle
889 .connection
890 .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr),
891 &display_attributes,
892 )
893 }
894 .map_err(instance_err("failed to get XCB display"))?;
895 (display, WindowKind::X11)
896 }
897 x if client_ext_str.contains("EGL_MESA_platform_surfaceless") => {
898 log::debug!(
899 "No (or unknown) windowing system ({x:?}) present. Using surfaceless platform"
900 );
901 #[allow(
902 clippy::unnecessary_literal_unwrap,
903 reason = "this is only a literal on Emscripten"
904 )]
905 let egl = egl1_5.expect("Failed to get EGL 1.5 for surfaceless");
907 let display = unsafe {
908 egl.get_platform_display(
909 EGL_PLATFORM_SURFACELESS_MESA,
910 khronos_egl::DEFAULT_DISPLAY,
911 &[khronos_egl::ATTRIB_NONE],
912 )
913 }
914 .map_err(instance_err("failed to get MESA surfaceless display"))?;
915 (display, WindowKind::Unknown)
916 }
917 x => {
918 log::debug!(
919 "No (or unknown) windowing system {x:?} and EGL_MESA_platform_surfaceless not available. Using default platform"
920 );
921 let display =
922 unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.ok_or_else(|| {
923 crate::InstanceError::new("Failed to get default display".into())
924 })?;
925 (display, WindowKind::Unknown)
926 }
927 };
928
929 if desc.flags.contains(wgt::InstanceFlags::VALIDATION)
930 && client_ext_str.contains("EGL_KHR_debug")
931 {
932 log::debug!("Enabling EGL debug output");
933 let function: EglDebugMessageControlFun = {
934 let addr = egl
935 .get_proc_address("eglDebugMessageControlKHR")
936 .ok_or_else(|| {
937 crate::InstanceError::new(
938 "failed to get `eglDebugMessageControlKHR` proc address".into(),
939 )
940 })?;
941 unsafe { core::mem::transmute(addr) }
942 };
943 let attributes = [
944 EGL_DEBUG_MSG_CRITICAL_KHR as khronos_egl::Attrib,
945 1,
946 EGL_DEBUG_MSG_ERROR_KHR as khronos_egl::Attrib,
947 1,
948 EGL_DEBUG_MSG_WARN_KHR as khronos_egl::Attrib,
949 1,
950 EGL_DEBUG_MSG_INFO_KHR as khronos_egl::Attrib,
951 1,
952 khronos_egl::ATTRIB_NONE,
953 ];
954 unsafe { (function)(Some(egl_debug_proc), attributes.as_ptr()) };
955 }
956
957 let inner = Inner::create(
958 desc.flags,
959 egl,
960 display,
961 desc.backend_options.gl.gles_minor_version,
962 )?;
963
964 Ok(Instance {
965 wsi: WindowSystemInterface { kind: wsi_kind },
966 flags: desc.flags,
967 options: desc.backend_options.gl.clone(),
968 inner: Mutex::new(inner),
969 })
970 }
971
972 unsafe fn create_surface(
973 &self,
974 display_handle: raw_window_handle::RawDisplayHandle,
975 window_handle: raw_window_handle::RawWindowHandle,
976 ) -> Result<Surface, crate::InstanceError> {
977 use raw_window_handle::RawWindowHandle as Rwh;
978
979 let inner = self.inner.lock();
980
981 match (window_handle, display_handle) {
982 (Rwh::Xlib(_), _) => {}
983 (Rwh::Xcb(_), _) => {}
984 (Rwh::Win32(_), _) => {}
985 (Rwh::AppKit(_), _) => {}
986 (Rwh::OhosNdk(_), _) => {}
987 #[cfg(target_os = "android")]
988 (Rwh::AndroidNdk(handle), _) => {
989 let format = inner
990 .egl
991 .instance
992 .get_config_attrib(
993 inner.egl.display,
994 inner.config,
995 khronos_egl::NATIVE_VISUAL_ID,
996 )
997 .map_err(instance_err("failed to get config NATIVE_VISUAL_ID"))?;
998
999 let ret = unsafe {
1000 ndk_sys::ANativeWindow_setBuffersGeometry(
1001 handle
1002 .a_native_window
1003 .as_ptr()
1004 .cast::<ndk_sys::ANativeWindow>(),
1005 0,
1006 0,
1007 format,
1008 )
1009 };
1010
1011 if ret != 0 {
1012 return Err(crate::InstanceError::new(format!(
1013 "error {ret} returned from ANativeWindow_setBuffersGeometry",
1014 )));
1015 }
1016 }
1017 (Rwh::Wayland(_), _) => {}
1018 #[cfg(Emscripten)]
1019 (Rwh::Web(_), _) => {}
1020 other => {
1021 return Err(crate::InstanceError::new(format!(
1022 "unsupported window: {other:?}"
1023 )));
1024 }
1025 };
1026
1027 inner.egl.unmake_current();
1028
1029 Ok(Surface {
1030 egl: inner.egl.clone(),
1031 wsi: self.wsi.clone(),
1032 config: inner.config,
1033 presentable: inner.supports_native_window,
1034 raw_window_handle: window_handle,
1035 swapchain: RwLock::new(None),
1036 srgb_kind: inner.srgb_kind,
1037 swap_buffers_with_damage: inner.swap_buffers_with_damage,
1038 })
1039 }
1040
1041 unsafe fn enumerate_adapters(
1042 &self,
1043 _surface_hint: Option<&Surface>,
1044 ) -> Vec<crate::ExposedAdapter<super::Api>> {
1045 let inner = self.inner.lock();
1046 inner.egl.make_current();
1047
1048 let mut gl = unsafe {
1049 glow::Context::from_loader_function(|name| {
1050 inner
1051 .egl
1052 .instance
1053 .get_proc_address(name)
1054 .map_or(ptr::null(), |p| p as *const _)
1055 })
1056 };
1057
1058 if !matches!(inner.srgb_kind, SrgbFrameBufferKind::None) {
1061 unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
1062 }
1063
1064 if self.flags.contains(wgt::InstanceFlags::DEBUG) && gl.supports_debug() {
1065 log::debug!("Max label length: {}", unsafe {
1066 gl.get_parameter_i32(glow::MAX_LABEL_LENGTH)
1067 });
1068 }
1069
1070 if self.flags.contains(wgt::InstanceFlags::VALIDATION) && gl.supports_debug() {
1071 log::debug!("Enabling GLES debug output");
1072 unsafe { gl.enable(glow::DEBUG_OUTPUT) };
1073 unsafe { gl.debug_message_callback(super::gl_debug_message_callback) };
1074 }
1075
1076 let gl = ManuallyDrop::new(gl);
1080 inner.egl.unmake_current();
1081
1082 unsafe {
1083 super::Adapter::expose(
1084 AdapterContext {
1085 glow: Mutex::new(gl),
1086 egl: Some(inner.egl.clone()),
1088 },
1089 self.options.clone(),
1090 )
1091 }
1092 .into_iter()
1093 .collect()
1094 }
1095}
1096
1097impl super::Adapter {
1098 pub unsafe fn new_external(
1108 fun: impl FnMut(&str) -> *const ffi::c_void,
1109 options: wgt::GlBackendOptions,
1110 ) -> Option<crate::ExposedAdapter<super::Api>> {
1111 let context = unsafe { glow::Context::from_loader_function(fun) };
1112 unsafe {
1113 Self::expose(
1114 AdapterContext {
1115 glow: Mutex::new(ManuallyDrop::new(context)),
1116 egl: None,
1117 },
1118 options,
1119 )
1120 }
1121 }
1122
1123 pub fn adapter_context(&self) -> &AdapterContext {
1124 &self.shared.context
1125 }
1126}
1127
1128impl super::Device {
1129 pub fn context(&self) -> &AdapterContext {
1131 &self.shared.context
1132 }
1133}
1134
1135#[derive(Debug)]
1136pub struct Swapchain {
1137 surface: khronos_egl::Surface,
1138 wl_window: Option<*mut ffi::c_void>,
1139 framebuffer: glow::Framebuffer,
1140 renderbuffer: glow::Renderbuffer,
1141 extent: wgt::Extent3d,
1143 format: wgt::TextureFormat,
1144 format_desc: super::TextureFormatDesc,
1145 #[allow(unused)]
1146 sample_type: wgt::TextureSampleType,
1147}
1148
1149#[derive(Debug)]
1150pub struct Surface {
1151 egl: EglContext,
1152 wsi: WindowSystemInterface,
1153 config: khronos_egl::Config,
1154 pub(super) presentable: bool,
1155 raw_window_handle: raw_window_handle::RawWindowHandle,
1156 swapchain: RwLock<Option<Swapchain>>,
1157 srgb_kind: SrgbFrameBufferKind,
1158 swap_buffers_with_damage: Option<EglSwapBuffersWithDamageFun>,
1159}
1160
1161unsafe impl Send for Surface {}
1162unsafe impl Sync for Surface {}
1163
1164impl Surface {
1165 pub(super) unsafe fn present(
1166 &self,
1167 _suf_texture: super::Texture,
1168 context: &AdapterContext,
1169 damage_rects: &[wgt::Rect<u32>],
1170 ) -> Result<(), crate::SurfaceError> {
1171 let gl = unsafe { context.get_without_egl_lock() };
1172 let swapchain = self.swapchain.read();
1173 let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other(
1174 "Surface has no swap-chain configured",
1175 ))?;
1176
1177 self.egl
1178 .instance
1179 .make_current(
1180 self.egl.display,
1181 Some(sc.surface),
1182 Some(sc.surface),
1183 Some(self.egl.raw),
1184 )
1185 .map_err(|e| {
1186 log::error!("make_current(surface) failed: {e}");
1187 crate::SurfaceError::Lost
1188 })?;
1189
1190 unsafe { gl.disable(glow::SCISSOR_TEST) };
1191 unsafe { gl.color_mask(true, true, true, true) };
1192
1193 unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
1194 unsafe { gl.draw_buffers(&[glow::BACK]) };
1195 unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer)) };
1196
1197 if !matches!(self.srgb_kind, SrgbFrameBufferKind::None) {
1198 unsafe { gl.disable(glow::FRAMEBUFFER_SRGB) };
1201 }
1202
1203 unsafe {
1207 gl.blit_framebuffer(
1208 0,
1209 sc.extent.height as i32,
1210 sc.extent.width as i32,
1211 0,
1212 0,
1213 0,
1214 sc.extent.width as i32,
1215 sc.extent.height as i32,
1216 glow::COLOR_BUFFER_BIT,
1217 glow::NEAREST,
1218 )
1219 };
1220
1221 if !matches!(self.srgb_kind, SrgbFrameBufferKind::None) {
1222 unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
1223 }
1224
1225 unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
1226
1227 match self.swap_buffers_with_damage {
1228 Some(swap_with_damage) if !damage_rects.is_empty() => {
1229 let rects = damage_rects
1231 .iter()
1232 .flat_map(|rect| {
1233 [
1234 rect.x as ffi::c_int,
1235 (sc.extent.height - rect.y - rect.h) as ffi::c_int,
1236 rect.w as ffi::c_int,
1237 rect.h as ffi::c_int,
1238 ]
1239 })
1240 .collect::<Vec<ffi::c_int>>();
1241 let ok = unsafe {
1242 swap_with_damage(
1243 self.egl.display.as_ptr(),
1244 sc.surface.as_ptr(),
1245 rects.as_ptr(),
1246 damage_rects.len() as ffi::c_int,
1247 )
1248 };
1249 if ok == khronos_egl::FALSE {
1250 log::error!("swap_buffers_with_damage failed");
1251 return Err(crate::SurfaceError::Lost);
1252 }
1253 }
1254 _ => {
1255 self.egl
1256 .instance
1257 .swap_buffers(self.egl.display, sc.surface)
1258 .map_err(|e| {
1259 log::error!("swap_buffers failed: {e}");
1260 crate::SurfaceError::Lost
1261 })?;
1263 }
1264 }
1265 self.egl
1266 .instance
1267 .make_current(self.egl.display, None, None, None)
1268 .map_err(|e| {
1269 log::error!("make_current(null) failed: {e}");
1270 crate::SurfaceError::Lost
1271 })?;
1272
1273 Ok(())
1274 }
1275
1276 unsafe fn unconfigure_impl(
1277 &self,
1278 device: &super::Device,
1279 ) -> Option<(khronos_egl::Surface, Option<*mut ffi::c_void>)> {
1280 let gl = &device.shared.context.lock();
1281 match self.swapchain.write().take() {
1282 Some(sc) => {
1283 unsafe { gl.delete_renderbuffer(sc.renderbuffer) };
1284 unsafe { gl.delete_framebuffer(sc.framebuffer) };
1285 Some((sc.surface, sc.wl_window))
1286 }
1287 None => None,
1288 }
1289 }
1290
1291 pub fn supports_srgb(&self) -> bool {
1292 match self.srgb_kind {
1293 SrgbFrameBufferKind::None => false,
1294 _ => true,
1295 }
1296 }
1297}
1298
1299impl crate::Surface for Surface {
1300 type A = super::Api;
1301
1302 unsafe fn configure(
1303 &self,
1304 device: &super::Device,
1305 config: &crate::SurfaceConfiguration,
1306 ) -> Result<(), crate::SurfaceError> {
1307 use raw_window_handle::RawWindowHandle as Rwh;
1308
1309 let (surface, wl_window) = match unsafe { self.unconfigure_impl(device) } {
1310 Some((sc, wl_window)) => {
1311 #[cfg(unix)]
1312 if let Some(window) = wl_window {
1313 wayland_sys::ffi_dispatch!(
1314 wayland_sys::egl::wayland_egl_handle(),
1315 wl_egl_window_resize,
1316 window.cast(),
1317 config.extent.width as i32,
1318 config.extent.height as i32,
1319 0,
1320 0,
1321 );
1322 }
1323
1324 (sc, wl_window)
1325 }
1326 None => {
1327 #[cfg_attr(not(unix), expect(unused_mut))]
1328 let mut wl_window = None;
1329 let (mut temp_xlib_handle, mut temp_xcb_handle);
1330 let native_window_ptr = match (self.wsi.kind, self.raw_window_handle) {
1331 (WindowKind::Unknown | WindowKind::X11, Rwh::Xlib(handle)) => {
1332 temp_xlib_handle = handle.window;
1333 ptr::from_mut(&mut temp_xlib_handle).cast::<ffi::c_void>()
1334 }
1335 (WindowKind::AngleX11, Rwh::Xlib(handle)) => handle.window as *mut ffi::c_void,
1336 (WindowKind::Unknown | WindowKind::X11, Rwh::Xcb(handle)) => {
1337 temp_xcb_handle = handle.window;
1338 ptr::from_mut(&mut temp_xcb_handle).cast::<ffi::c_void>()
1339 }
1340 (WindowKind::AngleX11, Rwh::Xcb(handle)) => {
1341 handle.window.get() as *mut ffi::c_void
1342 }
1343 (WindowKind::Unknown, Rwh::AndroidNdk(handle)) => {
1344 handle.a_native_window.as_ptr()
1345 }
1346 (WindowKind::Unknown, Rwh::OhosNdk(handle)) => handle.native_window.as_ptr(),
1347 #[cfg(unix)]
1348 (WindowKind::Wayland, Rwh::Wayland(handle)) => {
1349 let window = wayland_sys::ffi_dispatch!(
1350 wayland_sys::egl::wayland_egl_handle(),
1351 wl_egl_window_create,
1352 handle.surface.as_ptr().cast(),
1353 config.extent.width as i32,
1354 config.extent.height as i32,
1355 );
1356 wl_window = Some(window.cast());
1357 window.cast()
1358 }
1359 #[cfg(Emscripten)]
1360 (WindowKind::Unknown, Rwh::Web(handle)) => handle.id as *mut ffi::c_void,
1361 (WindowKind::Unknown, Rwh::Win32(handle)) => {
1362 handle.hwnd.get() as *mut ffi::c_void
1363 }
1364 (WindowKind::Unknown, Rwh::AppKit(handle)) => {
1365 #[cfg(not(target_os = "macos"))]
1366 let window_ptr = handle.ns_view.as_ptr();
1367 #[cfg(target_os = "macos")]
1368 let window_ptr = {
1369 use objc2::msg_send;
1370 use objc2::runtime::AnyObject;
1371 let layer: *mut AnyObject =
1373 msg_send![handle.ns_view.as_ptr().cast::<AnyObject>(), layer];
1374 layer.cast::<ffi::c_void>()
1375 };
1376 window_ptr
1377 }
1378 _ => {
1379 log::warn!(
1380 "Initialized platform {:?} doesn't work with window {:?}",
1381 self.wsi.kind,
1382 self.raw_window_handle
1383 );
1384 return Err(crate::SurfaceError::Other("incompatible window kind"));
1385 }
1386 };
1387
1388 let mut attributes = vec![
1389 khronos_egl::RENDER_BUFFER,
1390 if cfg!(any(
1394 target_os = "android",
1395 target_os = "macos",
1396 target_env = "ohos"
1397 )) || cfg!(windows)
1398 || self.wsi.kind == WindowKind::AngleX11
1399 {
1400 khronos_egl::BACK_BUFFER
1401 } else {
1402 khronos_egl::SINGLE_BUFFER
1403 },
1404 ];
1405 if config.format.has_srgb_suffix() {
1406 match self.srgb_kind {
1407 SrgbFrameBufferKind::None => {}
1408 SrgbFrameBufferKind::Core => {
1409 attributes.push(khronos_egl::GL_COLORSPACE);
1410 attributes.push(khronos_egl::GL_COLORSPACE_SRGB);
1411 }
1412 SrgbFrameBufferKind::Khr => {
1413 attributes.push(EGL_GL_COLORSPACE_KHR as i32);
1414 attributes.push(EGL_GL_COLORSPACE_SRGB_KHR as i32);
1415 }
1416 }
1417 }
1418 attributes.push(khronos_egl::ATTRIB_NONE as i32);
1419
1420 #[cfg(not(Emscripten))]
1421 let egl1_5 = self.egl.instance.upcast::<khronos_egl::EGL1_5>();
1422
1423 #[cfg(Emscripten)]
1424 let egl1_5: Option<&Arc<EglInstance>> = Some(&self.egl.instance);
1425
1426 let raw_result = match egl1_5 {
1428 Some(egl) if self.wsi.kind != WindowKind::Unknown => {
1429 let attributes_usize = attributes
1430 .into_iter()
1431 .map(|v| v as usize)
1432 .collect::<Vec<_>>();
1433 unsafe {
1434 egl.create_platform_window_surface(
1435 self.egl.display,
1436 self.config,
1437 native_window_ptr,
1438 &attributes_usize,
1439 )
1440 }
1441 }
1442 _ => unsafe {
1443 self.egl.instance.create_window_surface(
1444 self.egl.display,
1445 self.config,
1446 native_window_ptr,
1447 Some(&attributes),
1448 )
1449 },
1450 };
1451
1452 match raw_result {
1453 Ok(raw) => (raw, wl_window),
1454 Err(e) => {
1455 log::warn!("Error in create_window_surface: {e:?}");
1456 return Err(crate::SurfaceError::Lost);
1457 }
1458 }
1459 }
1460 };
1461
1462 let format_desc = device.shared.describe_texture_format(config.format);
1463 let gl = &device.shared.context.lock();
1464 let renderbuffer = unsafe { gl.create_renderbuffer() }.map_err(|error| {
1465 log::error!("Internal swapchain renderbuffer creation failed: {error}");
1466 crate::DeviceError::OutOfMemory
1467 })?;
1468 unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(renderbuffer)) };
1469 unsafe {
1470 gl.renderbuffer_storage(
1471 glow::RENDERBUFFER,
1472 format_desc.internal,
1473 config.extent.width as _,
1474 config.extent.height as _,
1475 )
1476 };
1477 let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| {
1478 log::error!("Internal swapchain framebuffer creation failed: {error}");
1479 crate::DeviceError::OutOfMemory
1480 })?;
1481 unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) };
1482 unsafe {
1483 gl.framebuffer_renderbuffer(
1484 glow::READ_FRAMEBUFFER,
1485 glow::COLOR_ATTACHMENT0,
1486 glow::RENDERBUFFER,
1487 Some(renderbuffer),
1488 )
1489 };
1490 unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
1491 unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
1492
1493 let mut swapchain = self.swapchain.write();
1494 *swapchain = Some(Swapchain {
1495 surface,
1496 wl_window,
1497 renderbuffer,
1498 framebuffer,
1499 extent: config.extent,
1500 format: config.format,
1501 format_desc,
1502 sample_type: wgt::TextureSampleType::Float { filterable: false },
1503 });
1504
1505 Ok(())
1506 }
1507
1508 unsafe fn unconfigure(&self, device: &super::Device) {
1509 if let Some((surface, wl_window)) = unsafe { self.unconfigure_impl(device) } {
1510 self.egl
1511 .instance
1512 .destroy_surface(self.egl.display, surface)
1513 .unwrap();
1514 if let Some(_window) = wl_window {
1515 #[cfg(unix)]
1516 wayland_sys::ffi_dispatch!(
1517 wayland_sys::egl::wayland_egl_handle(),
1518 wl_egl_window_destroy,
1519 _window.cast(),
1520 );
1521 }
1522 }
1523 }
1524
1525 unsafe fn acquire_texture(
1526 &self,
1527 _timeout_ms: Option<Duration>, _fence: &super::Fence,
1529 ) -> Result<crate::AcquiredSurfaceTexture<super::Api>, crate::SurfaceError> {
1530 let swapchain = self.swapchain.read();
1531 let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other(
1532 "Surface has no swap-chain configured",
1533 ))?;
1534 let texture = super::Texture {
1535 inner: super::TextureInner::Renderbuffer {
1536 raw: sc.renderbuffer,
1537 },
1538 drop_guard: None,
1539 array_layer_count: 1,
1540 mip_level_count: 1,
1541 format: sc.format,
1542 format_desc: sc.format_desc.clone(),
1543 copy_size: crate::CopyExtent {
1544 width: sc.extent.width,
1545 height: sc.extent.height,
1546 depth: 1,
1547 },
1548 };
1549 Ok(crate::AcquiredSurfaceTexture {
1550 texture,
1551 suboptimal: false,
1552 })
1553 }
1554 unsafe fn discard_texture(&self, _texture: super::Texture) {}
1555}