]> git.tdb.fi Git - libs/gl.git/blob - source/buffer.cpp
Rework exceptions
[libs/gl.git] / source / buffer.cpp
1 #include <stdexcept>
2 #include "arb_vertex_buffer_object.h"
3 #include "extension.h"
4 #include "buffer.h"
5
6 using namespace std;
7
8 namespace Msp {
9 namespace GL {
10
11 Buffer::Buffer(BufferType t):
12         type(t),
13         usage(STATIC_DRAW)
14 {
15         static RequireExtension _req_vbo("GL_ARB_vertex_buffer_object");
16         if(type==PIXEL_PACK_BUFFER || type==PIXEL_UNPACK_BUFFER)
17                 static RequireExtension _req_pbo("GL_ARB_pixel_buffer_object");
18
19         glGenBuffersARB(1, &id);
20 }
21
22 Buffer::~Buffer()
23 {
24         glDeleteBuffersARB(1, &id);
25 }
26
27 void Buffer::set_usage(BufferUsage u)
28 {
29         usage = u;
30 }
31
32 void Buffer::data(unsigned size, const void *d)
33 {
34         const Buffer *old = current(type);
35         bind();
36         glBufferDataARB(type, size, d, usage);
37         restore(old, type);
38 }
39
40 void Buffer::sub_data(unsigned offset, unsigned size, const void *d)
41 {
42         const Buffer *old = current(type);
43         bind();
44         glBufferSubDataARB(type, offset, size, d);
45         restore(old, type);
46 }
47
48 void Buffer::bind_to(BufferType t) const
49 {
50         const Buffer *&ptr = binding(t);
51         if(ptr!=this)
52         {
53                 glBindBufferARB(t, id);
54                 ptr = this;
55         }
56 }
57
58 void Buffer::unbind_from(BufferType type)
59 {
60         const Buffer *&ptr = binding(type);
61         if(ptr)
62         {
63                 glBindBufferARB(type, 0);
64                 ptr = 0;
65         }
66 }
67
68 const Buffer *&Buffer::binding(BufferType type)
69 {
70         switch(type)
71         {
72         case ARRAY_BUFFER:         return bound[0];
73         case ELEMENT_ARRAY_BUFFER: return bound[1];
74         case PIXEL_PACK_BUFFER:    return bound[2];
75         case PIXEL_UNPACK_BUFFER:  return bound[3];
76         default: throw invalid_argument("Buffer::binding");
77         }
78 }
79
80 void Buffer::restore(const Buffer *buf, BufferType type)
81 {
82         if(buf!=current(type))
83         {
84                 if(buf)
85                         buf->bind_to(type);
86                 else
87                         unbind_from(type);
88         }
89 }
90
91 const Buffer *Buffer::bound[4] = { 0, 0, 0, 0 };
92
93 } // namespace GL
94 } // namespace Msp