简体   繁体   中英

getting a region from texture atlas with opengl using soil

I want to map different regions of texture atlas to the different sides of a cube with opengl using soil. So far, I manage to map a single image to one of the sides of the cube :

int LoadTexture(const char*);

int texID;

void DrawCube(float width)
{
    float wd2 = width / 2;
    glColor3f(0, 0, 1);
    glBegin(GL_QUADS);

    //front
    glTexCoord2f(0, 1);
    glVertex3f(-wd2, -wd2, wd2);
    glTexCoord2f(1, 1);
    glVertex3f(wd2, -wd2, wd2);
    glTexCoord2f(1, 0);

    glVertex3f(wd2, wd2, wd2);
    glTexCoord2f(0, 0);

    glVertex3f(-wd2, wd2, wd2);

    //left side..
    //right side..
    //back..
    //top..
    //bottom..

    glEnd();
}

int LoadTexture(const char* tex) {
    texID = SOIL_load_OGL_texture(tex, 4, 0, 0);
    if (!texID) {
        cout << "Texture not loaded!\n";

    }
    return texID;
}

And in the init function :

glEnable(GL_TEXTURE_2D);
texID = LoadTexture("sas.jpg");
glBindTexture(GL_TEXTURE_2D, texID);

But my question is how do I get only one sprite of the whole texture ?

Here is the image : 图片

Texture coordinates map the vertices (points) of the geometry to a point in the texture image. Thereby it is specified which part of the texture is placed on an specific part of the geometry and together with the texture parameters (see glTexParameter ) it specifies how the geometry is wrapped by the texture.
In general, the lower left point of the texture is addressed by the texture coordinate (0, 0) and the upper right point of the texture is addressed by (1, 1).

Your texture consists of tiles in 8 columns and 4 rows. To place a single tile of the texture on a quad, the texture coordinates have to be split in the same way. The corners of a single tile are addressed like this:

float tiles_U = 8.0f;
float tiles_V = 4.0f;
float index_U = .... ; // index of the column in [0, tiles_U-1];
float index_V = .... ; // index of the row in [0, tiles_V-1];

float left_U  = index_U        / tiles_U;
float right_U = (index_U+1.0f) / tiles_U;

float top_V    = (tiles_V - index_V)        / tiles_V;
float bottom_V = (tiles_V - index_V - 1.0f) / tiles_V;

Apply that to your code like this:

float wd2 = width / 2;
glColor3f(0, 0, 1);
glBegin(GL_QUADS);

glTexCoord2f( left_U, top_V );
glVertex3f(-wd2, -wd2, wd2);

glTexCoord2f( right_U, top_V );
glVertex3f(wd2, -wd2, wd2);

glTexCoord2f( right_U, bottom_V );
glVertex3f(wd2, wd2, wd2);

glTexCoord2f( left_U, bottom_V );
glVertex3f(-wd2, wd2, wd2);

glEnd();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM