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
// surfman/surfman/src/platform/generic/multi/context.rs
//
//! A context abstraction that allows the choice of backends dynamically.

use super::device::Device;
use super::surface::Surface;
use crate::device::Device as DeviceInterface;
use crate::{ContextAttributes, ContextID, Error, SurfaceInfo};

use std::os::raw::c_void;

/// Represents an OpenGL rendering context.
///
/// A context allows you to issue rendering commands to a surface. When initially created, a
/// context has no attached surface, so rendering commands will fail or be ignored. Typically, you
/// attach a surface to the context before rendering.
///
/// Contexts take ownership of the surfaces attached to them. In order to mutate a surface in any
/// way other than rendering to it (e.g. presenting it to a window, which causes a buffer swap), it
/// must first be detached from its context. Each surface is associated with a single context upon
/// creation and may not be rendered to from any other context. However, you can wrap a surface in
/// a surface texture, which allows the surface to be read from another context.
///
/// OpenGL objects may not be shared across contexts directly, but surface textures effectively
/// allow for sharing of texture data. Contexts are local to a single thread and device.
///
/// A context must be explicitly destroyed with `destroy_context()`, or a panic will occur.
pub enum Context<Def, Alt>
where
    Def: DeviceInterface,
    Alt: DeviceInterface,
{
    /// The default rendering context type.
    Default(Def::Context),
    /// The alternate rendering context type.
    Alternate(Alt::Context),
}

/// Information needed to create a context. Some APIs call this a "config" or a "pixel format".
///
/// These are local to a device.
#[derive(Clone)]
pub enum ContextDescriptor<Def, Alt>
where
    Def: DeviceInterface,
    Alt: DeviceInterface,
{
    /// The default context descriptor type.
    Default(Def::ContextDescriptor),
    /// The alternate context descriptor type.
    Alternate(Alt::ContextDescriptor),
}

/// Wraps a platform-specific native context.
pub enum NativeContext<Def, Alt>
where
    Def: DeviceInterface,
    Alt: DeviceInterface,
{
    /// The default context type.
    Default(Def::NativeContext),
    /// The alternate context type.
    Alternate(Alt::NativeContext),
}

