openGL: lines with shaders

Johnny Pauling picture Johnny Pauling · Jul 21, 2012 · Viewed 15.5k times · Source

How would I create a line (possibly colored) with shaders? I'm using programmable pipeline and I'm a beginner with openGL. I can't find an example on how to draw lines with shaders.. I suppose I have to load a VAO (vertices array object) into the shader, but then what? What functions should I use and how?

Answer

torbjoernwh picture torbjoernwh · Jul 21, 2012

First, set use the shaderprogram. Then draw lines using glDrawArrays (or Elements if your data is indexed) with mode=GL_LINES or one of the other line drawing modes.

Here's a code example for 2D lines with different color in each end. If shading mode is set to smooth, OpenGL will interpolate the colors along the line.

struct LineSegment_t
{
  float x1, y1;
  float r1,g1,b1,a1;
  float x2, y2;
  float r2,g2,b2,a2;
};

int num_verts = lines.size()*2;
glBindVertexArray( line_vao ); // setup for the layout of LineSegment_t
glBindBuffer(GL_ARRAY_BUFFER, LineBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(LineSegment_t)/2 * num_verts, &lines[0], GL_DYNAMIC_DRAW);
glDrawArrays(GL_LINES, 0, num_verts );

If you need more flexibility, you can draw lines using triangles by creating a rectangle (4 points) from the line endpoints. In 2D you can create the 4 points by translating the endpoints using the line normal / perpendicular (-y,x) by the desired line with. In 3D you need to make sure the triangles are aligned to the camera as in billboarding.