]> git.tdb.fi Git - libs/gl.git/blob - source/vertexsetup.cpp
Only update the changed parts of VertexSetup
[libs/gl.git] / source / vertexsetup.cpp
1 #include <msp/gl/extensions/arb_vertex_array_object.h>
2 #include <msp/gl/extensions/arb_vertex_buffer_object.h>
3 #include <msp/gl/extensions/arb_vertex_shader.h>
4 #include "buffer.h"
5 #include "gl.h"
6 #include "vertexarray.h"
7 #include "vertexsetup.h"
8
9 namespace Msp {
10 namespace GL {
11
12 VertexSetup::VertexSetup():
13         dirty(0),
14         array(0),
15         index_buffer(0)
16 {
17         static Require req(ARB_vertex_array_object);
18         glGenVertexArrays(1, &id);
19 }
20
21 VertexSetup::~VertexSetup()
22 {
23         if(current()==this)
24                 unbind();
25         glDeleteVertexArrays(1, &id);
26 }
27
28 void VertexSetup::set_vertex_array(const VertexArray &a)
29 {
30         array = &a;
31         update(VERTEX_ARRAY);
32 }
33
34 void VertexSetup::set_index_buffer(const Buffer &ibuf)
35 {
36         index_buffer = &ibuf;
37         update(INDEX_BUFFER);
38 }
39
40 void VertexSetup::update(unsigned mask) const
41 {
42         if(current()!=this)
43         {
44                 dirty |= mask;
45                 return;
46         }
47
48         if(mask&VERTEX_ARRAY)
49                 update_vertex_array();
50
51         if(mask&INDEX_BUFFER)
52                 glBindBuffer(ELEMENT_ARRAY_BUFFER, index_buffer->get_id());
53 }
54
55 void VertexSetup::update_vertex_array() const
56 {
57         Bind bind_vbuf(array->get_buffer(), ARRAY_BUFFER);
58
59         const VertexFormat &fmt = array->get_format();
60         unsigned stride = get_stride(fmt)*sizeof(float);
61         float *ptr = 0;
62         for(const unsigned char *c=fmt.begin(); c!=fmt.end(); ++c)
63         {
64                 unsigned t = get_component_type(*c);
65                 if(t>=get_component_type(ATTRIB1))
66                         t -= get_component_type(ATTRIB1);
67                 unsigned sz = get_component_size(*c);
68                 if(*c==COLOR4_UBYTE)
69                         glVertexAttribPointer(t, 4, GL_UNSIGNED_BYTE, true, stride, ptr);
70                 else
71                         glVertexAttribPointer(t, sz, GL_FLOAT, false, stride, ptr);
72                 glEnableVertexAttribArray(t);
73                 ptr += sz;
74         }
75 }
76
77 void VertexSetup::bind() const
78 {
79         if(set_current(this))
80         {
81                 glBindVertexArray(id);
82                 if(dirty)
83                 {
84                         update(dirty);
85                         dirty = 0;
86                 }
87         }
88 }
89
90 void VertexSetup::unbind()
91 {
92         if(set_current(0))
93                 glBindVertexArray(0);
94 }
95
96 } // namespace GL
97 } // namespace Msp