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