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
//! Contains everything related to the interface between glium and the OpenGL implementation.

use gl;
use backtrace;

use std::collections::HashMap;
use std::mem;
use std::ptr;
use std::str;
use std::borrow::Cow;
use std::cell::{Cell, RefCell, RefMut};
use std::marker::PhantomData;
use std::ffi::CStr;
use std::rc::Rc;
use std::os::raw;
use std::hash::BuildHasherDefault;

use fnv::FnvHasher;

use IncompatibleOpenGl;
use SwapBuffersError;
use CapabilitiesSource;
use ContextExt;
use backend::Backend;
use version;
use version::Api;
use version::Version;

use debug;
use fbo;
use ops;
use sampler_object;
use texture;
use uniforms;
use vertex_array_object;

pub use self::capabilities::{ReleaseBehavior, Capabilities, Profile};
pub use self::extensions::ExtensionsList;
pub use self::state::GlState;

mod capabilities;
mod extensions;
mod state;

/// Stores the state and information required for glium to execute commands. Most public glium
/// functions require passing a `Rc<Context>`.
pub struct Context {
    /// Contains the pointers to OpenGL functions.
    gl: gl::Gl,

    /// The current state of the OpenGL state machine. Contains for example which buffer is bound
    /// to which bind point, whether depth testing is activated, etc.
    state: RefCell<GlState>,

    /// Version of OpenGL of the backend.
    version: Version,

    /// Tells whether or not the backend supports each extension.
    extensions: ExtensionsList,

    /// Constants defined by the backend and retrieved at initialization. For example, number
    /// of texture units, maximum size of the viewport, etc.
    capabilities: Capabilities,

    /// Glue between glium and the code that handles windowing. Contains functions that allows
    /// you to swap buffers, retrieve the size of the framebuffer, etc.
    backend: RefCell<Box<Backend>>,

    /// Whether or not glium must check that the OpenGL context is the current one before each
    /// call.
    check_current_context: bool,

    /// The callback that is used by the debug output feature.
    debug_callback: Option<debug::DebugCallback>,

    /// Whether or not errors triggered by ARB_debug_output (and similar extensions) should be
    /// reported to the user when `DebugCallbackBehavior::DebugMessageOnError` is used. This must
    /// be set to `false` in some situations, like compiling/linking shaders.
    report_debug_output_errors: Cell<bool>,

    /// We maintain a cache of FBOs.
    /// The `Option` is here in order to destroy the container. It must be filled at all time
    /// is a normal situation.
    framebuffer_objects: Option<fbo::FramebuffersContainer>,

    /// We maintain a list of vertex array objecs.
    vertex_array_objects: vertex_array_object::VertexAttributesSystem,

    /// We maintain a list of samplers for each possible behavior.
    samplers: RefCell<HashMap<uniforms::SamplerBehavior, sampler_object::SamplerObject, BuildHasherDefault<FnvHasher>>>,

    /// List of texture handles that are resident. We need to call `MakeTextureHandleResidentARB`
    /// when rebuilding the context.
    resident_texture_handles: RefCell<Vec<gl::types::GLuint64>>,

    /// List of images handles that are resident. We need to call `MakeImageHandleResidentARB`
    /// when rebuilding the context.
    resident_image_handles: RefCell<Vec<(gl::types::GLuint64, gl::types::GLenum)>>,
}

/// This struct is a guard that is returned when you want to access the OpenGL backend.
pub struct CommandContext<'a> {
    /// Source of OpenGL function pointers.
    pub gl: &'a gl::Gl,

    /// Refers to the state of the OpenGL backend. Maintained between multiple calls.
    /// **Must** be synchronized with the real state of the backend.
    pub state: RefMut<'a, GlState>,

    /// Version of the backend.
    pub version: &'a Version,

    /// Extensions supported by the backend.
    pub extensions: &'a ExtensionsList,

    /// Capabilities of the backend.
    pub capabilities: &'a Capabilities,

    /// Whether or not errors triggered by ARB_debug_output (and similar extensions) should be
    /// reported to the user (by panicking).
    pub report_debug_output_errors: &'a Cell<bool>,

    /// The list of vertex array objects.
    pub vertex_array_objects: &'a vertex_array_object::VertexAttributesSystem,

    /// The list of framebuffer objects.
    pub framebuffer_objects: &'a fbo::FramebuffersContainer,

    /// The list of samplers.
    pub samplers: RefMut<'a, HashMap<uniforms::SamplerBehavior, sampler_object::SamplerObject, BuildHasherDefault<FnvHasher>>>,

    /// List of texture handles that need to be made resident.
    pub resident_texture_handles: RefMut<'a, Vec<gl::types::GLuint64>>,

    /// List of image handles and their access that need to be made resident.
    pub resident_image_handles: RefMut<'a, Vec<(gl::types::GLuint64, gl::types::GLenum)>>,

    /// This marker is here to prevent `CommandContext` from implementing `Send`
    // TODO: use this when possible
    //impl<'a, 'b> !Send for CommandContext<'a, 'b> {}
    marker: PhantomData<*mut u8>,
}

