Reputation: 407
My goal is to render a list of segments using VBOs with different colors and if possible with different widths.
Each vertex is defined by:
class Vector2f {
public:
float x, y;
};
The list of segments consists in pairs of vertexes that define a segment.
Then I initialize the VBO:
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vector2f) * segments.size(), &segments[0], GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
And then I draw using:
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, sizeof(Vector2f), (void*)(sizeof(float) * 0));
glColor3f(0.0f, 1.0f, 0.0f);
glDrawArrays(GL_LINES, 0, segments.size());
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
In my example, I want to give to each segment a color. The color is previously defined and can only be 1 from 3 options. How can I do it? And can I optimize it by using indexes for color instead of repeating them all over?
If so, how?
Also, is it possible to define the width of each individual segment?
Upvotes: 2
Views: 397
Reputation: 52164
How can I do it?
Extend your vertex struct to contain color values:
class Vector2f
{
public:
float x, y;
unsigned char r, g, b;
};
And use GL_COLOR_ARRAY
+ glColorPointer()
:
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_FLOAT, sizeof(Vector2f), offsetof( Vector2f, x ) );
glColorPointer(3, GL_UNSIGNED_BYTE, sizeof(Vector2f), offsetof( Vector2f, r ) );
glDrawArrays(GL_LINES, 0, segments.size());
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
Also, is it possible to define the width of each individual segment?
Not really with fixed-function. You either end up with a glLineWidth()
+ draw-call per segment (losing the performance benefit of batching draw-calls) or converting the line into triangle geometry on the CPU (significantly more complicated).
Upvotes: 3