impl<Def, Alt> Device<Def, Alt>
where
    Def: DeviceInterface,
    Alt: DeviceInterface,
{
    /// Creates a context descriptor with the given attributes.
    ///
    /// Context descriptors are local to this device.
    pub fn create_context_descriptor(
        &self,
        attributes: &ContextAttributes,
    ) -> Result<ContextDescriptor<Def, Alt>, Error> {
        match *self {
            Device::Default(ref device) => device
                .create_context_descriptor(attributes)
                .map(ContextDescriptor::Default),
            Device::Alternate(ref device) => device
                .create_context_descriptor(attributes)
                .map(ContextDescriptor::Alternate),
        }
    }

    /// Creates a new OpenGL context.
    ///
    /// The context initially has no surface attached. Until a surface is bound to it, rendering
    /// commands will fail or have no effect.
    pub fn create_context(
        &mut self,
        descriptor: &ContextDescriptor<Def, Alt>,
        share_with: Option<&Context<Def, Alt>>,
    ) -> Result<Context<Def, Alt>, Error> {
        match (&mut *self, descriptor) {
            (&mut Device::Default(ref mut device), &ContextDescriptor::Default(ref descriptor)) => {
                let shared = match share_with {
                    Some(&Context::Default(ref other)) => Some(other),
                    Some(_) => {
                        return Err(Error::IncompatibleSharedContext);
                    }
                    None => None,
                };
                device
                    .create_context(descriptor, shared)
                    .map(Context::Default)
            }
            (
                &mut Device::Alternate(ref mut device),
                &ContextDescriptor::Alternate(ref descriptor),
            ) => {
                let shared = match share_with {
                    Some(&Context::Alternate(ref other)) => Some(other),
                    Some(_) => {
                        return Err(Error::IncompatibleSharedContext);
                    }
                    None => None,
                };
                device
                    .create_context(descriptor, shared)
                    .map(Context::Alternate)
            }
            _ => Err(Error::IncompatibleContextDescriptor),
        }
    }

    /// Wraps an existing native context in a `Context` object.
    pub unsafe fn create_context_from_native_context(
        &self,
        native_context: NativeContext<Def, Alt>,
    ) -> Result<Context<Def, Alt>, Error> {
        match self {
            &Device::Default(ref device) => match native_context {
                NativeContext::Default(native_context) => device
                    .create_context_from_native_context(native_context)
                    .map(Context::Default),
                _ => Err(Error::IncompatibleNativeContext),
            },
            &Device::Alternate(ref device) => match native_context {
                NativeContext::Alternate(native_context) => device
                    .create_context_from_native_context(native_context)
                    .map(Context::Alternate),
                _ => Err(Error::IncompatibleNativeContext),
            },
        }
    }

    /// Destroys a context.
    ///
    /// The context must have been created on this device.
    pub fn destroy_context(&self, context: &mut Context<Def, Alt>) -> Result<(), Error> {
        match (self, &mut *context) {
            (&Device::Default(ref device), &mut Context::Default(ref mut context)) => {
                device.destroy_context(context)
            }
            (&Device::Alternate(ref device), &mut Context::Alternate(ref mut context)) => {
                device.destroy_context(context)
            }
            _ => Err(Error::IncompatibleContext),
        }
    }

    /// Returns the native context underlying this context.
    pub fn native_context(&self, context: &Context<Def, Alt>) -> NativeContext<Def, Alt> {
        match (self, context) {
            (&Device::Default(ref device), &Context::Default(ref context)) => {
                NativeContext::Default(device.native_context(context))
            }
            (&Device::Alternate(ref device), &Context::Alternate(ref context)) => {
                NativeContext::Alternate(device.native_context(context))
            }
            _ => panic!("Incompatible context!"),
        }
    }

    /// Returns the descriptor that this context was created with.
    pub fn context_descriptor(&self, context: &Context<Def, Alt>) -> ContextDescriptor<Def, Alt> {
        match (self, context) {
            (&Device::Default(ref device), &Context::Default(ref context)) => {
                ContextDescriptor::Default(device.context_descriptor(context))
            }
            (&Device::Alternate(ref device), &Context::Alternate(ref context)) => {
                ContextDescriptor::Alternate(device.context_descriptor(context))
            }
            _ => panic!("Incompatible context!"),
        }
    }

    /// Makes the context the current OpenGL context for this thread.
    ///
    /// After calling this function, it is valid to use OpenGL rendering commands.
    pub fn make_context_current(&self, context: &Context<Def, Alt>) -> Result<(), Error> {
        match (self, context) {
            (&Device::Default(ref device), &Context::Default(ref context)) => {
                device.make_context_current(context)
            }
            (&Device::Alternate(ref device), &Context::Alternate(ref context)) => {
                device.make_context_current(context)
            }
            _ => Err(Error::IncompatibleContext),
        }
    }

    /// Removes the current OpenGL context from this thread.
    ///
    /// After calling this function, OpenGL rendering commands will fail until a new context is
    /// made current.
    pub fn make_no_context_current(&self) -> Result<(), Error> {
        match self {
            &Device::Default(ref device) => device.make_no_context_current(),
            &Device::Alternate(ref device) => device.make_no_context_current(),
        }
    }

    /// Attaches a surface to a context for rendering.
    ///
    /// This function takes ownership of the surface. The surface must have been created with this
    /// context, or an `IncompatibleSurface` error is returned.
    ///
    /// If this function is called with a surface already bound, a `SurfaceAlreadyBound` error is
    /// returned. To avoid this error, first unbind the existing surface with
    /// `unbind_surface_from_context`.
    ///
    /// If an error is returned, the surface is returned alongside it.
    pub fn bind_surface_to_context(
        &self,
        context: &mut Context<Def, Alt>,
        surface: Surface<Def, Alt>,
    ) -> Result<(), (Error, Surface<Def, Alt>)> {
        match (self, &mut *context) {
            (&Device::Default(ref device), &mut Context::Default(ref mut context)) => match surface
            {
                Surface::Default(surface) => device
                    .bind_surface_to_context(context, surface)
                    .map_err(|(err, surface)| (err, Surface::Default(surface))),
                _ => Err((Error::IncompatibleSurface, surface)),
            },
            (&Device::Alternate(ref device), &mut Context::Alternate(ref mut context)) => {
                match surface {
                    Surface::Alternate(surface) => device
                        .bind_surface_to_context(context, surface)
                        .map_err(|(err, surface)| (err, Surface::Alternate(surface))),
                    _ => Err((Error::IncompatibleSurface, surface)),
                }
            }
            _ => Err((Error::IncompatibleContext, surface)),
        }
    }

    /// Removes and returns any attached surface from this context.
    ///
    /// Any pending OpenGL commands targeting this surface will be automatically flushed, so the
    /// surface is safe to read from immediately when this function returns.
    pub fn unbind_surface_from_context(
        &self,
        context: &mut Context<Def, Alt>,
    ) -> Result<Option<Surface<Def, Alt>>, Error> {
        match (self, &mut *context) {
            (&Device::Default(ref device), &mut Context::Default(ref mut context)) => device
                .unbind_surface_from_context(context)
                .map(|surface| surface.map(Surface::Default)),
            (&Device::Alternate(ref device), &mut Context::Alternate(ref mut context)) => device
                .unbind_surface_from_context(context)
                .map(|surface| surface.map(Surface::Alternate)),
            _ => Err(Error::IncompatibleContext),
        }
    }

    /// Returns the attributes that the context descriptor was created with.
    pub fn context_descriptor_attributes(
        &self,
        context_descriptor: &ContextDescriptor<Def, Alt>,
    ) -> ContextAttributes {
        match (self, context_descriptor) {
            (&Device::Default(ref device), &ContextDescriptor::Default(ref context_descriptor)) => {
                device.context_descriptor_attributes(context_descriptor)
            }
            (
                &Device::Alternate(ref device),
                &ContextDescriptor::Alternate(ref context_descriptor),
            ) => device.context_descriptor_attributes(context_descriptor),
            _ => panic!("Incompatible context!"),
        }
    }

    /// Fetches the address of an OpenGL function associated with this context.
    ///
    /// OpenGL functions are local to a context. You should not use OpenGL functions on one context
    /// with any other context.
    ///
    /// This method is typically used with a function like `gl::load_with()` from the `gl` crate to
    /// load OpenGL function pointers.
    pub fn get_proc_address(
        &self,
        context: &Context<Def, Alt>,
        symbol_name: &str,
    ) -> *const c_void {
        match (self, context) {
            (&Device::Default(ref device), &Context::Default(ref context)) => {
                device.get_proc_address(context, symbol_name)
            }
            (&Device::Alternate(ref device), &Context::Alternate(ref context)) => {
                device.get_proc_address(context, symbol_name)
            }
            _ => panic!("Incompatible context!"),
        }
    }

    /// Returns a unique ID representing a context.
    ///
    /// This ID is unique to all currently-allocated contexts. If you destroy a context and create
    /// a new one, the new context might have the same ID as the destroyed one.
    pub fn context_id(&self, context: &Context<Def, Alt>) -> ContextID {
        match (self, context) {
            (&Device::Default(ref device), &Context::Default(ref context)) => {
                device.context_id(context)
            }
            (&Device::Alternate(ref device), &Context::Alternate(ref context)) => {
                device.context_id(context)
            }
            _ => panic!("Incompatible context!"),
        }
    }

    /// Returns various information about the surface attached to a context.
    ///
    /// This includes, most notably, the OpenGL framebuffer object needed to render to the surface.
    pub fn context_surface_info(
        &self,
        context: &Context<Def, Alt>,
    ) -> Result<Option<SurfaceInfo>, Error> {
        match (self, context) {
            (&Device::Default(ref device), &Context::Default(ref context)) => {
                device.context_surface_info(context)
            }
            (&Device::Alternate(ref device), &Context::Alternate(ref context)) => {
                device.context_surface_info(context)
            }
            _ => Err(Error::IncompatibleContext),
        }
    }
}