impl Context {
    /// Builds a new context.
    ///
    /// The `check_current_context` parameter tells the context whether it should check
    /// if the backend's OpenGL context is the current one before each OpenGL operation.
    ///
    /// If you pass `false`, you must ensure that no other OpenGL context is going to be made
    /// current in the same thread as this context. Passing `true` makes things safe but
    /// is slightly slower.
    ///
    /// The OpenGL context must be newly-created. If you make modifications to the context before
    /// passing it to this function, glium's state cache may mismatch the actual one.
    ///
    pub unsafe fn new<B>(
        backend: B,
        check_current_context: bool,
        callback_behavior: DebugCallbackBehavior,
    ) -> Result<Rc<Context>, IncompatibleOpenGl>
        where B: Backend + 'static
    {
        backend.make_current();

        let gl = gl::Gl::load_with(|symbol| backend.get_proc_address(symbol) as *const _);
        let gl_state: RefCell<GlState> = RefCell::new(Default::default());

        let version = version::get_gl_version(&gl);
        let extensions = extensions::get_extensions(&gl, &version);
        try!(check_gl_compatibility(&version, &extensions));

        let capabilities = capabilities::get_capabilities(&gl, &version, &extensions);
        let report_debug_output_errors = Cell::new(true);

        let vertex_array_objects = vertex_array_object::VertexAttributesSystem::new();
        let framebuffer_objects = fbo::FramebuffersContainer::new();
        let samplers = RefCell::new({
            let mut map = HashMap::with_hasher(Default::default());
            map.reserve(16);
            map
        });
        let resident_texture_handles = RefCell::new(Vec::new());
        let resident_image_handles = RefCell::new(Vec::new());

        let (debug_callback, synchronous) = match callback_behavior {
            DebugCallbackBehavior::Ignore => (None, false),
            DebugCallbackBehavior::DebugMessageOnError => {
                (Some(Box::new(default_debug_callback) as debug::DebugCallback), true)
            },
            DebugCallbackBehavior::PrintAll => {
                (Some(Box::new(printall_debug_callback) as debug::DebugCallback), false)
            },
            DebugCallbackBehavior::Custom { callback, synchronous } => {
                (Some(callback), synchronous)
            },
        };

        let context = Rc::new(Context {
            gl: gl,
            state: gl_state,
            version: version,
            extensions: extensions,
            capabilities: capabilities,
            debug_callback: debug_callback,
            report_debug_output_errors: report_debug_output_errors,
            backend: RefCell::new(Box::new(backend)),
            check_current_context: check_current_context,
            framebuffer_objects: Some(framebuffer_objects),
            vertex_array_objects: vertex_array_objects,
            samplers: samplers,
            resident_texture_handles: resident_texture_handles,
            resident_image_handles: resident_image_handles,
        });

        if context.debug_callback.is_some() {
            init_debug_callback(&context, synchronous);
        }

        // making sure that an error wasn't triggered during initialization
        {
            let mut ctxt = context.make_current();
            if ::get_gl_error(&mut ctxt).is_some() {
                println!("glium has triggered an OpenGL error during initialization. Please report \
                          this error: https://github.com/tomaka/glium/issues");
            }
            /*assert!(::get_gl_error(&mut ctxt).is_none(),
                    "glium has triggered an OpenGL error during initialization. Please report \
                     this error: https://github.com/tomaka/glium/issues");*/
        }

        Ok(context)
    }

    /// Calls `get_framebuffer_dimensions` on the backend object stored by this context.
    #[inline]
    pub fn get_framebuffer_dimensions(&self) -> (u32, u32) {
        self.backend.borrow().get_framebuffer_dimensions()
    }

