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