Search code examples
c++opengltexturesglutglew

Create texture from sprite_sheet coordinates


I have a sprite_sheet (example sheet):

This is an example, this is not my own authority.

I loaded as vector data and I need to make a new texture from a specified area. Like this:

const std::vector <char> image_data = LoadPNG("sprite_sheet.png"); // This works.

glMakeTexture([0, 0], [50, 50], configs, image_data) //to display only one sqm.

enter image description here

But i don't know how, 'couse mostly GL functions only works in full area, like glTexImage2D.

// Only have width and height, the bottomLeft coords is 0, 0 -- I want to change this.
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(_sprite_sheet.data[0]));

Have a way to do that without load the full sprite_sheet as a texture?

OBS: I'm using picoPNG to decode PNG and I CAN load png, but not make a texture from specified area.


Solution

  • Because you show no code I assume that:

    char *data; // data of 8-bit per sample RGBA image
    int w, h; // size of the image
    int sx, sy, sw, sh; // position and size of area you want to crop.
    

    glTexImage2D does support regions-of-interest. You do it as follows:

    glPixelStorei(GL_UNPACK_ROW_LENGTH, w);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // LodePNG tightly packs everything
    glTexImage2D(GL_TEXTURE_2D, level, internalFormat, sw, sh, border, format, type, data);