    /// Changes the OpenGL context associated with this context.
    ///
    /// The new context **must** have lists shared with the old one.
    pub unsafe fn rebuild<B>(&self, new_backend: B) -> Result<(), IncompatibleOpenGl>
        where B: Backend + 'static
    {
        // framebuffer objects and vertex array objects aren't shared,
        // so we have to destroy them
        {
            let mut ctxt = self.make_current();
            fbo::FramebuffersContainer::purge_all(&mut ctxt);
            vertex_array_object::VertexAttributesSystem::purge_all(&mut ctxt);
        }

        new_backend.make_current();

        *self.state.borrow_mut() = Default::default();
        // FIXME: verify version, capabilities and extensions
        *self.backend.borrow_mut() = Box::new(new_backend);

        // making textures resident
        let textures = self.resident_texture_handles.borrow();
        for &texture in textures.iter() {
            self.gl.MakeTextureHandleResidentARB(texture);
        }

        // making images resident
        let images = self.resident_image_handles.borrow();
        for &(image, access) in images.iter() {
            self.gl.MakeImageHandleResidentARB(image, access);
        }

        Ok(())
    }

    /// Swaps the buffers in the backend.
    pub fn swap_buffers(&self) -> Result<(), SwapBuffersError> {
        if self.state.borrow().lost_context {
            return Err(SwapBuffersError::ContextLost);
        }

        // Note: This is a work-around for the FRAPS software.
        //       The Fraps software calls `glClear` with scissoring and reads the image of the
        //       current framebuffer.
        //       Therefore we need to bind the default framebuffer before swapping.
        if self.state.borrow().draw_framebuffer != 0 || self.state.borrow().read_framebuffer != 0 {
            let mut ctxt = self.make_current();

            if ctxt.version >= &Version(Api::Gl, 3, 0) ||
               ctxt.extensions.gl_arb_framebuffer_object
            {
                unsafe { ctxt.gl.BindFramebuffer(gl::FRAMEBUFFER, 0); }
                ctxt.state.draw_framebuffer = 0;
                ctxt.state.read_framebuffer = 0;
            } else if ctxt.version >= &Version(Api::GlEs, 2, 0) {
                unsafe { ctxt.gl.BindFramebuffer(gl::FRAMEBUFFER, 0); }
                ctxt.state.draw_framebuffer = 0;
                ctxt.state.read_framebuffer = 0;
            } else if ctxt.extensions.gl_ext_framebuffer_object {
                unsafe { ctxt.gl.BindFramebufferEXT(gl::FRAMEBUFFER_EXT, 0); }
                ctxt.state.draw_framebuffer = 0;
                ctxt.state.read_framebuffer = 0;
            } else {
                unreachable!();
            }
        }

        let backend = self.backend.borrow();
        if self.check_current_context {
            if !backend.is_current() {
                unsafe { backend.make_current() };
            }
        }

        // swapping
        let err = backend.swap_buffers();
        if let Err(SwapBuffersError::ContextLost) = err {
            self.state.borrow_mut().lost_context = true;
        }
        err
    }

    /// DEPRECATED. Use `get_opengl_version` instead.
    #[inline]
    pub fn get_version(&self) -> &Version {
        &self.version
    }

    /// Returns the OpenGL version detected by this context.
    #[inline]
    pub fn get_opengl_version(&self) -> &Version {
        &self.version
    }

    /// Returns the GLSL version guaranteed to be supported.
    #[inline]
    pub fn get_supported_glsl_version(&self) -> Version {
        version::get_supported_glsl_version(self.get_version())
    }

    /// Returns true if the given GLSL version is supported.
    #[inline]
    pub fn is_glsl_version_supported(&self, version: &Version) -> bool {
        self.capabilities().supported_glsl_versions.iter().find(|&v| v == version).is_some()
    }

    /// Returns a string containing this GL version or release number used by this context.
    ///
    /// Vendor-specific information may follow the version number.
    #[inline]
    pub fn get_opengl_version_string(&self) -> &str {
        &self.capabilities().version
    }

    /// Returns a string containing the company responsible for this GL implementation.
    #[inline]
    pub fn get_opengl_vendor_string(&self) -> &str {
        &self.capabilities().vendor
    }

    /// Returns a string containing the name of the GL renderer used by this context.
    ///
    /// This name is typically specific to a particular configuration of a hardware platform.
    #[inline]
    pub fn get_opengl_renderer_string(&self) -> &str {
        &self.capabilities().renderer
    }

    /// Returns true if the context is in debug mode.
    ///
    /// Debug mode may provide additional error and performance issue reporting functionality.
    #[inline]
    pub fn is_debug(&self) -> bool {
        self.capabilities().debug
    }

    /// Returns true if the context is in "forward-compatible" mode.
    ///
    /// Forward-compatible mode means that no deprecated functionality will be supported.
    #[inline]
    pub fn is_forward_compatible(&self) -> bool {
        self.capabilities().forward_compatible
    }

