1 #include <msp/core/raii.h>
2 #include <msp/gl/extensions/arb_direct_state_access.h>
3 #include <msp/gl/extensions/arb_instanced_arrays.h>
4 #include <msp/gl/extensions/arb_vertex_array_object.h>
5 #include <msp/gl/extensions/arb_vertex_attrib_binding.h>
6 #include <msp/gl/extensions/arb_vertex_buffer_object.h>
7 #include <msp/gl/extensions/arb_vertex_shader.h>
11 #include "vertexarray.h"
12 #include "vertexsetup.h"
19 VertexSetup::VertexSetup():
25 static Require req(ARB_vertex_array_object);
26 if(ARB_direct_state_access)
27 glCreateVertexArrays(1, &id);
29 glGenVertexArrays(1, &id);
32 VertexSetup::~VertexSetup()
36 glDeleteVertexArrays(1, &id);
39 void VertexSetup::set_vertex_array(const VertexArray &a)
42 throw invalid_argument("VertexSetup::set_vertex_array");
48 void VertexSetup::set_instance_array(const VertexArray *a)
53 throw invalid_argument("VertexSetup::set_instance_array");
55 static Require req(ARB_instanced_arrays);
59 update(INSTANCE_ARRAY);
62 void VertexSetup::set_index_buffer(const Buffer &ibuf)
68 void VertexSetup::update(unsigned mask) const
70 static bool direct = ARB_direct_state_access && ARB_vertex_attrib_binding;
71 if(!direct && current()!=this)
78 update_vertex_array(*vertex_array, 0, 0, direct);
80 if(mask&INSTANCE_ARRAY)
83 update_vertex_array(*inst_array, 1, 1, direct);
89 glVertexArrayElementBuffer(id, index_buffer->get_id());
91 glBindBuffer(ELEMENT_ARRAY_BUFFER, index_buffer->get_id());
95 void VertexSetup::update_vertex_array(const VertexArray &array, unsigned binding, unsigned divisor, bool direct) const
97 Conditional<Bind> bind_vbuf(!direct, array.get_buffer(), ARRAY_BUFFER);
99 const VertexFormat &fmt = array.get_format();
100 unsigned stride = get_stride(fmt)*sizeof(float);
103 glVertexArrayVertexBuffer(id, binding, array.get_buffer()->get_id(), 0, stride);
104 glVertexArrayBindingDivisor(id, binding, divisor);
108 for(const unsigned char *c=fmt.begin(); c!=fmt.end(); ++c)
110 unsigned t = get_component_type(*c);
111 if(t>=get_component_type(ATTRIB1))
112 t -= get_component_type(ATTRIB1);
113 unsigned sz = get_component_size(*c);
117 glVertexArrayAttribFormat(id, t, 4, GL_UNSIGNED_BYTE, true, offset);
119 glVertexArrayAttribFormat(id, t, sz, GL_FLOAT, false, offset);
120 glVertexArrayAttribBinding(id, t, binding);
121 glEnableVertexArrayAttrib(id, t);
126 glVertexAttribPointer(t, 4, GL_UNSIGNED_BYTE, true, stride, reinterpret_cast<unsigned char *>(offset));
128 glVertexAttribPointer(t, sz, GL_FLOAT, false, stride, reinterpret_cast<float *>(offset));
129 if(ARB_instanced_arrays)
130 glVertexAttribDivisor(t, divisor);
131 glEnableVertexAttribArray(t);
133 offset += sz*sizeof(float);
137 void VertexSetup::bind() const
139 if(!vertex_array || !index_buffer)
140 throw invalid_operation("VertexSetup::bind");
142 if(set_current(this))
144 vertex_array->refresh();
146 inst_array->refresh();
147 glBindVertexArray(id);
156 void VertexSetup::unbind()
159 glBindVertexArray(0);