exposed-gl 0.0.1-beta

OpenGl context creation for library "exposed".
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#![allow(non_snake_case)]

use std::{
    alloc::{dealloc, handle_alloc_error, Layout},
    ffi::{c_char, c_void},
    io::{Error, ErrorKind},
    mem::zeroed,
    ptr::{null, null_mut},
};

use glutin_wgl_sys::wgl_extra::{self, Wgl};
use std::alloc::alloc;
use windows_sys::{
    w,
    Win32::{
        Foundation::{
            GetLastError, ERROR_DC_NOT_FOUND, ERROR_INVALID_OPERATION, ERROR_INVALID_PARAMETER, ERROR_INVALID_PIXEL_FORMAT,
            ERROR_NO_SYSTEM_RESOURCES, HMODULE, FreeLibrary,
        },
        Graphics::{
            Gdi::{GetDC, ReleaseDC, HDC},
            OpenGL::{
                wglCreateContext, wglDeleteContext, wglGetProcAddress, wglMakeCurrent, ChoosePixelFormat, DescribePixelFormat,
                SetPixelFormat, SwapBuffers, HGLRC, PFD_DOUBLEBUFFER, PFD_DRAW_TO_WINDOW, PFD_MAIN_PLANE, PFD_SUPPORT_OPENGL,
                PFD_TYPE_RGBA, PIXELFORMATDESCRIPTOR,
            },
        },
        System::LibraryLoader::{GetModuleHandleW, GetProcAddress, LoadLibraryW},
        UI::WindowsAndMessaging::{
            CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, UnregisterClassW, CS_OWNDC, CW_USEDEFAULT, WNDCLASSW,
            WS_OVERLAPPEDWINDOW,
        },
    },
};

use exposed::{
    destroy::{Destroy, Destroyable},
    window::{
        platform::{WindowBuilder, WindowHandle},
        Context, Event,
    },
};

use crate::GlConfigPicker;

pub use glutin_wgl_sys as pgl;

pub use pgl::wgl_extra as pgl_extra;

#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct GlSurfaceBuilder {
    pub pixelFormatAttribs: *const i32,
}

impl Default for GlSurfaceBuilder {
    fn default() -> Self {
        Self {
            pixelFormatAttribs: {
                const GL_TRUE: u32 = 1;

                #[rustfmt::skip]
                static PIXEL_FORMAT_ATTRIBS: [u32; 19] = [
                    wgl_extra::DRAW_TO_WINDOW_ARB,     GL_TRUE,
                    wgl_extra::SUPPORT_OPENGL_ARB,     GL_TRUE,
                    wgl_extra::DOUBLE_BUFFER_ARB,      GL_TRUE,
                    wgl_extra::ACCELERATION_ARB,       wgl_extra::FULL_ACCELERATION_ARB,
                    wgl_extra::PIXEL_TYPE_ARB,         wgl_extra::TYPE_RGBA_ARB,
                    wgl_extra::COLOR_BITS_ARB,         32,
                    wgl_extra::DEPTH_BITS_ARB,         24,
                    wgl_extra::STENCIL_BITS_ARB,       8,
                    wgl_extra::SAMPLES_ARB,            4,
                    0
                ];

                PIXEL_FORMAT_ATTRIBS.as_ptr() as *const i32
            },
        }
    }
}

impl GlSurfaceBuilder {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn build_with<E: Event>(
        &self, context: Context, window_builder: &WindowBuilder,
    ) -> Result<(GlSurface, WindowHandle), Error> {
        let window = window_builder.build::<E>(context)?;
        let display = self.build::<E>(window)?;

        Ok((display, window))
    }