    /// Returns this context's OpenGL profile if available.
    ///
    /// The context profile is available from OpenGL 3.2 onwards. Returns `None` if not supported.
    pub fn get_opengl_profile(&self) -> Option<Profile> {
        self.capabilities().profile
    }

    /// Returns true if out-of-bound buffer access from the GPU side (inside a program) cannot
    /// result in a crash.
    ///
    /// You should take extra care if `is_robust` returns false.
    #[inline]
    pub fn is_robust(&self) -> bool {
        self.capabilities().robustness
    }

    /// Returns true if a context loss is possible.
    #[inline]
    pub fn is_context_loss_possible(&self) -> bool {
        self.capabilities().can_lose_context
    }

    /// Returns true if the context has been lost and needs to be recreated.
    ///
    /// # Implementation
    ///
    /// If it has been determined that the context has been lost before, then the function
    /// immediatly returns true. Otherwise, calls `glGetGraphicsResetStatus`. If this function
    /// is not available, returns false.
    pub fn is_context_lost(&self) -> bool {
        if self.state.borrow().lost_context {
            return true;
        }

        let mut ctxt = self.make_current();

        let lost = if ctxt.version >= &Version(Api::Gl, 4, 5) ||
                      ctxt.version >= &Version(Api::GlEs, 3, 2) ||
                      ctxt.extensions.gl_khr_robustness
        {
            unsafe { ctxt.gl.GetGraphicsResetStatus() != gl::NO_ERROR }
        } else if ctxt.extensions.gl_ext_robustness {
            unsafe { ctxt.gl.GetGraphicsResetStatusEXT() != gl::NO_ERROR }
        } else if ctxt.extensions.gl_arb_robustness {
            unsafe { ctxt.gl.GetGraphicsResetStatusARB() != gl::NO_ERROR }
        } else {
            false
        };

        if lost { ctxt.state.lost_context = true; }
        lost
    }

    /// Returns the behavior when the current OpenGL context is changed.
    ///
    /// The most common value is `Flush`. In order to get `None` you must explicitely request it
    /// during creation.
    #[inline]
    pub fn get_release_behavior(&self) -> ReleaseBehavior {
        self.capabilities().release_behavior
    }

    /// Returns the maximum value that can be used for anisotropic filtering, or `None`
    /// if the hardware doesn't support it.
    #[inline]
    pub fn get_max_anisotropy_support(&self) -> Option<u16> {
        self.capabilities().max_texture_max_anisotropy.map(|v| v as u16)
    }

    /// Returns the maximum dimensions of the viewport.
    ///
    /// Glium will panic if you request a larger viewport than this when drawing.
    #[inline]
    pub fn get_max_viewport_dimensions(&self) -> (u32, u32) {
        let d = self.capabilities().max_viewport_dims;
        (d.0 as u32, d.1 as u32)
    }

    /// Releases the shader compiler, indicating that no new programs will be created for a while.
    ///
    /// This method is a no-op if it's not available in the implementation.
    pub fn release_shader_compiler(&self) {
        unsafe {
            let ctxt = self.make_current();

            if ctxt.version >= &Version(Api::GlEs, 2, 0) ||
                ctxt.version >= &Version(Api::Gl, 4, 1)
            {
                if !ctxt.capabilities.supported_glsl_versions.is_empty() {
                    ctxt.gl.ReleaseShaderCompiler();
                }
            }
        }
    }

    /// Returns an estimate of the amount of video memory available in bytes.
    ///
    /// Returns `None` if no estimate is available.
    pub fn get_free_video_memory(&self) -> Option<usize> {
        unsafe {
            let ctxt = self.make_current();

            let mut value: [gl::types::GLint; 4] = mem::uninitialized();

            if ctxt.extensions.gl_nvx_gpu_memory_info {
                ctxt.gl.GetIntegerv(gl::GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX,
                               &mut value[0]);
                Some(value[0] as usize * 1024)

            } else if ctxt.extensions.gl_ati_meminfo {
                ctxt.gl.GetIntegerv(gl::TEXTURE_FREE_MEMORY_ATI, &mut value[0]);
                Some(value[0] as usize * 1024)

            } else {
                return None;
            }
        }
    }

