]> git.tdb.fi Git - libs/gl.git/blobdiff - source/buffer.cpp
Improve binding of buffers
[libs/gl.git] / source / buffer.cpp
index fbb1e159ee564df8b2d7816e459adda6312cfc20..1762b20482eaa45944d94529b7c044aa25c898b5 100644 (file)
@@ -8,13 +8,14 @@ using namespace std;
 namespace Msp {
 namespace GL {
 
+const Buffer *Buffer::bound[4] = { 0, 0, 0, 0 };
+
 Buffer::Buffer(BufferType t):
        type(t),
-       usage(STATIC_DRAW)
+       usage(STATIC_DRAW),
+       size(0)
 {
-       static RequireExtension _req_vbo("GL_ARB_vertex_buffer_object");
-       if(type==PIXEL_PACK_BUFFER || type==PIXEL_UNPACK_BUFFER)
-               static RequireExtension _req_pbo("GL_ARB_pixel_buffer_object");
+       require_buffer_type(type);
 
        glGenBuffersARB(1, &id);
 }
@@ -24,45 +25,47 @@ Buffer::~Buffer()
        glDeleteBuffersARB(1, &id);
 }
 
+void Buffer::require_buffer_type(BufferType type)
+{
+       static RequireExtension _req_vbo("GL_ARB_vertex_buffer_object");
+       if(type==PIXEL_PACK_BUFFER || type==PIXEL_UNPACK_BUFFER)
+               static RequireExtension _req_pbo("GL_ARB_pixel_buffer_object");
+}
+
 void Buffer::set_usage(BufferUsage u)
 {
        usage = u;
 }
 
-void Buffer::data(unsigned size, const void *d)
+void Buffer::data(unsigned sz, const void *d)
 {
        const Buffer *old = current(type);
        bind();
-       glBufferDataARB(type, size, d, usage);
+       glBufferDataARB(type, sz, d, usage);
+       size = sz;
        restore(old, type);
 }
 
-void Buffer::sub_data(unsigned offset, unsigned size, const void *d)
+void Buffer::sub_data(unsigned off, unsigned sz, const void *d)
 {
        const Buffer *old = current(type);
        bind();
-       glBufferSubDataARB(type, offset, size, d);
+       glBufferSubDataARB(type, off, sz, d);
        restore(old, type);
 }
 
 void Buffer::bind_to(BufferType t) const
 {
-       const Buffer *&ptr = binding(t);
-       if(ptr!=this)
-       {
+       if(t!=type)
+               require_buffer_type(t);
+       if(set_current(t, this))
                glBindBufferARB(t, id);
-               ptr = this;
-       }
 }
 
 void Buffer::unbind_from(BufferType type)
 {
-       const Buffer *&ptr = binding(type);
-       if(ptr)
-       {
+       if(set_current(type, 0))
                glBindBufferARB(type, 0);
-               ptr = 0;
-       }
 }
 
 const Buffer *&Buffer::binding(BufferType type)
@@ -77,6 +80,16 @@ const Buffer *&Buffer::binding(BufferType type)
        }
 }
 
+bool Buffer::set_current(BufferType type, const Buffer *buf)
+{
+       const Buffer *&ptr = binding(type);
+       if(ptr==buf)
+               return false;
+
+       ptr = buf;
+       return true;
+}
+
 void Buffer::restore(const Buffer *buf, BufferType type)
 {
        if(buf!=current(type))
@@ -88,7 +101,5 @@ void Buffer::restore(const Buffer *buf, BufferType type)
        }
 }
 
-const Buffer *Buffer::bound[4] = { 0, 0, 0, 0 };
-
 } // namespace GL
 } // namespace Msp