Debian Codegraph @

third_party/rust/wgpu-hal/src/gles/wgl.rs

raw
1 use alloc::{borrow::ToOwned as _, ffi::CString, string::String, sync::Arc, vec::Vec};
2 use core::{
3 ffi::{c_void, CStr},
4 mem::{self, ManuallyDrop},
5 ptr,
6 time::Duration,
7 };
8 use std::{
9 os::raw::c_int,
10 sync::{
11 mpsc::{sync_channel, SyncSender},
12 LazyLock,
13 },
14 thread,
15 };
16
17 use glow::HasContext;
18 use glutin_wgl_sys::wgl_extra::{
19 Wgl, CONTEXT_CORE_PROFILE_BIT_ARB, CONTEXT_DEBUG_BIT_ARB, CONTEXT_FLAGS_ARB,
20 CONTEXT_PROFILE_MASK_ARB,
21 };
22 use hashbrown::HashSet;
23 use parking_lot::{Mutex, MutexGuard, RwLock};
24 use raw_window_handle::{RawDisplayHandle, RawWindowHandle};
25 use wgt::InstanceFlags;
26 use windows::{
27 core::{Error, PCSTR},
28 Win32::{
29 Foundation,
30 Graphics::{Gdi, OpenGL},
31 System::LibraryLoader,
32 UI::WindowsAndMessaging,
33 },
34 };
35
36 /// The amount of time to wait while trying to obtain a lock to the adapter context
37 const CONTEXT_LOCK_TIMEOUT_SECS: u64 = 1;
38
39 /// A wrapper around a `[`glow::Context`]` and the required WGL context that uses locking to
40 /// guarantee exclusive access when shared with multiple threads.
41 pub struct AdapterContext {
42 inner: Arc<Mutex<Inner>>,
43 }
44
45 unsafe impl Sync for AdapterContext {}
46 unsafe impl Send for AdapterContext {}
47
48 impl AdapterContext {
49 pub fn is_owned(&self) -> bool {
50 true
51 }
52
53 pub fn raw_context(&self) -> *mut c_void {
54 match self.inner.lock().context {
55 Some(ref wgl) => wgl.context.0,
56 None => ptr::null_mut(),
57 }
58 }
59
60 /// Obtain a lock to the WGL context and get handle to the [`glow::Context`] that can be used to
61 /// do rendering.
62 #[track_caller]
63 pub fn lock(&self) -> AdapterContextLock<'_> {
64 let inner = self
65 .inner
66 // Don't lock forever. If it takes longer than 1 second to get the lock we've got a
67 // deadlock and should panic to show where we got stuck
68 .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
69 .expect("Could not lock adapter context. This is most-likely a deadlock.");
70
71 if let Some(wgl) = &inner.context {
72 wgl.make_current(inner.device.dc).unwrap()
73 };
74
75 AdapterContextLock { inner }
76 }
77
78 /// Obtain a lock to the WGL context and get handle to the [`glow::Context`] that can be used to
79 /// do rendering.
80 ///
81 /// Unlike [`lock`](Self::lock), this accepts a device to pass to `make_current` and exposes the error
82 /// when `make_current` fails.
83 #[track_caller]
84 fn lock_with_dc(&self, device: Gdi::HDC) -> windows::core::Result<AdapterContextLock<'_>> {
85 let inner = self
86 .inner
87 .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS))
88 .expect("Could not lock adapter context. This is most-likely a deadlock.");
89
90 if let Some(wgl) = &inner.context {
91 wgl.make_current(device)?;
92 }
93
94 Ok(AdapterContextLock { inner })
95 }
96 }
97
98 /// A guard containing a lock to an [`AdapterContext`], while the GL context is kept current.
99 pub struct AdapterContextLock<'a> {
100 inner: MutexGuard<'a, Inner>,
101 }
102
103 impl<'a> core::ops::Deref for AdapterContextLock<'a> {
104 type Target = glow::Context;
105
106 fn deref(&self) -> &Self::Target {
107 &self.inner.gl
108 }
109 }
110
111 impl<'a> Drop for AdapterContextLock<'a> {
112 fn drop(&mut self) {
113 if let Some(wgl) = &self.inner.context {
114 wgl.unmake_current().unwrap()
115 }
116 }
117 }
118
119 struct WglContext {
120 context: OpenGL::HGLRC,
121 }
122
123 impl WglContext {
124 fn make_current(&self, device: Gdi::HDC) -> windows::core::Result<()> {
125 unsafe { OpenGL::wglMakeCurrent(device, self.context) }
126 }
127
128 fn unmake_current(&self) -> windows::core::Result<()> {
129 if unsafe { OpenGL::wglGetCurrentContext() }.is_invalid() {
130 return Ok(());
131 }
132 unsafe { OpenGL::wglMakeCurrent(None, None) }
133 }
134 }
135
136 impl Drop for WglContext {
137 fn drop(&mut self) {
138 if let Err(e) = unsafe { OpenGL::wglDeleteContext(self.context) } {
139 log::error!("failed to delete WGL context: {e}");
140 }
141 }
142 }
143
144 unsafe impl Send for WglContext {}
145 unsafe impl Sync for WglContext {}
146
147 struct Inner {
148 gl: ManuallyDrop<glow::Context>,
149 device: InstanceDevice,
150 context: Option<WglContext>,
151 }
152
153 impl Drop for Inner {
154 fn drop(&mut self) {
155 struct CurrentGuard<'a>(&'a WglContext);
156 impl Drop for CurrentGuard<'_> {
157 fn drop(&mut self) {
158 self.0.unmake_current().unwrap();
159 }
160 }
161
162 // Context must be current when dropped. See safety docs on
163 // `glow::HasContext`.
164 //
165 // NOTE: This is only set to `None` by `Adapter::new_external` which
166 // requires the context to be current when anything that may be holding
167 // the `Arc<AdapterShared>` is dropped.
168 let _guard = self.context.as_ref().map(|wgl| {
169 wgl.make_current(self.device.dc).unwrap();
170 CurrentGuard(wgl)
171 });
172 // SAFETY: Field not used after this.
173 unsafe { ManuallyDrop::drop(&mut self.gl) };
174 }
175 }
176
177 unsafe impl Send for Inner {}
178 unsafe impl Sync for Inner {}
179
180 pub struct Instance {
181 srgb_capable: bool,
182 options: wgt::GlBackendOptions,
183 inner: Arc<Mutex<Inner>>,
184 }
185
186 unsafe impl Send for Instance {}
187 unsafe impl Sync for Instance {}
188
189 fn load_gl_func(name: &str, module: Option<Foundation::HMODULE>) -> *const c_void {
190 let addr = CString::new(name.as_bytes()).unwrap();
191 let mut ptr = unsafe { OpenGL::wglGetProcAddress(PCSTR(addr.as_ptr().cast())) };
192 if ptr.is_none() {
193 if let Some(module) = module {
194 ptr = unsafe { LibraryLoader::GetProcAddress(module, PCSTR(addr.as_ptr().cast())) };
195 }
196 }
197 ptr.map_or_else(ptr::null_mut, |p| p as *mut c_void)
198 }
199
200 fn get_extensions(extra: &Wgl, dc: Gdi::HDC) -> HashSet<String> {
201 if extra.GetExtensionsStringARB.is_loaded() {
202 unsafe { CStr::from_ptr(extra.GetExtensionsStringARB(dc.0)) }
203 .to_str()
204 .unwrap_or("")
205 } else {
206 ""
207 }
208 .split(' ')
209 .map(|s| s.to_owned())
210 .collect()
211 }
212
213 unsafe fn setup_pixel_format(dc: Gdi::HDC) -> Result<(), crate::InstanceError> {
214 {
215 let format = OpenGL::PIXELFORMATDESCRIPTOR {
216 nVersion: 1,
217 nSize: size_of::<OpenGL::PIXELFORMATDESCRIPTOR>() as u16,
218 dwFlags: OpenGL::PFD_DRAW_TO_WINDOW
219 | OpenGL::PFD_SUPPORT_OPENGL
220 | OpenGL::PFD_DOUBLEBUFFER,
221 iPixelType: OpenGL::PFD_TYPE_RGBA,
222 cColorBits: 8,
223 ..unsafe { mem::zeroed() }
224 };
225
226 let index = unsafe { OpenGL::ChoosePixelFormat(dc, &format) };
227 if index == 0 {
228 return Err(crate::InstanceError::with_source(
229 String::from("unable to choose pixel format"),
230 Error::from_win32(),
231 ));
232 }
233
234 let current = unsafe { OpenGL::GetPixelFormat(dc) };
235
236 if index != current {
237 unsafe { OpenGL::SetPixelFormat(dc, index, &format) }.map_err(|e| {
238 crate::InstanceError::with_source(String::from("unable to set pixel format"), e)
239 })?;
240 }
241 }
242
243 {
244 let index = unsafe { OpenGL::GetPixelFormat(dc) };
245 if index == 0 {
246 return Err(crate::InstanceError::with_source(
247 String::from("unable to get pixel format index"),
248 Error::from_win32(),
249 ));
250 }
251 let mut format = Default::default();
252 if unsafe {
253 OpenGL::DescribePixelFormat(dc, index, size_of_val(&format) as u32, Some(&mut format))
254 } == 0
255 {
256 return Err(crate::InstanceError::with_source(
257 String::from("unable to read pixel format"),
258 Error::from_win32(),
259 ));
260 }
261
262 if !format.dwFlags.contains(OpenGL::PFD_SUPPORT_OPENGL)
263 || format.iPixelType != OpenGL::PFD_TYPE_RGBA
264 {
265 return Err(crate::InstanceError::new(String::from(
266 "unsuitable pixel format",
267 )));
268 }
269 }
270 Ok(())
271 }
272
273 fn create_global_window_class() -> Result<CString, crate::InstanceError> {
274 let instance = unsafe { LibraryLoader::GetModuleHandleA(None) }.map_err(|e| {
275 crate::InstanceError::with_source(String::from("unable to get executable instance"), e)
276 })?;
277
278 // Use the address of `UNIQUE` as part of the window class name to ensure different
279 // `wgpu` versions use different names.
280 static UNIQUE: Mutex<u8> = Mutex::new(0);
281 let class_addr: *const _ = &UNIQUE;
282 let name = format!("wgpu Device Class {:x}\0", class_addr as usize);
283 let name = CString::from_vec_with_nul(name.into_bytes()).unwrap();
284
285 // Use a wrapper function for compatibility with `windows-rs`.
286 unsafe extern "system" fn wnd_proc(
287 window: Foundation::HWND,
288 msg: u32,
289 wparam: Foundation::WPARAM,
290 lparam: Foundation::LPARAM,
291 ) -> Foundation::LRESULT {
292 unsafe { WindowsAndMessaging::DefWindowProcA(window, msg, wparam, lparam) }
293 }
294
295 let window_class = WindowsAndMessaging::WNDCLASSEXA {
296 cbSize: size_of::<WindowsAndMessaging::WNDCLASSEXA>() as u32,
297 style: WindowsAndMessaging::CS_OWNDC,
298 lpfnWndProc: Some(wnd_proc),
299 cbClsExtra: 0,
300 cbWndExtra: 0,
301 hInstance: instance.into(),
302 hIcon: WindowsAndMessaging::HICON::default(),
303 hCursor: WindowsAndMessaging::HCURSOR::default(),
304 hbrBackground: Gdi::HBRUSH::default(),
305 lpszMenuName: PCSTR::null(),
306 lpszClassName: PCSTR(name.as_ptr().cast()),
307 hIconSm: WindowsAndMessaging::HICON::default(),
308 };
309
310 let atom = unsafe { WindowsAndMessaging::RegisterClassExA(&window_class) };
311
312 if atom == 0 {
313 return Err(crate::InstanceError::with_source(
314 String::from("unable to register window class"),
315 Error::from_win32(),
316 ));
317 }
318
319 // We intentionally leak the window class as we only need one per process.
320
321 Ok(name)
322 }
323
324 fn get_global_window_class() -> Result<CString, crate::InstanceError> {
325 static GLOBAL: LazyLock<Result<CString, crate::InstanceError>> =
326 LazyLock::new(create_global_window_class);
327 GLOBAL.clone()
328 }
329
330 struct InstanceDevice {
331 dc: Gdi::HDC,
332
333 /// This is used to keep the thread owning `dc` alive until this struct is dropped.
334 _tx: SyncSender<()>,
335 }
336
337 fn create_instance_device() -> Result<InstanceDevice, crate::InstanceError> {
338 #[derive(Clone, Copy)]
339 // TODO: We can get these SendSync definitions in the upstream metadata if this is the case
340 struct SendDc(Gdi::HDC);
341 unsafe impl Sync for SendDc {}
342 unsafe impl Send for SendDc {}
343
344 struct Window {
345 window: Foundation::HWND,
346 }
347 impl Drop for Window {
348 fn drop(&mut self) {
349 if let Err(e) = unsafe { WindowsAndMessaging::DestroyWindow(self.window) } {
350 log::error!("failed to destroy window: {e}");
351 }
352 }
353 }
354
355 let window_class = get_global_window_class()?;
356
357 let (drop_tx, drop_rx) = sync_channel(0);
358 let (setup_tx, setup_rx) = sync_channel(0);
359
360 // We spawn a thread which owns the hidden window for this instance.
361 thread::Builder::new()
362 .stack_size(256 * 1024)
363 .name("wgpu-hal WGL Instance Thread".to_owned())
364 .spawn(move || {
365 let setup = (|| {
366 let instance = unsafe { LibraryLoader::GetModuleHandleA(None) }.map_err(|e| {
367 crate::InstanceError::with_source(
368 String::from("unable to get executable instance"),
369 e,
370 )
371 })?;
372
373 // Create a hidden window since we don't pass `WS_VISIBLE`.
374 let window = unsafe {
375 WindowsAndMessaging::CreateWindowExA(
376 WindowsAndMessaging::WINDOW_EX_STYLE::default(),
377 PCSTR(window_class.as_ptr().cast()),
378 PCSTR(window_class.as_ptr().cast()),
379 WindowsAndMessaging::WINDOW_STYLE::default(),
380 0,
381 0,
382 1,
383 1,
384 None,
385 None,
386 instance,
387 None,
388 )
389 }
390 .map_err(|e| {
391 crate::InstanceError::with_source(
392 String::from("unable to create hidden instance window"),
393 e,
394 )
395 })?;
396 let window = Window { window };
397
398 let dc = unsafe { Gdi::GetDC(window.window) };
399 if dc.is_invalid() {
400 return Err(crate::InstanceError::with_source(
401 String::from("unable to create memory device"),
402 Error::from_win32(),
403 ));
404 }
405 let dc = DeviceContextHandle {
406 device: dc,
407 window: window.window,
408 };
409 unsafe { setup_pixel_format(dc.device)? };
410
411 Ok((window, dc))
412 })();
413
414 match setup {
415 Ok((_window, dc)) => {
416 setup_tx.send(Ok(SendDc(dc.device))).unwrap();
417 // Wait for the shutdown event to free the window and device context handle.
418 drop_rx.recv().ok();
419 }
420 Err(err) => {
421 setup_tx.send(Err(err)).unwrap();
422 }
423 }
424 })
425 .map_err(|e| {
426 crate::InstanceError::with_source(String::from("unable to create instance thread"), e)
427 })?;
428
429 let dc = setup_rx.recv().unwrap()?.0;
430
431 Ok(InstanceDevice { dc, _tx: drop_tx })
432 }
433
434 impl crate::Instance for Instance {
435 type A = super::Api;
436
437 unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
438 profiling::scope!("Init OpenGL (WGL) Backend");
439 let opengl_module =
440 unsafe { LibraryLoader::LoadLibraryA(PCSTR(c"opengl32.dll".as_ptr().cast())) }
441 .map_err(|e| {
442 crate::InstanceError::with_source(
443 String::from("unable to load the OpenGL library"),
444 e,
445 )
446 })?;
447
448 let device = create_instance_device()?;
449 let dc = device.dc;
450
451 let context = unsafe { OpenGL::wglCreateContext(dc) }.map_err(|e| {
452 crate::InstanceError::with_source(
453 String::from("unable to create initial OpenGL context"),
454 e,
455 )
456 })?;
457 let context = WglContext { context };
458 context.make_current(dc).map_err(|e| {
459 crate::InstanceError::with_source(
460 String::from("unable to set initial OpenGL context as current"),
461 e,
462 )
463 })?;
464
465 let extra = Wgl::load_with(|name| load_gl_func(name, None));
466 let extensions = get_extensions(&extra, dc);
467
468 let can_use_profile = extensions.contains("WGL_ARB_create_context_profile")
469 && extra.CreateContextAttribsARB.is_loaded();
470
471 let context = if can_use_profile {
472 let attributes = [
473 CONTEXT_PROFILE_MASK_ARB as c_int,
474 CONTEXT_CORE_PROFILE_BIT_ARB as c_int,
475 CONTEXT_FLAGS_ARB as c_int,
476 if desc.flags.contains(InstanceFlags::DEBUG) {
477 CONTEXT_DEBUG_BIT_ARB as c_int
478 } else {
479 0
480 },
481 0, // End of list
482 ];
483 let context =
484 unsafe { extra.CreateContextAttribsARB(dc.0, ptr::null(), attributes.as_ptr()) };
485 if context.is_null() {
486 return Err(crate::InstanceError::with_source(
487 String::from("unable to create OpenGL context"),
488 Error::from_win32(),
489 ));
490 }
491 WglContext {
492 context: OpenGL::HGLRC(context.cast_mut()),
493 }
494 } else {
495 context
496 };
497
498 context.make_current(dc).map_err(|e| {
499 crate::InstanceError::with_source(
500 String::from("unable to set OpenGL context as current"),
501 e,
502 )
503 })?;
504
505 let mut gl = unsafe {
506 glow::Context::from_loader_function(|name| load_gl_func(name, Some(opengl_module)))
507 };
508
509 let extra = Wgl::load_with(|name| load_gl_func(name, None));
510 let extensions = get_extensions(&extra, dc);
511
512 let srgb_capable = extensions.contains("WGL_EXT_framebuffer_sRGB")
513 || extensions.contains("WGL_ARB_framebuffer_sRGB")
514 || gl
515 .supported_extensions()
516 .contains("GL_ARB_framebuffer_sRGB");
517
518 // In contrast to OpenGL ES, OpenGL requires explicitly enabling sRGB conversions,
519 // as otherwise the user has to do the sRGB conversion.
520 if srgb_capable {
521 unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
522 }
523
524 if desc.flags.contains(InstanceFlags::VALIDATION) && gl.supports_debug() {
525 log::debug!("Enabling GL debug output");
526 unsafe { gl.enable(glow::DEBUG_OUTPUT) };
527 unsafe { gl.debug_message_callback(super::gl_debug_message_callback) };
528 }
529
530 // Wrap in ManuallyDrop to make it easier to "current" the GL context before dropping this
531 // GLOW context, which could also happen if a panic occurs after we uncurrent the context
532 // below but before Inner is constructed.
533 let gl = ManuallyDrop::new(gl);
534 context.unmake_current().map_err(|e| {
535 crate::InstanceError::with_source(
536 String::from("unable to unset the current WGL context"),
537 e,
538 )
539 })?;
540
541 Ok(Instance {
542 inner: Arc::new(Mutex::new(Inner {
543 device,
544 gl,
545 context: Some(context),
546 })),
547 options: desc.backend_options.gl.clone(),
548 srgb_capable,
549 })
550 }
551
552 #[cfg_attr(target_os = "macos", allow(unused, unused_mut, unreachable_code))]
553 unsafe fn create_surface(
554 &self,
555 _display_handle: RawDisplayHandle,
556 window_handle: RawWindowHandle,
557 ) -> Result<Surface, crate::InstanceError> {
558 let window = if let RawWindowHandle::Win32(handle) = window_handle {
559 handle
560 } else {
561 return Err(crate::InstanceError::new(format!(
562 "unsupported window: {window_handle:?}"
563 )));
564 };
565 Ok(Surface {
566 // This cast exists because of https://github.com/rust-windowing/raw-window-handle/issues/171
567 window: Foundation::HWND(window.hwnd.get() as *mut _),
568 presentable: true,
569 swapchain: RwLock::new(None),
570 srgb_capable: self.srgb_capable,
571 })
572 }
573
574 unsafe fn enumerate_adapters(
575 &self,
576 _surface_hint: Option<&Surface>,
577 ) -> Vec<crate::ExposedAdapter<super::Api>> {
578 unsafe {
579 super::Adapter::expose(
580 AdapterContext {
581 inner: self.inner.clone(),
582 },
583 self.options.clone(),
584 )
585 }
586 .into_iter()
587 .collect()
588 }
589 }
590
591 impl super::Adapter {
592 /// Creates a new external adapter using the specified loader function.
593 ///
594 /// # Safety
595 ///
596 /// - The underlying OpenGL ES context must be current.
597 /// - The underlying OpenGL ES context must be current when interfacing with any objects returned by
598 /// wgpu-hal from this adapter.
599 /// - The underlying OpenGL ES context must be current when dropping this adapter and when
600 /// dropping any objects returned from this adapter.
601 pub unsafe fn new_external(
602 fun: impl FnMut(&str) -> *const c_void,
603 options: wgt::GlBackendOptions,
604 ) -> Option<crate::ExposedAdapter<super::Api>> {
605 let context = unsafe { glow::Context::from_loader_function(fun) };
606 unsafe {
607 Self::expose(
608 AdapterContext {
609 inner: Arc::new(Mutex::new(Inner {
610 gl: ManuallyDrop::new(context),
611 device: create_instance_device().ok()?,
612 context: None,
613 })),
614 },
615 options,
616 )
617 }
618 }
619
620 pub fn adapter_context(&self) -> &AdapterContext {
621 &self.shared.context
622 }
623 }
624
625 impl super::Device {
626 /// Returns the underlying WGL context.
627 pub fn context(&self) -> &AdapterContext {
628 &self.shared.context
629 }
630 }
631
632 struct DeviceContextHandle {
633 device: Gdi::HDC,
634 window: Foundation::HWND,
635 }
636
637 impl Drop for DeviceContextHandle {
638 fn drop(&mut self) {
639 unsafe {
640 Gdi::ReleaseDC(self.window, self.device);
641 };
642 }
643 }
644
645 pub struct Swapchain {
646 framebuffer: glow::Framebuffer,
647 renderbuffer: glow::Renderbuffer,
648
649 /// Extent because the window lies
650 extent: wgt::Extent3d,
651
652 format: wgt::TextureFormat,
653 format_desc: super::TextureFormatDesc,
654 #[allow(unused)]
655 sample_type: wgt::TextureSampleType,
656 }
657
658 pub struct Surface {
659 window: Foundation::HWND,
660 pub(super) presentable: bool,
661 swapchain: RwLock<Option<Swapchain>>,
662 srgb_capable: bool,
663 }
664
665 unsafe impl Send for Surface {}
666 unsafe impl Sync for Surface {}
667
668 impl Surface {
669 pub(super) unsafe fn present(
670 &self,
671 _suf_texture: super::Texture,
672 context: &AdapterContext,
673 ) -> Result<(), crate::SurfaceError> {
674 let swapchain = self.swapchain.read();
675 let sc = swapchain.as_ref().unwrap();
676 let dc = unsafe { Gdi::GetDC(self.window) };
677 if dc.is_invalid() {
678 log::error!(
679 "unable to get the device context from window: {}",
680 Error::from_win32()
681 );
682 return Err(crate::SurfaceError::Other(
683 "unable to get the device context from window",
684 ));
685 }
686 let dc = DeviceContextHandle {
687 device: dc,
688 window: self.window,
689 };
690
691 let gl = context.lock_with_dc(dc.device).map_err(|e| {
692 log::error!("unable to make the OpenGL context current for surface: {e}",);
693 crate::SurfaceError::Other("unable to make the OpenGL context current for surface")
694 })?;
695
696 unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) };
697 unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer)) };
698
699 if self.srgb_capable {
700 // Disable sRGB conversions for `glBlitFramebuffer` as behavior does diverge between
701 // drivers and formats otherwise and we want to ensure no sRGB conversions happen.
702 unsafe { gl.disable(glow::FRAMEBUFFER_SRGB) };
703 }
704
705 // Note the Y-flipping here. GL's presentation is not flipped,
706 // but main rendering is. Therefore, we Y-flip the output positions
707 // in the shader, and also this blit.
708 unsafe {
709 gl.blit_framebuffer(
710 0,
711 sc.extent.height as i32,
712 sc.extent.width as i32,
713 0,
714 0,
715 0,
716 sc.extent.width as i32,
717 sc.extent.height as i32,
718 glow::COLOR_BUFFER_BIT,
719 glow::NEAREST,
720 )
721 };
722
723 if self.srgb_capable {
724 unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) };
725 }
726
727 unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
728 unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
729
730 if let Err(e) = unsafe { OpenGL::SwapBuffers(dc.device) } {
731 log::error!("unable to swap buffers: {e}");
732 return Err(crate::SurfaceError::Other("unable to swap buffers"));
733 }
734
735 Ok(())
736 }
737
738 pub fn supports_srgb(&self) -> bool {
739 self.srgb_capable
740 }
741 }
742
743 impl crate::Surface for Surface {
744 type A = super::Api;
745
746 unsafe fn configure(
747 &self,
748 device: &super::Device,
749 config: &crate::SurfaceConfiguration,
750 ) -> Result<(), crate::SurfaceError> {
751 // Remove the old configuration.
752 unsafe { self.unconfigure(device) };
753
754 let dc = unsafe { Gdi::GetDC(self.window) };
755 if dc.is_invalid() {
756 log::error!(
757 "unable to get the device context from window: {}",
758 Error::from_win32()
759 );
760 return Err(crate::SurfaceError::Other(
761 "unable to get the device context from window",
762 ));
763 }
764 let dc = DeviceContextHandle {
765 device: dc,
766 window: self.window,
767 };
768
769 if let Err(e) = unsafe { setup_pixel_format(dc.device) } {
770 log::error!("unable to setup surface pixel format: {e}",);
771 return Err(crate::SurfaceError::Other(
772 "unable to setup surface pixel format",
773 ));
774 }
775
776 let format_desc = device.shared.describe_texture_format(config.format);
777 let gl = &device.shared.context.lock_with_dc(dc.device).map_err(|e| {
778 log::error!("unable to make the OpenGL context current for surface: {e}",);
779 crate::SurfaceError::Other("unable to make the OpenGL context current for surface")
780 })?;
781
782 let renderbuffer = unsafe { gl.create_renderbuffer() }.map_err(|error| {
783 log::error!("Internal swapchain renderbuffer creation failed: {error}");
784 crate::DeviceError::OutOfMemory
785 })?;
786 unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(renderbuffer)) };
787 unsafe {
788 gl.renderbuffer_storage(
789 glow::RENDERBUFFER,
790 format_desc.internal,
791 config.extent.width as _,
792 config.extent.height as _,
793 )
794 };
795
796 let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| {
797 log::error!("Internal swapchain framebuffer creation failed: {error}");
798 crate::DeviceError::OutOfMemory
799 })?;
800 unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) };
801 unsafe {
802 gl.framebuffer_renderbuffer(
803 glow::READ_FRAMEBUFFER,
804 glow::COLOR_ATTACHMENT0,
805 glow::RENDERBUFFER,
806 Some(renderbuffer),
807 )
808 };
809 unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
810 unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) };
811
812 // Setup presentation mode
813 let extra = Wgl::load_with(|name| load_gl_func(name, None));
814 let extensions = get_extensions(&extra, dc.device);
815 if !(extensions.contains("WGL_EXT_swap_control") && extra.SwapIntervalEXT.is_loaded()) {
816 log::error!("WGL_EXT_swap_control is unsupported");
817 return Err(crate::SurfaceError::Other(
818 "WGL_EXT_swap_control is unsupported",
819 ));
820 }
821
822 let vsync = match config.present_mode {
823 wgt::PresentMode::Immediate => false,
824 wgt::PresentMode::Fifo => true,
825 _ => {
826 log::error!("unsupported present mode: {:?}", config.present_mode);
827 return Err(crate::SurfaceError::Other("unsupported present mode"));
828 }
829 };
830
831 if unsafe { extra.SwapIntervalEXT(if vsync { 1 } else { 0 }) } == Foundation::FALSE.0 {
832 log::error!("unable to set swap interval: {}", Error::from_win32());
833 return Err(crate::SurfaceError::Other("unable to set swap interval"));
834 }
835
836 self.swapchain.write().replace(Swapchain {
837 renderbuffer,
838 framebuffer,
839 extent: config.extent,
840 format: config.format,
841 format_desc,
842 sample_type: wgt::TextureSampleType::Float { filterable: false },
843 });
844
845 Ok(())
846 }
847
848 unsafe fn unconfigure(&self, device: &super::Device) {
849 let gl = &device.shared.context.lock();
850 if let Some(sc) = self.swapchain.write().take() {
851 unsafe {
852 gl.delete_renderbuffer(sc.renderbuffer);
853 gl.delete_framebuffer(sc.framebuffer)
854 };
855 }
856 }
857
858 unsafe fn acquire_texture(
859 &self,
860 _timeout_ms: Option<Duration>,
861 _fence: &super::Fence,
862 ) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
863 let swapchain = self.swapchain.read();
864 let sc = swapchain.as_ref().unwrap();
865 let texture = super::Texture {
866 inner: super::TextureInner::Renderbuffer {
867 raw: sc.renderbuffer,
868 },
869 drop_guard: None,
870 array_layer_count: 1,
871 mip_level_count: 1,
872 format: sc.format,
873 format_desc: sc.format_desc.clone(),
874 copy_size: crate::CopyExtent {
875 width: sc.extent.width,
876 height: sc.extent.height,
877 depth: 1,
878 },
879 };
880 Ok(Some(crate::AcquiredSurfaceTexture {
881 texture,
882 suboptimal: false,
883 }))
884 }
885 unsafe fn discard_texture(&self, _texture: super::Texture) {}
886 }