    /// Reads the content of the front buffer.
    ///
    /// You will only see the data that has finished being drawn.
    ///
    /// This function can return any type that implements `Texture2dDataSink<(u8, u8, u8, u8)>`.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # extern crate glium;
    /// # extern crate glutin;
    /// # fn main() {
    /// # let display: glium::Display = unsafe { ::std::mem::uninitialized() };
    /// let pixels: Vec<Vec<(u8, u8, u8, u8)>> = display.read_front_buffer();
    /// # }
    /// ```
    pub fn read_front_buffer<T>(&self) -> T
                                where T: texture::Texture2dDataSink<(u8, u8, u8, u8)>
    {
        let mut ctxt = self.make_current();
        let dimensions = self.get_framebuffer_dimensions();
        let rect = ::Rect { left: 0, bottom: 0, width: dimensions.0, height: dimensions.1 };

        let mut data = Vec::with_capacity(0);
        ops::read(&mut ctxt, ops::Source::DefaultFramebuffer(gl::FRONT_LEFT), &rect,
                          &mut data, false);
        T::from_raw(Cow::Owned(data), dimensions.0, dimensions.1)
    }

    /// Execute an arbitrary closure with the OpenGL context active. Useful if another
    /// component needs to directly manipulate OpenGL state.
    ///
    /// **If `action` manipulates any OpenGL state, it must be restored before `action`
    /// completes.**
    #[inline]
    pub unsafe fn exec_in_context<'a, T, F>(&self, action: F) -> T
                                            where T: Send + 'static,
                                            F: FnOnce() -> T + 'a
    {
        let _ctxt = self.make_current();
        action()
    }

    /// Asserts that there are no OpenGL errors pending.
    ///
    /// This function should be used in tests.
    pub fn assert_no_error(&self, user_msg: Option<&str>) {
        let mut ctxt = self.make_current();

        match (::get_gl_error(&mut ctxt), user_msg) {
            (Some(msg), None) => panic!("{}", msg),
            (Some(msg), Some(user_msg)) => panic!("{} : {}", user_msg, msg),
            (None, _) => ()
        };
    }

    /// DEPRECATED. Renamed `finish`.
    #[inline]
    pub fn synchronize(&self) {
        self.finish();
    }

    /// Calls `glFinish()`. This waits until all the previously issued commands have finished
    /// being executed.
    ///
    /// When you execute OpenGL functions, they are not executed immediately. Instead they are
    /// put in a queue. This function flushes this queue, then waits until all commands
    /// have finished being executed.
    ///
    /// You normally don't need to call this function manually, except for debugging purposes.
    #[inline]
    pub fn finish(&self) {
        let ctxt = self.make_current();
        unsafe { ctxt.gl.Finish(); }
    }

    /// Calls `glFlush()`. This starts executing the commands that you have issued if it is not
    /// yet the case.
    ///
    /// When you execute OpenGL functions, they are not executed immediately. Instead they are
    /// put in a queue. This function flushes this queue so that commands start being executed.
    ///
    /// You normally don't need to call this function manually. Swapping buffers automatically
    /// flushes the queue. This function can be useful if you want to benchmark the time it
    /// takes from your OpenGL driver to process commands.
    #[inline]
    pub fn flush(&self) {
        let ctxt = self.make_current();
        unsafe { ctxt.gl.Flush(); }
    }

    /// Inserts a debugging string in the commands queue. If you use an OpenGL debugger, you will
    /// be able to see that string.
    ///
    /// This is helpful to understand where you are when you have big applications.
    ///
    /// Returns `Err` if the backend doesn't support this functionnality. You can choose whether
    /// to call `.unwrap()` if you want to make sure that it works, or `.ok()` if you don't care.
    pub fn insert_debug_marker(&self, marker: &str) -> Result<(), ()> {
        let ctxt = self.make_current();

        if ctxt.extensions.gl_gremedy_string_marker {
            let marker = marker.as_bytes();
            unsafe { ctxt.gl.StringMarkerGREMEDY(marker.len() as gl::types::GLsizei,
                                                 marker.as_ptr() as *const _) };
            Ok(())

        } else if ctxt.extensions.gl_ext_debug_marker {
            let marker = marker.as_bytes();
            unsafe { ctxt.gl.InsertEventMarkerEXT(marker.len() as gl::types::GLsizei,
                                                  marker.as_ptr() as *const _) };
            Ok(())

        } else {
            Err(())
        }
    }

    /// Same as `insert_debug_marker`, except that if you don't compile with `debug_assertions`
    /// it is a no-op and returns `Ok`.
    #[inline]
    pub fn debug_insert_debug_marker(&self, marker: &str) -> Result<(), ()> {
        if cfg!(debug_assertions) {
            self.insert_debug_marker(marker)
        } else {
            Ok(())
        }
    }
}

impl ContextExt for Context {
    #[inline]
    fn set_report_debug_output_errors(&self, value: bool) {
        self.report_debug_output_errors.set(value);
    }

