macosopenglimmediate-mode

OpenGL Immediate Mode textures not working


I am attempting to build a simple project using immediate mode textures. Unfortunately, when I render, the GL color shows up rather than the texture. I've searched around for solutions, but found no meaningful difference between online examples and my code.

I've reduced it to a minimal failing example, which I have provided here. If my understanding is correct, this should produce a textured quad, with corners of black, red, green, and blue. Unfortunately, it appears purple, as if it's ignoring the texture completely. What am I doing wrong?

#include <glut.h>

GLuint tex;

void displayFunc() {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, tex);
    glBegin(GL_TRIANGLE_STRIP);
    glColor3f(0.5, 0, 1);
    glTexCoord2f(0.0, 0.0);
    glVertex2f(-1.0, -1.0);

    glTexCoord2f(1.0, 0.0);
    glVertex2f(1.0, -1.0);

    glTexCoord2f(0.0, 1.0);
    glVertex2f(-1.0, 1.0);

    glTexCoord2f(1.0, 1.0);
    glVertex2f(1.0, 1.0);
    glEnd();

    glutSwapBuffers();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowPosition(0, 0);
    glutInitWindowSize(640, 480);
    glutCreateWindow("Test");
    glutDisplayFunc(displayFunc);

    GLubyte textureData[] = { 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0 };
    GLsizei width = 2;
    GLsizei height = 2;

    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB8, GL_UNSIGNED_BYTE, (GLvoid*)textureData);

    glutMainLoop();
}

The output: quad is purple

Also possibly worth mentioning:

I am building this project on a Mac (running El Capitan 10.11.1)

Graphics card: NVIDIA GeForce GT 650M 1024 MB


Solution

  • You're passing an invalid argument to glTexImage2D(). GL_RGB8 is not one of the supported values for the 7th (format) argument. The correct value is GL_RGB.

    Sized formats, like GL_RGB8, are used for the internalFormat argument. In that case, the value defines both the number of components and the size of each component used for the internal storage of the texture.

    The format and type parameters define the data you pass in. For these, the format only defined the number of components, while the type defines the type and size of each component.

    Whenever you have problems with your OpenGL code, make sure that you call glGetError() to check for errors. In this case, you would see a GL_INVALID_ENUM error caused by your glTexImage2D() call.