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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! Thread-bound OpenGL 3.3–4.6 Core context, pipeline state, draw/compute commands,
//! and zero-dependency offscreen WGL context creation on Windows.
use std::collections::HashSet;
use std::ffi::{c_void, CString};
use std::fmt;
use std::rc::Rc;
use crate::error::{checked_sizei, GlError, GlErrorCode, Result};
use crate::loader::{gl_ptr_to_string, os::SystemGlLibrary, GlFnTable, SystemLibraryGuard};
use crate::sys;
use crate::types::{
BlendEquation, BlendFactor, Capability, ClearColor, ClearMask, CompareFunc, ContextInfo,
CullFace, FrontFace, GlProfile, GlVersion, IndexType, MemoryBarrierFlags, PixelFormat,
PixelType, PolygonMode, PrimitiveMode, ScissorRect, Viewport,
};
// ---------------------------------------------------------------------------
// Optional native context handle (keeps OS context alive until all GL objects drop)
// ---------------------------------------------------------------------------
pub(crate) trait NativeContextDrop {}
// ---------------------------------------------------------------------------
// Internal shared state (intentionally !Send + !Sync via Rc)
// ---------------------------------------------------------------------------
pub(crate) struct GlInner {
pub(crate) fns: GlFnTable,
pub(crate) info: ContextInfo,
pub(crate) extensions: HashSet<String>,
_sys_lib: Option<SystemLibraryGuard>,
_native_ctx: Option<Box<dyn NativeContextDrop>>,
}
impl GlInner {
/// Checks `glGetError()` and returns `Err(GlError::GlCallFailed)` if non-zero.
#[inline]
pub(crate) fn check_gl_error(&self, operation: &'static str) -> Result<()> {
// SAFETY: Context is current on this thread (`GlInner` is `!Send + !Sync`).
let code = unsafe { (self.fns.get_error)() };
if code == sys::GL_NO_ERROR {
Ok(())
} else {
Err(GlError::GlCallFailed {
operation,
code: GlErrorCode(code),
})
}
}
/// Drains all pending OpenGL error flags from the driver queue.
pub(crate) fn drain_errors(&self) -> Vec<GlErrorCode> {
let mut errors = Vec::new();
// Cap iterations to guard against broken drivers returning non-zero forever.
for _ in 0..64 {
// SAFETY: Context is current on this thread.
let code = unsafe { (self.fns.get_error)() };
if code == sys::GL_NO_ERROR {
break;
}
errors.push(GlErrorCode(code));
}
errors
}
}
/// Configuration for creating a [`GlContext`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContextDesc {
/// Minimum required OpenGL version (defaults to `3.3`).
pub min_version: GlVersion,
/// Preferred OpenGL version when creating an offscreen context (defaults to `4.6`).
pub preferred_version: GlVersion,
/// Request a debug OpenGL context (`WGL_CONTEXT_DEBUG_BIT_ARB`) when creating an offscreen context.
pub debug: bool,
}
impl Default for ContextDesc {
fn default() -> Self {
Self {
min_version: GlVersion::V3_3,
preferred_version: GlVersion::V4_6,
debug: false,
}
}
}
/// Thread-affine handle to an active OpenGL 3.3–4.6 Core context.
///
/// `GlContext` is intentionally `!Send` and `!Sync` (backed by `Rc`), enforcing
/// OpenGL's thread-local context affinity at compile time. Cloning a `GlContext`
/// is cheap (reference-count increment) and all GPU objects created from it keep
/// the dispatch table and any owned native context alive until they are dropped.
#[derive(Clone)]
pub struct GlContext {
pub(crate) inner: Rc<GlInner>,
}
impl fmt::Debug for GlContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GlContext")
.field("version", &self.inner.info.version)
.field("profile", &self.inner.info.profile)
.field("renderer", &self.inner.info.renderer)
.finish()
}
}
impl GlContext {
/// Initializes a [`GlContext`] from a user-supplied OpenGL symbol loader
/// (for example, `glutin`, `glfw`, `sdl2`, or a custom WGL/GLX/EGL loader).
///
/// # Safety
/// An OpenGL context must already be current on the calling thread, and `loader`
/// must return valid OpenGL function pointers (or null) for the requested symbol names.
pub unsafe fn from_loader<F>(mut loader: F, desc: &ContextDesc) -> Result<Self>
where
F: FnMut(&str) -> *const c_void,
{
let fns = GlFnTable::load(&mut loader)?;
Self::finish_init(fns, desc, None, None)
}
/// Initializes a [`GlContext`] using the operating system's native OpenGL loader
/// (`opengl32.dll` / `libGL.so.1` / `OpenGL.framework`).
///
/// # Safety
/// An OpenGL context must already be current on the calling thread.
pub unsafe fn load_with_system_loader(desc: &ContextDesc) -> Result<Self> {
let lib = SystemGlLibrary::load().map_err(|reason| GlError::LibraryLoadFailed { reason })?;
let fns = GlFnTable::load(&mut |name| {
let Ok(cstr) = CString::new(name) else {
return std::ptr::null();
};
lib.get_proc_address(cstr.as_bytes_with_nul())
})?;
Self::finish_init(fns, desc, Some(SystemLibraryGuard::new(lib)), None)
}
fn finish_init(
fns: GlFnTable,
desc: &ContextDesc,
sys_lib: Option<SystemLibraryGuard>,
native_ctx: Option<Box<dyn NativeContextDrop>>,
) -> Result<Self> {
// Clear any pre-existing errors left by context creation.
for _ in 0..64 {
// SAFETY: Context is current on this thread.
if unsafe { (fns.get_error)() } == sys::GL_NO_ERROR {
break;
}
}
let mut major: sys::GLint = 0;
let mut minor: sys::GLint = 0;
// SAFETY: `glGetIntegerv` writes a single `GLint` to valid stack storage.
unsafe {
(fns.get_integerv)(sys::GL_MAJOR_VERSION, &mut major);
(fns.get_integerv)(sys::GL_MINOR_VERSION, &mut minor);
}
let version = GlVersion::new(
u32::try_from(major).unwrap_or(0),
u32::try_from(minor).unwrap_or(0),
);
if version < desc.min_version {
return Err(GlError::UnsupportedVersion {
required: desc.min_version,
actual: version,
});
}
let mut profile_mask: sys::GLint = 0;
// SAFETY: `glGetIntegerv` writes a single `GLint` to valid stack storage.
unsafe {
(fns.get_integerv)(sys::GL_CONTEXT_PROFILE_MASK, &mut profile_mask);
}
let profile = if (profile_mask & sys::GL_CONTEXT_CORE_PROFILE_BIT) != 0 {
GlProfile::Core
} else if (profile_mask & sys::GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0 {
GlProfile::Compatibility
} else {
GlProfile::Unknown
};
// SAFETY: `glGetString` returns static driver-owned NUL-terminated strings or null.
let (vendor, renderer, version_string, glsl_version) = unsafe {
(
gl_ptr_to_string((fns.get_string)(sys::GL_VENDOR)),
gl_ptr_to_string((fns.get_string)(sys::GL_RENDERER)),
gl_ptr_to_string((fns.get_string)(sys::GL_VERSION)),
gl_ptr_to_string((fns.get_string)(sys::GL_SHADING_LANGUAGE_VERSION)),
)
};
// Query extensions via GL 3.0+ `glGetStringi`
let mut extensions = HashSet::new();
if let Some(get_stringi) = fns.get_stringi {
let mut num_ext: sys::GLint = 0;
// SAFETY: Valid stack pointer for `GL_NUM_EXTENSIONS`.
unsafe {
(fns.get_integerv)(sys::GL_NUM_EXTENSIONS, &mut num_ext);
}
if num_ext > 0 {
for i in 0..(num_ext as sys::GLuint) {
// SAFETY: `i < num_ext` is in range and `glGetStringi` returns a static C string.
let ext = unsafe { gl_ptr_to_string(get_stringi(sys::GL_EXTENSIONS, i)) };
if !ext.is_empty() {
extensions.insert(ext);
}
}
}
}
// Drain any benign query error (e.g. profile mask on non-3.2 drivers)
for _ in 0..64 {
// SAFETY: Context is current on this thread.
if unsafe { (fns.get_error)() } == sys::GL_NO_ERROR {
break;
}
}
let info = ContextInfo {
version,
profile,
vendor,
renderer,
version_string,
glsl_version,
};
Ok(Self {
inner: Rc::new(GlInner {
fns,
info,
extensions,
_sys_lib: sys_lib,
_native_ctx: native_ctx,
}),
})
}
/// Returns queried metadata (`version`, `profile`, `vendor`, `renderer`, `glsl_version`).
#[inline]
pub fn info(&self) -> &ContextInfo {
&self.inner.info
}
/// Returns the active OpenGL version.
#[inline]
pub fn version(&self) -> GlVersion {
self.inner.info.version
}
/// Returns `true` if the given OpenGL extension string is supported by this context.
#[inline]
pub fn has_extension(&self, name: &str) -> bool {
self.inner.extensions.contains(name)
}
/// Returns the full set of advertised OpenGL extension names.
#[inline]
pub fn extensions(&self) -> &HashSet<String> {
&self.inner.extensions
}
/// Returns `true` if OpenGL 4.3+ compute shaders (`glDispatchCompute`) are available.
#[inline]
pub fn supports_compute(&self) -> bool {
self.inner.fns.dispatch_compute.is_some()
}
/// Returns `true` if OpenGL 4.4+ immutable buffer storage (`glBufferStorage`) is available.
#[inline]
pub fn supports_buffer_storage(&self) -> bool {
self.inner.fns.buffer_storage.is_some()
}
/// Returns `true` if OpenGL 4.3 / `KHR_debug` debug callbacks are available.
#[inline]
pub fn supports_debug_output(&self) -> bool {
self.inner.fns.debug_message_callback.is_some()
}
/// Checks `glGetError()` and returns `Err` if the driver has recorded an error.
#[inline]
pub fn check_error(&self) -> Result<()> {
self.inner.check_gl_error("check_error")
}
/// Drains and returns all pending OpenGL error codes from the driver error queue.
#[inline]
pub fn drain_errors(&self) -> Vec<GlErrorCode> {
self.inner.drain_errors()
}
/// Queries a single integer state parameter (`glGetIntegerv`).
#[inline]
pub fn get_integer(&self, pname: u32) -> i32 {
let mut value: sys::GLint = 0;
// SAFETY: `value` is a valid mutable stack pointer.
unsafe { (self.inner.fns.get_integerv)(pname, &mut value) };
value
}
/// Queries a single float state parameter (`glGetFloatv`).
#[inline]
pub fn get_float(&self, pname: u32) -> f32 {
let mut value: sys::GLfloat = 0.0;
// SAFETY: `value` is a valid mutable stack pointer.
unsafe { (self.inner.fns.get_floatv)(pname, &mut value) };
value
}
// -----------------------------------------------------------------------
// Pipeline State
// -----------------------------------------------------------------------
/// Sets the active viewport rectangle (`glViewport`).
pub fn set_viewport(&self, viewport: Viewport) -> Result<()> {
let w = checked_sizei(viewport.width as usize, "set_viewport width")?;
let h = checked_sizei(viewport.height as usize, "set_viewport height")?;
// SAFETY: Dimensions are validated non-negative `GLsizei`.
unsafe { (self.inner.fns.viewport)(viewport.x, viewport.y, w, h) };
Ok(())
}
/// Sets the scissor test clipping rectangle (`glScissor`).
pub fn set_scissor(&self, rect: ScissorRect) -> Result<()> {
let w = checked_sizei(rect.width as usize, "set_scissor width")?;
let h = checked_sizei(rect.height as usize, "set_scissor height")?;
// SAFETY: Dimensions are validated non-negative `GLsizei`.
unsafe { (self.inner.fns.scissor)(rect.x, rect.y, w, h) };
Ok(())
}
/// Sets the RGBA color used by [`Self::clear`] (`glClearColor`).
#[inline]
pub fn set_clear_color(&self, color: ClearColor) {
// SAFETY: Pure state setter on the current context.
unsafe { (self.inner.fns.clear_color)(color.r, color.g, color.b, color.a) };
}
/// Sets the depth value used by [`Self::clear`] (`glClearDepth`).
#[inline]
pub fn set_clear_depth(&self, depth: f64) {
// SAFETY: Pure state setter on the current context.
unsafe { (self.inner.fns.clear_depth)(depth) };
}
/// Clears the selected framebuffer attachments (`glClear`).
#[inline]
pub fn clear(&self, mask: ClearMask) {
// SAFETY: `mask` is constructed from valid `GL_*_BUFFER_BIT` flags.
unsafe { (self.inner.fns.clear)(mask.bits()) };
}
/// Enables an OpenGL pipeline capability (`glEnable`).
#[inline]
pub fn enable(&self, cap: Capability) {
// SAFETY: `cap` is a valid `GLenum` capability.
unsafe { (self.inner.fns.enable)(cap as sys::GLenum) };
}
/// Disables an OpenGL pipeline capability (`glDisable`).
#[inline]
pub fn disable(&self, cap: Capability) {
// SAFETY: `cap` is a valid `GLenum` capability.
unsafe { (self.inner.fns.disable)(cap as sys::GLenum) };
}
/// Returns whether an OpenGL pipeline capability is currently enabled (`glIsEnabled`).
#[inline]
pub fn is_enabled(&self, cap: Capability) -> bool {
// SAFETY: `cap` is a valid `GLenum` capability.
unsafe { (self.inner.fns.is_enabled)(cap as sys::GLenum) != sys::GL_FALSE }
}
/// Configures color blending factors (`glBlendFunc`).
#[inline]
pub fn set_blend_func(&self, src: BlendFactor, dst: BlendFactor) {
// SAFETY: Both factors are valid `GLenum` blend factors.
unsafe { (self.inner.fns.blend_func)(src as sys::GLenum, dst as sys::GLenum) };
}
/// Configures separate RGB and alpha blending factors (`glBlendFuncSeparate`).
#[inline]
pub fn set_blend_func_separate(
&self,
src_rgb: BlendFactor,
dst_rgb: BlendFactor,
src_alpha: BlendFactor,
dst_alpha: BlendFactor,
) {
// SAFETY: All four factors are valid `GLenum` blend factors.
unsafe {
(self.inner.fns.blend_func_separate)(
src_rgb as sys::GLenum,
dst_rgb as sys::GLenum,
src_alpha as sys::GLenum,
dst_alpha as sys::GLenum,
);
}
}
/// Configures the blending equation (`glBlendEquation`).
#[inline]
pub fn set_blend_equation(&self, eq: BlendEquation) {
// SAFETY: `eq` is a valid `GLenum` blend equation.
unsafe { (self.inner.fns.blend_equation)(eq as sys::GLenum) };
}
/// Configures the depth comparison function (`glDepthFunc`).
#[inline]
pub fn set_depth_func(&self, func: CompareFunc) {
// SAFETY: `func` is a valid `GLenum` compare function.
unsafe { (self.inner.fns.depth_func)(func as sys::GLenum) };
}
/// Enables or disables writing into the depth buffer (`glDepthMask`).
#[inline]
pub fn set_depth_mask(&self, write_enabled: bool) {
let flag = if write_enabled {
sys::GL_TRUE
} else {
sys::GL_FALSE
};
// SAFETY: Pure state setter.
unsafe { (self.inner.fns.depth_mask)(flag) };
}
/// Enables or disables writing to individual RGBA color channels (`glColorMask`).
#[inline]
pub fn set_color_mask(&self, r: bool, g: bool, b: bool, a: bool) {
let b2g = |v: bool| if v { sys::GL_TRUE } else { sys::GL_FALSE };
// SAFETY: Pure state setter.
unsafe { (self.inner.fns.color_mask)(b2g(r), b2g(g), b2g(b), b2g(a)) };
}
/// Selects which polygon faces are culled (`glCullFace`).
#[inline]
pub fn set_cull_face(&self, face: CullFace) {
// SAFETY: `face` is a valid `GLenum` cull face mode.
unsafe { (self.inner.fns.cull_face)(face as sys::GLenum) };
}
/// Selects front-face triangle winding order (`glFrontFace`).
#[inline]
pub fn set_front_face(&self, winding: FrontFace) {
// SAFETY: `winding` is `GL_CW` or `GL_CCW`.
unsafe { (self.inner.fns.front_face)(winding as sys::GLenum) };
}
/// Sets polygon rasterization mode (`glPolygonMode`).
#[inline]
pub fn set_polygon_mode(&self, face: CullFace, mode: PolygonMode) {
// SAFETY: Both arguments are valid `GLenum` values.
unsafe { (self.inner.fns.polygon_mode)(face as sys::GLenum, mode as sys::GLenum) };
}
// -----------------------------------------------------------------------
// Draw & Compute Commands
// -----------------------------------------------------------------------
/// Issues a non-indexed draw call (`glDrawArrays`).
pub fn draw_arrays(&self, mode: PrimitiveMode, first: u32, count: u32) -> Result<()> {
let first_i = checked_sizei(first as usize, "draw_arrays first")?;
let count_i = checked_sizei(count as usize, "draw_arrays count")?;
// SAFETY: `first_i` and `count_i` are non-negative `GLsizei`.
unsafe { (self.inner.fns.draw_arrays)(mode as sys::GLenum, first_i, count_i) };
Ok(())
}
/// Issues an instanced non-indexed draw call (`glDrawArraysInstanced`).
pub fn draw_arrays_instanced(
&self,
mode: PrimitiveMode,
first: u32,
count: u32,
instance_count: u32,
) -> Result<()> {
let first_i = checked_sizei(first as usize, "draw_arrays_instanced first")?;
let count_i = checked_sizei(count as usize, "draw_arrays_instanced count")?;
let inst_i = checked_sizei(instance_count as usize, "draw_arrays_instanced instances")?;
// SAFETY: All counts are validated non-negative `GLsizei`.
unsafe {
(self.inner.fns.draw_arrays_instanced)(mode as sys::GLenum, first_i, count_i, inst_i);
}
Ok(())
}
/// Issues an indexed draw call (`glDrawElements`) using the currently bound element array buffer.
pub fn draw_elements(
&self,
mode: PrimitiveMode,
count: u32,
index_type: IndexType,
byte_offset: usize,
) -> Result<()> {
if byte_offset % index_type.byte_size() != 0 {
return Err(GlError::InvalidParameter {
parameter: "byte_offset",
reason: "element byte offset must be aligned to index_type size",
});
}
let count_i = checked_sizei(count as usize, "draw_elements count")?;
// SAFETY: In OpenGL Core, `indices` is a byte offset into the bound `GL_ELEMENT_ARRAY_BUFFER`.
unsafe {
(self.inner.fns.draw_elements)(
mode as sys::GLenum,
count_i,
index_type as sys::GLenum,
byte_offset as *const c_void,
);
}
Ok(())
}
/// Issues an instanced indexed draw call (`glDrawElementsInstanced`).
pub fn draw_elements_instanced(
&self,
mode: PrimitiveMode,
count: u32,
index_type: IndexType,
byte_offset: usize,
instance_count: u32,
) -> Result<()> {
if byte_offset % index_type.byte_size() != 0 {
return Err(GlError::InvalidParameter {
parameter: "byte_offset",
reason: "element byte offset must be aligned to index_type size",
});
}
let count_i = checked_sizei(count as usize, "draw_elements_instanced count")?;
let inst_i = checked_sizei(
instance_count as usize,
"draw_elements_instanced instances",
)?;
// SAFETY: `byte_offset` is aligned and counts are validated non-negative `GLsizei`.
unsafe {
(self.inner.fns.draw_elements_instanced)(
mode as sys::GLenum,
count_i,
index_type as sys::GLenum,
byte_offset as *const c_void,
inst_i,
);
}
Ok(())
}
/// Dispatches a compute shader workgroup grid (`glDispatchCompute`, OpenGL 4.3+).
pub fn dispatch_compute(&self, groups_x: u32, groups_y: u32, groups_z: u32) -> Result<()> {
let Some(dispatch) = self.inner.fns.dispatch_compute else {
return Err(GlError::MissingFunction {
name: "glDispatchCompute",
});
};
if groups_x == 0 || groups_y == 0 || groups_z == 0 {
return Err(GlError::InvalidParameter {
parameter: "groups",
reason: "compute dispatch group counts must be non-zero",
});
}
// SAFETY: `dispatch` was resolved and group counts are non-zero.
unsafe { dispatch(groups_x, groups_y, groups_z) };
self.inner.check_gl_error("glDispatchCompute")
}
/// Inserts a GPU memory barrier (`glMemoryBarrier`, OpenGL 4.2+).
pub fn memory_barrier(&self, barriers: MemoryBarrierFlags) -> Result<()> {
let Some(barrier_fn) = self.inner.fns.memory_barrier else {
return Err(GlError::MissingFunction {
name: "glMemoryBarrier",
});
};
// SAFETY: `barriers` is constructed from valid `GL_*_BARRIER_BIT` constants.
unsafe { barrier_fn(barriers.bits()) };
Ok(())
}
/// Flushes queued OpenGL commands (`glFlush`).
#[inline]
pub fn flush(&self) {
// SAFETY: Valid call on the current context.
unsafe { (self.inner.fns.flush)() };
}
/// Blocks until all previously issued OpenGL commands complete (`glFinish`).
#[inline]
pub fn finish(&self) {
// SAFETY: Valid call on the current context.
unsafe { (self.inner.fns.finish)() };
}
/// Reads pixels from the currently bound read framebuffer into `dst` (`glReadPixels`).
///
/// Automatically sets `GL_PACK_ALIGNMENT` to `1` and validates that `dst.len()` is large
/// enough to prevent out-of-bounds buffer writes.
#[allow(clippy::too_many_arguments)]
pub fn read_pixels(
&self,
x: i32,
y: i32,
width: u32,
height: u32,
format: PixelFormat,
pixel_type: PixelType,
dst: &mut [u8],
) -> Result<()> {
let w = checked_sizei(width as usize, "read_pixels width")?;
let h = checked_sizei(height as usize, "read_pixels height")?;
let expected = (width as usize)
.checked_mul(height as usize)
.and_then(|px| px.checked_mul(format.channel_count()))
.and_then(|ch| ch.checked_mul(pixel_type.component_bytes()))
.ok_or(GlError::IntegerOverflow {
context: "read_pixels byte size",
})?;
if dst.len() < expected {
return Err(GlError::BufferSizeMismatch {
expected,
actual: dst.len(),
});
}
// SAFETY: `GL_PACK_ALIGNMENT = 1` guarantees tightly packed rows matching `expected`,
// and `dst` has at least `expected` writable bytes.
unsafe {
(self.inner.fns.pixel_storei)(sys::GL_PACK_ALIGNMENT, 1);
(self.inner.fns.read_pixels)(
x,
y,
w,
h,
format as sys::GLenum,
pixel_type as sys::GLenum,
dst.as_mut_ptr().cast(),
);
}
self.inner.check_gl_error("glReadPixels")
}
}
// ---------------------------------------------------------------------------
// Zero-dependency Windows WGL Offscreen / Headless Core Context
// ---------------------------------------------------------------------------
#[cfg(windows)]
mod wgl_offscreen {
use std::ffi::{c_char, c_int, c_uint, c_void, CString};
use std::mem;
use std::ptr;
use crate::context::{ContextDesc, GlContext, NativeContextDrop};
use crate::error::{GlError, Result};
use crate::loader::os::SystemGlLibrary;
use crate::loader::{GlFnTable, SystemLibraryGuard};
use crate::types::GlVersion;
type Hwnd = *mut c_void;
type Hdc = *mut c_void;
type Hglrc = *mut c_void;
type Hinstance = *mut c_void;
type Atom = u16;
const CS_OWNDC: u32 = 0x0020;
const WS_OVERLAPPEDWINDOW: u32 = 0x00CF_0000;
const PFD_DRAW_TO_WINDOW: u32 = 0x0000_0004;
const PFD_SUPPORT_OPENGL: u32 = 0x0000_0020;
const PFD_DOUBLEBUFFER: u32 = 0x0000_0001;
const PFD_TYPE_RGBA: u8 = 0;
const PFD_MAIN_PLANE: u8 = 0;
const WGL_CONTEXT_MAJOR_VERSION_ARB: c_int = 0x2091;
const WGL_CONTEXT_MINOR_VERSION_ARB: c_int = 0x2092;
const WGL_CONTEXT_FLAGS_ARB: c_int = 0x2094;
const WGL_CONTEXT_DEBUG_BIT_ARB: c_int = 0x0001;
const WGL_CONTEXT_PROFILE_MASK_ARB: c_int = 0x9126;
const WGL_CONTEXT_CORE_PROFILE_BIT_ARB: c_int = 0x0000_0001;
type WndProc = unsafe extern "system" fn(Hwnd, c_uint, usize, isize) -> isize;
type PfnWglCreateContextAttribsArb =
unsafe extern "system" fn(Hdc, Hglrc, *const c_int) -> Hglrc;
#[repr(C)]
struct WndClassA {
style: c_uint,
lpfn_wnd_proc: WndProc,
cb_cls_extra: c_int,
cb_wnd_extra: c_int,
h_instance: Hinstance,
h_icon: *mut c_void,
h_cursor: *mut c_void,
hbr_background: *mut c_void,
lpsz_menu_name: *const c_char,
lpsz_class_name: *const c_char,
}
#[repr(C)]
struct PixelFormatDescriptor {
n_size: u16,
n_version: u16,
dw_flags: u32,
i_pixel_type: u8,
c_color_bits: u8,
c_red_bits: u8,
c_red_shift: u8,
c_green_bits: u8,
c_green_shift: u8,
c_blue_bits: u8,
c_blue_shift: u8,
c_alpha_bits: u8,
c_alpha_shift: u8,
c_accum_bits: u8,
c_accum_red_bits: u8,
c_accum_green_bits: u8,
c_accum_blue_bits: u8,
c_accum_alpha_bits: u8,
c_depth_bits: u8,
c_stencil_bits: u8,
c_aux_buffers: u8,
i_layer_type: u8,
b_reserved: u8,
dw_layer_mask: u32,
dw_visible_mask: u32,
dw_damage_mask: u32,
}
#[link(name = "kernel32")]
extern "system" {
fn GetModuleHandleA(lpModuleName: *const c_char) -> Hinstance;
}
#[link(name = "user32")]
extern "system" {
fn DefWindowProcA(hwnd: Hwnd, msg: c_uint, wparam: usize, lparam: isize) -> isize;
fn RegisterClassA(lpWndClass: *const WndClassA) -> Atom;
fn CreateWindowExA(
dwExStyle: u32,
lpClassName: *const c_char,
lpWindowName: *const c_char,
dwStyle: u32,
x: c_int,
y: c_int,
nWidth: c_int,
nHeight: c_int,
hWndParent: Hwnd,
hMenu: *mut c_void,
hInstance: Hinstance,
lpParam: *mut c_void,
) -> Hwnd;
fn DestroyWindow(hwnd: Hwnd) -> c_int;
fn GetDC(hwnd: Hwnd) -> Hdc;
fn ReleaseDC(hwnd: Hwnd, hdc: Hdc) -> c_int;
}
#[link(name = "gdi32")]
extern "system" {
fn ChoosePixelFormat(hdc: Hdc, ppfd: *const PixelFormatDescriptor) -> c_int;
fn SetPixelFormat(
hdc: Hdc,
format: c_int,
ppfd: *const PixelFormatDescriptor,
) -> c_int;
}
#[link(name = "opengl32")]
extern "system" {
fn wglCreateContext(hdc: Hdc) -> Hglrc;
fn wglDeleteContext(hglrc: Hglrc) -> c_int;
fn wglMakeCurrent(hdc: Hdc, hglrc: Hglrc) -> c_int;
fn wglGetProcAddress(lpszProc: *const c_char) -> *const c_void;
}
struct WglNativeContext {
hwnd: Hwnd,
hdc: Hdc,
hglrc: Hglrc,
}
impl NativeContextDrop for WglNativeContext {}
impl Drop for WglNativeContext {
fn drop(&mut self) {
// SAFETY: Teardown in strict reverse creation order. All GL objects have
// already been dropped because `GlInner` drops after all `Rc<GlInner>` holders.
unsafe {
let _ = wglMakeCurrent(ptr::null_mut(), ptr::null_mut());
if !self.hglrc.is_null() {
let _ = wglDeleteContext(self.hglrc);
}
if !self.hwnd.is_null() && !self.hdc.is_null() {
let _ = ReleaseDC(self.hwnd, self.hdc);
}
if !self.hwnd.is_null() {
let _ = DestroyWindow(self.hwnd);
}
}
}
}
impl GlContext {
/// Creates a headless / offscreen OpenGL Core Profile context on Windows via WGL.
///
/// Useful for compute pipelines, offscreen rendering, and automated GPU testing
/// with zero third-party windowing dependencies.
pub fn new_offscreen(desc: &ContextDesc) -> Result<Self> {
let class_name = b"SiftGlOffscreenWindowClass\0";
// SAFETY: Win32 module handle for the current executable.
let hinstance = unsafe { GetModuleHandleA(ptr::null()) };
let wc = WndClassA {
style: CS_OWNDC,
lpfn_wnd_proc: DefWindowProcA,
cb_cls_extra: 0,
cb_wnd_extra: 0,
h_instance: hinstance,
h_icon: ptr::null_mut(),
h_cursor: ptr::null_mut(),
hbr_background: ptr::null_mut(),
lpsz_menu_name: ptr::null(),
lpsz_class_name: class_name.as_ptr().cast(),
};
// RegisterClassA may return 0 if already registered in this process; ignore harmless duplicate.
// SAFETY: `wc` is fully initialized with valid pointers.
let _ = unsafe { RegisterClassA(&wc) };
// SAFETY: Creates an invisible 1x1 host window for WGL pixel format & context ownership.
let hwnd = unsafe {
CreateWindowExA(
0,
class_name.as_ptr().cast(),
b"siftgl-offscreen\0".as_ptr().cast(),
WS_OVERLAPPEDWINDOW,
0,
0,
1,
1,
ptr::null_mut(),
ptr::null_mut(),
hinstance,
ptr::null_mut(),
)
};
if hwnd.is_null() {
return Err(GlError::ContextCreationFailed {
reason: "CreateWindowExA returned null".to_owned(),
});
}
// SAFETY: `hwnd` is a valid window handle.
let hdc = unsafe { GetDC(hwnd) };
if hdc.is_null() {
// SAFETY: Clean up window on failure.
unsafe {
let _ = DestroyWindow(hwnd);
}
return Err(GlError::ContextCreationFailed {
reason: "GetDC returned null".to_owned(),
});
}
let pfd = PixelFormatDescriptor {
n_size: mem::size_of::<PixelFormatDescriptor>() as u16,
n_version: 1,
dw_flags: PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
i_pixel_type: PFD_TYPE_RGBA,
c_color_bits: 32,
c_red_bits: 0,
c_red_shift: 0,
c_green_bits: 0,
c_green_shift: 0,
c_blue_bits: 0,
c_blue_shift: 0,
c_alpha_bits: 8,
c_alpha_shift: 0,
c_accum_bits: 0,
c_accum_red_bits: 0,
c_accum_green_bits: 0,
c_accum_blue_bits: 0,
c_accum_alpha_bits: 0,
c_depth_bits: 24,
c_stencil_bits: 8,
c_aux_buffers: 0,
i_layer_type: PFD_MAIN_PLANE,
b_reserved: 0,
dw_layer_mask: 0,
dw_visible_mask: 0,
dw_damage_mask: 0,
};
// SAFETY: `hdc` is valid and `pfd` is properly sized.
let pixel_format = unsafe { ChoosePixelFormat(hdc, &pfd) };
let set_pf_ok = if pixel_format != 0 {
// SAFETY: `hdc` and `pixel_format` are validated above.
unsafe { SetPixelFormat(hdc, pixel_format, &pfd) != 0 }
} else {
false
};
if !set_pf_ok {
// SAFETY: Release DC and window on failure.
unsafe {
let _ = ReleaseDC(hwnd, hdc);
let _ = DestroyWindow(hwnd);
}
return Err(GlError::ContextCreationFailed {
reason: "ChoosePixelFormat / SetPixelFormat failed".to_owned(),
});
}
// Bootstrap legacy context so we can query `wglCreateContextAttribsARB`.
// SAFETY: `hdc` has a valid OpenGL pixel format set.
let legacy_ctx = unsafe { wglCreateContext(hdc) };
let make_current_ok = if !legacy_ctx.is_null() {
// SAFETY: `hdc` and `legacy_ctx` are both valid non-null handles.
unsafe { wglMakeCurrent(hdc, legacy_ctx) != 0 }
} else {
false
};
if !make_current_ok {
// SAFETY: Clean up all Win32/WGL handles on failure.
unsafe {
if !legacy_ctx.is_null() {
let _ = wglDeleteContext(legacy_ctx);
}
let _ = ReleaseDC(hwnd, hdc);
let _ = DestroyWindow(hwnd);
}
return Err(GlError::ContextCreationFailed {
reason: "bootstrap wglCreateContext / wglMakeCurrent failed".to_owned(),
});
}
// Upgrade to a modern Core Profile context via `wglCreateContextAttribsARB`.
let mut active_ctx = legacy_ctx;
// SAFETY: A WGL context is current on this thread.
let raw_create_attribs =
unsafe { wglGetProcAddress(b"wglCreateContextAttribsARB\0".as_ptr().cast()) };
if crate::loader::os::is_valid_gl_proc_ptr(raw_create_attribs) {
// SAFETY: `wglCreateContextAttribsARB` matches `PfnWglCreateContextAttribsArb`.
let create_attribs: PfnWglCreateContextAttribsArb =
unsafe { mem::transmute(raw_create_attribs) };
let candidates = [
desc.preferred_version,
GlVersion::V4_6,
GlVersion::V4_5,
GlVersion::V4_3,
GlVersion::V4_1,
GlVersion::V3_3,
];
let flags = if desc.debug {
WGL_CONTEXT_DEBUG_BIT_ARB
} else {
0
};
for ver in candidates {
if ver < desc.min_version {
continue;
}
let attribs: [c_int; 9] = [
WGL_CONTEXT_MAJOR_VERSION_ARB,
ver.major as c_int,
WGL_CONTEXT_MINOR_VERSION_ARB,
ver.minor as c_int,
WGL_CONTEXT_PROFILE_MASK_ARB,
WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
WGL_CONTEXT_FLAGS_ARB,
flags,
0,
];
// SAFETY: `hdc` is valid and `attribs` is 0-terminated.
let modern_ctx = unsafe { create_attribs(hdc, ptr::null_mut(), attribs.as_ptr()) };
if !modern_ctx.is_null() {
// SAFETY: Switch to the new modern context and delete the bootstrap one.
if unsafe { wglMakeCurrent(hdc, modern_ctx) } != 0 {
// SAFETY: `legacy_ctx` is no longer current.
unsafe {
let _ = wglDeleteContext(legacy_ctx);
}
active_ctx = modern_ctx;
break;
}
// SAFETY: Making `modern_ctx` current failed; destroy it.
unsafe {
let _ = wglDeleteContext(modern_ctx);
}
}
}
}
let native = Box::new(WglNativeContext {
hwnd,
hdc,
hglrc: active_ctx,
});
let lib =
SystemGlLibrary::load().map_err(|reason| GlError::LibraryLoadFailed { reason })?;
let fns = GlFnTable::load(&mut |name| {
let Ok(cstr) = CString::new(name) else {
return ptr::null();
};
lib.get_proc_address(cstr.as_bytes_with_nul())
})?;
Self::finish_init(fns, desc, Some(SystemLibraryGuard::new(lib)), Some(native))
}
}
}