Saturday, September 19, 2009

GL_POINTS + Qt

GL_POINTS + Qt

There are a few ways to do 2D OpenGL: GL_POINTS, glDrawPixels/glPixelZoom, and 2D texture.

The strength of GL_POINTS is its simplicity, while its weakness is inability to scale in a way most people intend.
Basically, each point occupied exactly one pixel of the screen.  If a window size increase, the point is still drawn as a single pixel.
Therefore, some pixels in a window become background color.

Consequently, GL_POINTS can be a strong candidate for 2D graphics if the window will not be resized.

The following function shows the a call list function, as an example.

/// This example draw a red horizontal line made of individual points at
///   the very middle of its window.
GLuint GLPoint::makeCallList() {
    glClear(GL_COLOR_BUFFER_BIT);

    GLuint list = glGenLists(1);
    glNewList(list, GL_COMPILE);

    glColor3f(1.0f, 0.25f, 0.25f);
    glBegin(GL_POINTS);
    {
        int nRow = m_nHeight / 2;
        for (int i = 0; i < m_nWidth; ++i)
            glVertex2s(i, nRow);
    }
    glEnd();

    glEndList();

    return list;
}


Since we are doing 2D graphics, it is recommended to disable depth test, as shown in the following initialized function.

void GLPoint::initializeGL()
{
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glDisable(GL_DEPTH_TEST);    // we are going to do 2D OpenGL
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, m_nWidth, 0, m_nHeight, 0, 1);
    glMatrixMode(GL_MODELVIEW);

    callList = makeCallList();
}

An example Eclipse CDT / Qt project is stored at a public folder here.
The project file is valid for Eclipse CDT on Linux with Qt integration (Ubuntu 9.04 Juanty), but the main part should be applicable to most C++ environment.

Pinyo Taeprasartsit
August-September 2009