]> git.tdb.fi Git - libs/gui.git/blob - source/glcontext.cpp
Plug some memory leaks
[libs/gui.git] / source / glcontext.cpp
1 /* $Id$
2
3 This file is part of libmspgbase
4 Copyright © 2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <vector>
9 #include <msp/core/except.h>
10 #include "display.h"
11 #include "glcontext.h"
12 #include "window.h"
13
14 namespace Msp {
15 namespace Graphics {
16
17 GLOptions::GLOptions():
18         alpha(false),
19         stencil(false),
20         doublebuffer(true),
21         multisample(0)
22 { }
23
24
25 GLContext::GLContext(Display &d, const GLOptions &opts):
26         display(d)
27 {
28         std::vector<int> attribs;
29         
30         attribs.push_back(GLX_RGBA);
31         attribs.push_back(GLX_DEPTH_SIZE);
32         attribs.push_back(1);
33         
34         if(opts.alpha)
35         {
36                 attribs.push_back(GLX_ALPHA_SIZE);
37                 attribs.push_back(1);
38         }
39         
40         if(opts.stencil)
41         {
42                 attribs.push_back(GLX_STENCIL_SIZE);
43                 attribs.push_back(1);
44         }
45         
46         if(opts.doublebuffer)
47                 attribs.push_back(GLX_DOUBLEBUFFER);
48         
49         if(opts.multisample>0)
50         {
51                 attribs.push_back(GLX_SAMPLE_BUFFERS_ARB);
52                 attribs.push_back(opts.multisample);
53         }
54         
55         attribs.push_back(0);
56
57         ::Display *dpy=display.get_display();
58         XVisualInfo *vi=glXChooseVisual(dpy, DefaultScreen(dpy), &attribs.front());
59         if(!vi)
60                 throw Exception("Couldn't find a GLX visual");
61         context=glXCreateContext(dpy, vi, 0, true);
62
63         XSetWindowAttributes attr;
64         attr.colormap=XCreateColormap(dpy, DefaultRootWindow(dpy), vi->visual, AllocNone);
65
66         window=XCreateWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1024, 768, 0, vi->depth, InputOutput, vi->visual, CWColormap, &attr);
67
68         XFree(vi);
69
70         glXMakeCurrent(dpy, window, context);
71 }
72
73 GLContext::~GLContext()
74 {
75         glXDestroyContext(display.get_display(), context);
76         XDestroyWindow(display.get_display(), window);
77 }
78
79 void GLContext::attach(Window &wnd)
80 {
81         XReparentWindow(display.get_display(), window, wnd.get_handle(), 0, 0);
82         XMapWindow(display.get_display(), window);
83
84         wnd.signal_resize.connect(sigc::mem_fun(this, &GLContext::window_resized));
85         window_resized(wnd.get_width(), wnd.get_height());
86 }
87
88 void GLContext::swap_buffers()
89 {
90         glXSwapBuffers(display.get_display(), window);
91 }
92
93 void GLContext::window_resized(unsigned w, unsigned h)
94 {
95         XMoveResizeWindow(display.get_display(), window, 0, 0, w, h);
96         glViewport(0, 0, w, h);
97 }
98
99 } // namespace Graphics
100 } // namespace Msp