    pub fn build<E: Event>(&self, window: WindowHandle) -> Result<GlSurface, Error> {
        if unsafe { WGL }.is_null() {
            return Err(Error::new(std::io::ErrorKind::Other, "Todo wgl load error."));
        }

        let wgl = unsafe { &*WGL };

        let real_dc = unsafe { GetDC(window.0) };
        if real_dc == 0 {
            return Err(Error::new(std::io::ErrorKind::Other, "GetDc failed to get DC for HWND."));
        }

        if !wgl.ChoosePixelFormatARB.is_loaded() {
            return Err(Error::new(std::io::ErrorKind::Other, "Could not found ChoosePixelFormatARB!"));
        }

        if !wgl.CreateContextAttribsARB.is_loaded() {
            return Err(Error::new(std::io::ErrorKind::Other, "Could not found CreateContextAttribsARB!"));
        }

        let mut pixel_format: i32 = 0;
        let mut num_formats: u32 = 0;

        unsafe {
            wgl.ChoosePixelFormatARB(real_dc as _, self.pixelFormatAttribs, null(), 1, &mut pixel_format, &mut num_formats)
        };

        if num_formats == 0 {
            return Err(Error::last_os_error());
        }

        let mut pfd: PIXELFORMATDESCRIPTOR = unsafe { std::mem::zeroed() };
        if unsafe { DescribePixelFormat(real_dc, pixel_format, std::mem::size_of::<PIXELFORMATDESCRIPTOR>() as _, &mut pfd) } == 0
        {
            return Err(Error::last_os_error());
        }

        if unsafe { SetPixelFormat(real_dc, pixel_format, &pfd) } == 0 {
            return Err(Error::last_os_error());
        }

        Ok(GlSurface { dc: real_dc })
    }
}

#[repr(C)]
#[derive(Debug, Clone)]
pub struct GlContextBuilder {
    pub debug: u32,
    pub major: u32,
    pub minor: u32,
}

impl Default for GlContextBuilder {
    fn default() -> Self {
        Self { debug: wgl_extra::CONTEXT_DEBUG_BIT_ARB, major: 4, minor: 3 }
    }
}

impl GlContextBuilder {
    // !! WARN could cause problems when editing
    pub fn with_version(&mut self, major: u32, minor: u32) -> &mut Self {
        self.major = major;
        self.minor = minor;
        self
    }

    pub fn with_debug(&mut self) -> &mut Self {
        self.debug |= wgl_extra::CONTEXT_DEBUG_BIT_ARB;
        self
    }