    fn make_current(&self) -> CommandContext {
        if self.check_current_context {
            let backend = self.backend.borrow();
            if !backend.is_current() {
                unsafe { backend.make_current() };
                debug_assert!(backend.is_current());
            }
        }

        CommandContext {
            gl: &self.gl,
            state: self.state.borrow_mut(),
            version: &self.version,
            extensions: &self.extensions,
            capabilities: &self.capabilities,
            report_debug_output_errors: &self.report_debug_output_errors,
            vertex_array_objects: &self.vertex_array_objects,
            framebuffer_objects: self.framebuffer_objects.as_ref().unwrap(),
            samplers: self.samplers.borrow_mut(),
            resident_texture_handles: self.resident_texture_handles.borrow_mut(),
            resident_image_handles: self.resident_image_handles.borrow_mut(),
            marker: PhantomData,
        }
    }

    #[inline]
    fn capabilities(&self) -> &Capabilities {
        &self.capabilities
    }
}

impl CapabilitiesSource for Context {
    #[inline]
    fn get_version(&self) -> &Version {
        &self.version
    }

    #[inline]
    fn get_extensions(&self) -> &ExtensionsList {
        &self.extensions
    }

    #[inline]
    fn get_capabilities(&self) -> &Capabilities {
        &self.capabilities
    }
}

impl Drop for Context {
    fn drop(&mut self) {
        unsafe {
            // this is the code of make_current duplicated here because we can't borrow
            // `self` twice
            if self.check_current_context {
                let backend = self.backend.borrow();
                if !backend.is_current() {
                    backend.make_current();
                }
            }

            let mut ctxt = CommandContext {
                gl: &self.gl,
                state: self.state.borrow_mut(),
                version: &self.version,
                extensions: &self.extensions,
                capabilities: &self.capabilities,
                report_debug_output_errors: &self.report_debug_output_errors,
                vertex_array_objects: &self.vertex_array_objects,
                framebuffer_objects: self.framebuffer_objects.as_ref().unwrap(),
                samplers: self.samplers.borrow_mut(),
                resident_texture_handles: self.resident_texture_handles.borrow_mut(),
                resident_image_handles: self.resident_image_handles.borrow_mut(),
                marker: PhantomData,
            };

            fbo::FramebuffersContainer::cleanup(&mut ctxt);
            vertex_array_object::VertexAttributesSystem::cleanup(&mut ctxt);

            for (_, s) in mem::replace(&mut *ctxt.samplers, HashMap::with_hasher(Default::default())) {
                s.destroy(&mut ctxt);
            }

            // disabling callback
            if ctxt.state.enabled_debug_output != Some(false) {
                if ctxt.version >= &Version(Api::Gl, 4,5) || ctxt.extensions.gl_khr_debug {
                    ctxt.gl.Disable(gl::DEBUG_OUTPUT);
                } else if ctxt.extensions.gl_arb_debug_output {
                    ctxt.gl.DebugMessageCallbackARB(mem::transmute(0usize),
                                                    ptr::null());
                }

                ctxt.state.enabled_debug_output = Some(false);
                ctxt.gl.Finish();
            }
        }
    }
}

impl<'a> CapabilitiesSource for CommandContext<'a> {
    #[inline]
    fn get_version(&self) -> &Version {
        self.version
    }

    #[inline]
    fn get_extensions(&self) -> &ExtensionsList {
        self.extensions
    }

    #[inline]
    fn get_capabilities(&self) -> &Capabilities {
        self.capabilities
    }
}

/// Checks whether the backend supports glium. Returns an `Err` if it doesn't.
fn check_gl_compatibility(version: &Version, extensions: &ExtensionsList)
    -> Result<(), IncompatibleOpenGl>
{
    let mut result = Vec::with_capacity(0);

    if !(version >= &Version(Api::Gl, 1, 5)) &&
        !(version >= &Version(Api::GlEs, 2, 0)) &&
        (!extensions.gl_arb_vertex_buffer_object || !extensions.gl_arb_map_buffer_range)
    {
        result.push("OpenGL implementation doesn't support buffer objects");
    }

    if !(version >= &Version(Api::Gl, 2, 0)) &&
        !(version >= &Version(Api::GlEs, 2, 0)) &&
        (!extensions.gl_arb_shader_objects ||
            !extensions.gl_arb_vertex_shader || !extensions.gl_arb_fragment_shader)
    {
        result.push("OpenGL implementation doesn't support vertex/fragment shaders");
    }

    if !extensions.gl_ext_framebuffer_object && !(version >= &Version(Api::Gl, 3, 0)) &&
        !(version >= &Version(Api::GlEs, 2, 0)) && !extensions.gl_arb_framebuffer_object
    {
        result.push("OpenGL implementation doesn't support framebuffers");
    }

    if !extensions.gl_ext_framebuffer_blit && !(version >= &Version(Api::Gl, 3, 0)) &&
        !(version >= &Version(Api::GlEs, 2, 0))
    {
        result.push("OpenGL implementation doesn't support blitting framebuffers");
    }

    if result.len() == 0 {
        Ok(())
    } else {
        Err(IncompatibleOpenGl(result.join("\n")))
    }
}

