Search code examples
c++opengltexturestexture2dosx-snow-leopard

how to draw textures using stb_image.c


I want to load this picture into a 2d texture and then draw it onto the screen. The main problem is loading the picture into a texture variable. The follow code output the correct width and height and rgba but how do I put the data into a 3d texture.

#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
/* more includes... */
#include "stb_image.h"

using namespace std;

int main(int argc, char** argv) {
    int x,y,n;
    unsigned char *data = stbi_load("png.png", &x, &y, &n, 0);
    if (data == NULL) {
        // error
        cout << "Error, data was null";
    } else {
        // process
        cout << data << endl << endl;
    }
    stbi_image_free(data);

    cout << x << endl << y << endl << n;
    return 0;
}

Solution

  • First you need

    • a drawable (window, PBuffer, framebuffer)
    • a OpenGL context associated with the drawable

    You can use GLFW, SDL or GLUT for getting those (personally I recommend GLFW, if you need only one single window).

    Create a texture name with

    GLuint texture_name;

    void somefunction(…)
    {
    glGenTextures(1, &texture_name);
    glBindTexture(GL_TEXTURE_2D, texture_name);
    glPixelStorei(…); /* multiple calls to glPixelStorei describing the layout of the data to come */
    glTexImage2D(GL_TEXTURE_2D, miplevel, internal_format, width, height, border, format, type, data);
    }
    

    This was the quick and dirty explanation how to load it. Drawing is another business. I suggest you read some OpenGL tutorials. Google for "NeHe" or "Lighthouse3D", or "Arcsynthesis OpenGL tutorial".