How to draw a circle using VBO in ES2.0

Here’s some code fragments for rendering a circle. I haven’t compiled or run this code, so there’s a possibility of (hopefully minor) typos.

To prepare the VBO, which would be done once:

// Number of segments the circle is divided into.
const unsigned DIV_COUNT = 32;

// Will use a triangle fan rooted at the origin to draw the circle. So one additional
// point is needed for the origin, and another one because the first point is repeated
// as the last one to close the circle.
GLfloat* coordA = new GLfloat[(DIV_COUNT + 2) * 2];

// Origin.
unsigned coordIdx = 0;
coordA[coordIdx++] = 0.0f;
coordA[coordIdx++] = 0.0f;

// Calculate angle increment from point to point, and its cos/sin.
float angInc = 2.0f * M_PI / static_cast<float>(DIV_COUNT);
float cosInc = cos(angInc);
float sinInc = sin(angInc);

// Start with vector (1.0f, 0.0f), ...
coordA[coordIdx++] = 1.0f;
coordA[coordIdx++] = 0.0f;

// ... and then rotate it by angInc for each point.
float xc = 1.0f;
float yc = 0.0f;
for (unsigned iDiv = 1; iDiv < DIV_COUNT; ++iDiv) {
    float xcNew = cosInc * xc - sinInc * yc;
    yc = sinInc * xc + cosInc * yc;
    xc = xcNew;

    coordA[coordIdx++] = xc;
    coordA[coordIdx++] = yc;
}

// Repeat first point as last point to close circle.
coordA[coordIdx++] = 1.0f;
coordA[coordIdx++] = 0.0f;

GLuint vboId = 0;
glGenBuffers(1, &circVboId);
glBindBuffer(GL_ARRAY_BUFFER, circVboId);
glBufferData(GL_ARRAY_BUFFER, (DIV_COUNT + 2) * 2 * sizeof(GLfloat), coordA, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

delete[] coordA;

Then to draw, with posLoc being the location of the vertex attribute for the position:

glBindBuffer(GL_ARRAY_BUFFER, circVboId);
glVertexAttribPointer(posLoc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(posLoc);

glDrawArrays(GL_TRIANGLE_FAN, 0, DIV_COUNT + 2);

glBindBuffer(GL_ARRAY_BUFFER, 0);

Leave a Comment