/// Describes the behavior that the debug output should have.
pub enum DebugCallbackBehavior {
    /// Don't do anything. This is the default behavior in release.
    Ignore,

    /// Print a message on stdout on error, except in some circumstances like when compiling
    /// shaders. This is the default behavior in debug mode.
    DebugMessageOnError,

    /// Print every single output received by the driver.
    PrintAll,

    /// Use a custom callback.
    Custom {
        /// The function to be called.
        callback: debug::DebugCallback,
        /// Whether or not it should be called immediately (true) or asynchronously (false).
        synchronous: bool,
    },
}

impl Default for DebugCallbackBehavior {
    #[inline]
    fn default() -> DebugCallbackBehavior {
        if cfg!(debug_assertions) {
            DebugCallbackBehavior::DebugMessageOnError
        } else {
            DebugCallbackBehavior::Ignore
        }
    }
}

/// The callback corresponding to `DebugMessageOnError`.
fn default_debug_callback(_: debug::Source, ty: debug::MessageType, severity: debug::Severity,
                          _: u32, report_debug_output_errors: bool, message: &str)
{
    match severity {
        debug::Severity::Medium => (),
        debug::Severity::High => (),
        _ => return
    };

    match ty {
        debug::MessageType::Error => (),
        debug::MessageType::DeprecatedBehavior => (),
        debug::MessageType::UndefinedBehavior => (),
        debug::MessageType::Portability => (),
        _ => return,
    };

    if report_debug_output_errors {
        print!("Debug message with high or medium severity: `{}`.\n\
                Please report this error: https://github.com/tomaka/glium/issues\n\
                Backtrace:",
                message);

        let mut frame_id = 1;
        backtrace::trace(|frame| {
            let ip = frame.ip();
            print!("\n{:>#4} - {:p}", frame_id, ip);

            backtrace::resolve(ip, |symbol| {
                let name = symbol.name()
                                 .map(|n| n.as_str().unwrap_or("<not-utf8>"))
                                 .unwrap_or("<unknown>");
                let filename = symbol.filename()
                                     .map(|p| p.to_str().unwrap_or("<not-utf8>"))
                                     .unwrap_or("<unknown>");
                let line = symbol.lineno().map(|l| l.to_string())
                                          .unwrap_or_else(|| "??".to_owned());

                print!("\n         {} at {}:{}", name, filename, line);
            });

            frame_id += 1;
            true
        });

        println!("\n");
    }
}

/// The callback corresponding to `DebugMessageOnError`.
fn printall_debug_callback(source: debug::Source, ty: debug::MessageType, severity: debug::Severity,
                           id: u32, _: bool, message: &str)
{
    println!("Source: {src:?}\t\tSeverity: {sev:?}\t\tType: {ty:?}\t\tId: {id}\n{msg}",
              src = source, sev = severity, ty = ty, id = id, msg = message);
}

