]> git.tdb.fi Git - libs/gl.git/blob - source/vertexsetup.cpp
Move vertex array object management out of Mesh
[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(false),
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();
32 }
33
34 void VertexSetup::set_index_buffer(const Buffer &ibuf)
35 {
36         index_buffer = &ibuf;
37         update();
38 }
39
40 void VertexSetup::update() const
41 {
42         if(current()!=this)
43         {
44                 dirty = true;
45                 return;
46         }
47
48         Bind bind_vbuf(array->get_buffer(), ARRAY_BUFFER);
49
50         const VertexFormat &fmt = array->get_format();
51         unsigned stride = get_stride(fmt)*sizeof(float);
52         float *ptr = 0;
53         for(const unsigned char *c=fmt.begin(); c!=fmt.end(); ++c)
54         {
55                 unsigned t = get_component_type(*c);
56                 if(t>=get_component_type(ATTRIB1))
57                         t -= get_component_type(ATTRIB1);
58                 unsigned sz = get_component_size(*c);
59                 if(*c==COLOR4_UBYTE)
60                         glVertexAttribPointer(t, 4, GL_UNSIGNED_BYTE, true, stride, ptr);
61                 else
62                         glVertexAttribPointer(t, sz, GL_FLOAT, false, stride, ptr);
63                 glEnableVertexAttribArray(t);
64                 ptr += sz;
65         }
66
67         glBindBuffer(ELEMENT_ARRAY_BUFFER, index_buffer->get_id());
68 }
69
70 void VertexSetup::bind() const
71 {
72         if(set_current(this))
73         {
74                 glBindVertexArray(id);
75                 if(dirty)
76                 {
77                         update();
78                         dirty = false;
79                 }
80         }
81 }
82
83 void VertexSetup::unbind()
84 {
85         if(set_current(0))
86                 glBindVertexArray(0);
87 }
88
89 } // namespace GL
90 } // namespace Msp