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