/// Initializes `GL_KHR_debug`, `GL_ARB_debug`, or a similar extension so that the debug output
/// is reported.
fn init_debug_callback(context: &Rc<Context>, synchronous: bool) {
    // this is the C callback
    extern "system" fn callback_wrapper(source: gl::types::GLenum, ty: gl::types::GLenum,
                                        id: gl::types::GLuint, severity: gl::types::GLenum,
                                        _length: gl::types::GLsizei,
                                        message: *const gl::types::GLchar,
                                        user_param: *mut raw::c_void)
    {
        // note that we transmute the user param into a proper context
        // in order to enforce safety here, the context disables debug output and flushes in its
        // destructor

        let user_param = user_param as *const Context;
        let user_param: &mut Context = unsafe { mem::transmute(user_param) };

        let message = unsafe {
            String::from_utf8(CStr::from_ptr(message).to_bytes().to_vec()).unwrap()
        };

        let severity = match severity {
            gl::DEBUG_SEVERITY_NOTIFICATION => debug::Severity::Notification,
            gl::DEBUG_SEVERITY_LOW => debug::Severity::Low,
            gl::DEBUG_SEVERITY_MEDIUM => debug::Severity::Medium,
            gl::DEBUG_SEVERITY_HIGH => debug::Severity::High,
            _ => return,        // TODO: what to do in this situation?
        };

        let source = match source {
            gl::DEBUG_SOURCE_API => debug::Source::Api,
            gl::DEBUG_SOURCE_WINDOW_SYSTEM => debug::Source::WindowSystem,
            gl::DEBUG_SOURCE_SHADER_COMPILER => debug::Source::ShaderCompiler,
            gl::DEBUG_SOURCE_THIRD_PARTY => debug::Source::ThirdParty,
            gl::DEBUG_SOURCE_APPLICATION => debug::Source::Application,
            gl::DEBUG_SOURCE_OTHER => debug::Source::OtherSource,
            _ => return,        // TODO: what to do in this situation?
        };

        let ty = match ty {
            gl::DEBUG_TYPE_ERROR => debug::MessageType::Error,
            gl::DEBUG_TYPE_DEPRECATED_BEHAVIOR => debug::MessageType::DeprecatedBehavior,
            gl::DEBUG_TYPE_UNDEFINED_BEHAVIOR => debug::MessageType::UndefinedBehavior,
            gl::DEBUG_TYPE_PORTABILITY => debug::MessageType::Portability,
            gl::DEBUG_TYPE_PERFORMANCE => debug::MessageType::Performance,
            gl::DEBUG_TYPE_MARKER => debug::MessageType::Marker,
            gl::DEBUG_TYPE_PUSH_GROUP => debug::MessageType::PushGroup,
            gl::DEBUG_TYPE_POP_GROUP => debug::MessageType::PopGroup,
            gl::DEBUG_TYPE_OTHER => debug::MessageType::Other,
            _ => return,        // TODO: what to do in this situation?
        };

        if let Some(callback) = user_param.debug_callback.as_mut() {
            // FIXME: catch_panic here once it's stable
            callback(source, ty, severity, id, user_param.report_debug_output_errors.get(),
                     &message);
        }
    }

    struct ContextRawPtr(*const Context);
    unsafe impl Send for ContextRawPtr {}
    let context_raw_ptr = ContextRawPtr(&**context);

    unsafe {
        let mut ctxt = context.make_current();

        if ctxt.version >= &Version(Api::Gl, 4,5) || ctxt.version >= &Version(Api::GlEs, 3, 2) ||
           ctxt.extensions.gl_khr_debug || ctxt.extensions.gl_arb_debug_output
        {
            if synchronous {
                if ctxt.state.enabled_debug_output_synchronous != true {
                    ctxt.gl.Enable(gl::DEBUG_OUTPUT_SYNCHRONOUS);
                    ctxt.state.enabled_debug_output_synchronous = true;
                }
            }

            if ctxt.version >= &Version(Api::Gl, 4, 5) ||
               ctxt.version >= &Version(Api::GlEs, 3, 2) ||
               (ctxt.version >= &Version(Api::Gl, 1, 0) && ctxt.extensions.gl_khr_debug)
            {
                ctxt.gl.DebugMessageCallback(callback_wrapper, context_raw_ptr.0
                                                                 as *const _);
                ctxt.gl.DebugMessageControl(gl::DONT_CARE, gl::DONT_CARE, gl::DONT_CARE, 0,
                                            ptr::null(), gl::TRUE);

                if ctxt.state.enabled_debug_output != Some(true) {
                    ctxt.gl.Enable(gl::DEBUG_OUTPUT);
                    ctxt.state.enabled_debug_output = Some(true);
                }

            } else if ctxt.version >= &Version(Api::GlEs, 2, 0) &&
                      ctxt.extensions.gl_khr_debug
            {
                ctxt.gl.DebugMessageCallbackKHR(callback_wrapper, context_raw_ptr.0
                                                                 as *const _);
                ctxt.gl.DebugMessageControlKHR(gl::DONT_CARE, gl::DONT_CARE, gl::DONT_CARE, 0,
                                               ptr::null(), gl::TRUE);

                if ctxt.state.enabled_debug_output != Some(true) {
                    ctxt.gl.Enable(gl::DEBUG_OUTPUT);
                    ctxt.state.enabled_debug_output = Some(true);
                }

            } else {
                ctxt.gl.DebugMessageCallbackARB(callback_wrapper, context_raw_ptr.0
                                                                    as *const _);
                ctxt.gl.DebugMessageControlARB(gl::DONT_CARE, gl::DONT_CARE, gl::DONT_CARE,
                                               0, ptr::null(), gl::TRUE);

                ctxt.state.enabled_debug_output = Some(true);
            }
        }
    }
}