    pub fn build(&self, display: GlSurface, share_context: GlContext) -> Result<GlContext, Error> {
        unsafe {
            debug_assert!(!WGL.is_null());
            let wgl = &*WGL;

            let pixel_context_attribs = [
                wgl_extra::CONTEXT_MAJOR_VERSION_ARB,
                self.major,
                wgl_extra::CONTEXT_MINOR_VERSION_ARB,
                self.minor,
                wgl_extra::CONTEXT_PROFILE_MASK_ARB,
                wgl_extra::CONTEXT_CORE_PROFILE_BIT_ARB,
                wgl_extra::CONTEXT_FLAGS_ARB,
                self.debug,
                0,
            ];

            let gl_context =
                wgl.CreateContextAttribsARB(display.dc as _, share_context.context as _, pixel_context_attribs.as_ptr().cast())
                    as isize;

            if gl_context == 0 {
                println!("{}", GetLastError());
                match GetLastError() {
                    ERROR_INVALID_OPERATION => return Err(Error::new(std::io::ErrorKind::Other, "ERROR_INVALID_OPERATION")),
                    ERROR_DC_NOT_FOUND => return Err(Error::new(std::io::ErrorKind::Other, "ERROR_DC_NOT_FOUND")),
                    ERROR_INVALID_PIXEL_FORMAT => {
                        return Err(Error::new(std::io::ErrorKind::Other, "ERROR_INVALID_PIXEL_FORMAT"))
                    }
                    ERROR_NO_SYSTEM_RESOURCES => return Err(Error::new(std::io::ErrorKind::Other, "ERROR_NO_SYSTEM_RESOURCES")),
                    ERROR_INVALID_PARAMETER => return Err(Error::new(std::io::ErrorKind::Other, "ERROR_INVALID_PARAMETER")),

                    e => return Err(Error::new(std::io::ErrorKind::Other, format!("Unknown error {e}, {e:#X}"))),
                }
            }

            Ok(GlContext { context: gl_context })
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GlSurface {
    pub dc: HDC,
}

impl GlSurface {
    pub fn build_with<E: Event, P: GlConfigPicker>(
        window_builder: &WindowBuilder, context: Context, min_config: &[u32], picker: &mut P,
    ) -> Result<(GlSurface, WindowHandle), Error> {
        let window = Destroyable(window_builder.build::<E>(context)?);
        let surface = Self::build::<E, P>(window.0, min_config, picker)?;

        Ok((surface, unsafe { window.into_inner() }))
    }

    pub fn build<E: Event, P: GlConfigPicker>(window: WindowHandle, config: &[u32], picker: &mut P) -> Result<GlSurface, Error> {
        let wgl = get_wgl()?;

        let dc = unsafe { GetDC(window.0) };
        if dc == 0 {
            return Err(ErrorKind::Other.into());
        }

        let mut num_pixel_format = 0;
        let attr = wgl_extra::NUMBER_PIXEL_FORMATS_ARB as i32;

        if unsafe { wgl.GetPixelFormatAttribivARB(dc as _, 0, 0, 1, &attr, &mut num_pixel_format) } == 0 {
            return Err(Error::last_os_error());
        }

        let mut pixel_formats: Vec<i32> = Vec::with_capacity(num_pixel_format as _);

        let conf = if config.len() == 0 { null() } else { config.as_ptr() };

        let mut pixel_formats_len = 0;
        if unsafe {
            wgl.ChoosePixelFormatARB(
                dc as _,
                conf.cast(),
                null(),
                num_pixel_format as _,
                pixel_formats.as_mut_ptr(),
                &mut pixel_formats_len,
            )
        } == 0
        {
            return Err(Error::last_os_error());
        }

        unsafe { pixel_formats.set_len(pixel_formats_len as _) };

        let mut picked_format = None;

        for pixel_format in pixel_formats {
            let pixel_format = GlPixelFormat { hdc: dc, format: pixel_format as _ };
            if let Some(c) = picker.pick(pixel_format) {
                picked_format = Some(c);
            }
        }

        if let Some(picked_format) = picked_format {
            let mut pfd: PIXELFORMATDESCRIPTOR = unsafe { std::mem::zeroed() };
            if unsafe { DescribePixelFormat(dc, picked_format as _, std::mem::size_of::<PIXELFORMATDESCRIPTOR>() as _, &mut pfd) }
                == 0
            {
                return Err(Error::last_os_error());
            }

            if unsafe { SetPixelFormat(dc, picked_format as _, &pfd) } == 0 {
                return Err(Error::last_os_error());
            }

            Ok(GlSurface { dc })
        } else {
            todo!()
        }
    }

    pub fn create_context(&self, config: &[u32], share_context: GlContext) -> Result<GlContext, Error> {
        let wgl = get_wgl()?;

        let context = unsafe { wgl.CreateContextAttribsARB(self.dc as _, share_context.context as _, config.as_ptr().cast()) };
        if context.is_null() {
            return Err(Error::last_os_error());
        }

        Ok(GlContext { context: context as _ })
    }

    pub fn swap_buffers(self) -> Result<(), Error> {
        if unsafe { SwapBuffers(self.dc) } == 0 {
            Err(Error::last_os_error())
        } else {
            Ok(())
        }
    }

    pub fn set_swap_interval(self, interval: i32) -> Result<(), Error> {
        unsafe {
            debug_assert!(!WGL.is_null());

            let wgl = &*WGL;
            if wgl.SwapIntervalEXT.is_loaded() {
                if wgl.SwapIntervalEXT(interval) == 0 {
                    Err(Error::last_os_error())
                } else {
                    Ok(())
                }
            } else {
                Err(Error::new(std::io::ErrorKind::Other, "wglSwapIntervalEXT is not loaded."))
            }
        }
    }

    pub fn make_current(self, context: GlContext) -> Result<(), Error> {
        if unsafe { wglMakeCurrent(self.dc, context.context) } == 0 {
            Err(Error::last_os_error())
        } else {
            Ok(())
        }
    }
}

impl Destroy for GlSurface {
    fn destroy(&mut self) -> Result<(), Error> {
        Ok(())
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GlContext {
    pub context: HGLRC,
}

impl GlContext {
    pub const NO_CONTEXT: Self = Self { context: 0 };
}

impl Destroy for GlContext {
    fn destroy(&mut self) -> Result<(), Error> {
        if unsafe { wglDeleteContext(self.context) } == 0 {
            Err(Error::last_os_error())
        } else {
            Ok(())
        }
    }
}

#[repr(C)]
pub struct GlPixelFormat {
    pub hdc: HDC,
    pub format: usize,
}

impl GlPixelFormat {
    pub fn get<const C: usize>(&self, attributes: &[u32; C], values: &mut [i32; C]) -> Result<(), Error> {
        let wgl = get_wgl()?;

        if unsafe {
            wgl.GetPixelFormatAttribivARB(
                self.hdc as _,
                self.format as _,
                0,
                C as _,
                attributes.as_ptr().cast(),
                values.as_mut_ptr(),
            )
        } == 0
        {
            return Err(Error::last_os_error());
        }

        Ok(())
    }
}

pub fn get_wgl() -> Result<&'static mut Wgl, Error> {
    unsafe {
        if !WGL.is_null() {
            Ok(&mut *WGL)
        } else {
            Err(Error::new(ErrorKind::NotFound, "First initialize WGL with load_lib_opengl."))
        }
    }
}

const DUMMY_CLASS_NAME: *const u16 = w!("Dumb Dumb");
const DUMMY_WINDOW_NAME: *const u16 = w!("Dumb Dumb win");
pub static mut OPENGL_DLL_NAME: *const u16 = w!("opengl32.dll");

const WGL_LAYOUT: Layout = Layout::new::<Wgl>();

pub static mut WGL: *mut Wgl = null_mut();

pub static mut LIB_OPENGL: HMODULE = 0;

pub fn load_lib_opengl() -> Result<(), Error> {
    unsafe {
        if LIB_OPENGL == 0 {
            LIB_OPENGL = LoadLibraryW(OPENGL_DLL_NAME);
            if LIB_OPENGL == 0 {
                return Err(Error::last_os_error());
            }
        } else {
            eprintln!("LIB_OPENGL is already loaded.")
        }
    }

    if unsafe { WGL.is_null() } {
        let h_instance = unsafe { GetModuleHandleW(null()) };

        let wc: WNDCLASSW = WNDCLASSW {
            style: CS_OWNDC,
            lpfnWndProc: Some(DefWindowProcW),
            cbClsExtra: 0,
            cbWndExtra: 0,
            hInstance: h_instance,
            hIcon: 0,
            hCursor: 0,
            hbrBackground: 0,
            lpszMenuName: null(),
            lpszClassName: DUMMY_CLASS_NAME,
        };

        if unsafe { RegisterClassW(&wc) } == 0 {
            return Err(Error::last_os_error());
        }

        let dummy_window = unsafe {
            CreateWindowExW(
                0,
                DUMMY_CLASS_NAME,
                DUMMY_WINDOW_NAME,
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                0,
                0,
                h_instance,
                null(),
            )
        };

        if dummy_window == 0 {
            return Err(Error::last_os_error());
        }

        let dummy_dc = unsafe { GetDC(dummy_window) };

        if dummy_dc == 0 {
            return Err(Error::new(std::io::ErrorKind::Other, format!("[{}:{}]Failed to get dummy DC", file!(), line!())));
        }

        let mut pfd: PIXELFORMATDESCRIPTOR = unsafe { zeroed() };
        pfd.nSize = std::mem::size_of::<PIXELFORMATDESCRIPTOR>() as _;
        pfd.nVersion = 1;
        pfd.iPixelType = PFD_TYPE_RGBA;
        pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
        pfd.cColorBits = 32;
        pfd.iLayerType = PFD_MAIN_PLANE as _;
        pfd.cDepthBits = 24;
        pfd.cStencilBits = 8;

        let pixel_format = unsafe { ChoosePixelFormat(dummy_dc, &pfd) };
        if pixel_format == 0 {
            return Err(Error::last_os_error());
        }

        if unsafe { SetPixelFormat(dummy_dc, pixel_format, &pfd) } == 0 {
            return Err(Error::new(std::io::ErrorKind::Other, format!("[{}:{}] Failed to set pixel format.", file!(), line!())));
        }

        let dummy_context = unsafe { wglCreateContext(dummy_dc) };

        if dummy_context == 0 {
            return Err(Error::last_os_error());
        }

        if unsafe { wglMakeCurrent(dummy_dc, dummy_context) } == 0 {
            return Err(Error::last_os_error());
        }

        unsafe {
            WGL = alloc(WGL_LAYOUT).cast();
            if WGL.is_null() {
                handle_alloc_error(WGL_LAYOUT)
            }
        }

        unsafe { assert!(LIB_OPENGL != 0) };

        // TODO: remove null symbol pushing
        unsafe {
            *WGL = Wgl::load_with(|mut symbol| {
                if symbol == "wglUseFontBitmaps" {
                    symbol = "wglUseFontBitmapsW"
                }
                if symbol == "wglUseFontOutlines" {
                    symbol = "wglUseFontOutlinesW"
                }

                let mut c_symbol = symbol.to_string();
                c_symbol.push('\0');

                if let Some(pfn) = GetProcAddress(LIB_OPENGL, c_symbol.as_ptr()) {
                    return pfn as _;
                }

                if let Some(pfn) = wglGetProcAddress(c_symbol.as_ptr()) {
                    return pfn as _;
                }

                null()
            });
        }

        // TODO fix early returning before the cleanup

        if unsafe { wglMakeCurrent(dummy_dc, 0) } == 0 {
            return Err(Error::last_os_error());
        }

        if unsafe { wglDeleteContext(dummy_context) } == 0 {
            return Err(Error::last_os_error());
        }
        if unsafe { ReleaseDC(dummy_window, dummy_dc) } == 0 {
            return Err(Error::last_os_error());
        }
        if unsafe { DestroyWindow(dummy_window) } == 0 {
            return Err(Error::last_os_error());
        }
        if unsafe { UnregisterClassW(DUMMY_CLASS_NAME, h_instance) } == 0 {
            return Err(Error::last_os_error());
        }
    } else {
        eprintln!("WGL is already loaded.")
    }

    Ok(())
}

pub fn free_lib_opengl() -> Result<(), Error> {
    if unsafe { WGL.is_null() } {
        eprintln!("Static Egl library is already deallocated.");
    } else {
        unsafe { dealloc(WGL as *mut u8, WGL_LAYOUT) };
        unsafe { WGL = null_mut() };
    }

    if unsafe { LIB_OPENGL } == 0 {
        eprintln!("Static Gl library is already deallocated.");
    } else {
        if unsafe { FreeLibrary(LIB_OPENGL) } == 0 {
            return Err(Error::last_os_error());
        }
        unsafe { LIB_OPENGL = 0 };
    }
    Ok(())
}

pub unsafe fn get_proc_addr(symbol: *const c_char) -> *const c_void {
    debug_assert!(!WGL.is_null());
    debug_assert!(LIB_OPENGL != 0);

    if let Some(pfn) = GetProcAddress(LIB_OPENGL, symbol as *const u8) {
        return pfn as _;
    }

    let wgl = &*WGL;
    wgl.GetProcAddress(symbol).cast()
}