简体   繁体   中英

OpenGL - Easiest way to draw a square with a texture

Usually I draw a square with a texture like this:

  • Create a VBO with 4 coordinates (A,B,C,D for the square)
  • Create a EBO with 4 indices (A,C,D and B,C,D) telling that I want to draw a square out of 2 triangles.
  • Draw this elements with a texture

Isn't there an easiest way without having a EBO array?

Because it is not very handy to use... If I want to use like this:

VAO = [-0.8f, 0.5f, 0.0f, ...]

EBO = [0, 1, 3, 1, 2, 3, ...]

Then I need to remove a square from my VAO... then I also need to remove the indices from my EBO array and re-arrange it. Is there a better way to do this?

If you really only want to draw a square with a texture on it, you should consider make a new empty VAO, and just call glDrawArrays(GL_TRIANGLE_STRIP, 0,3);

The vertex shader then looks like this:

out vec2 mapping;

void main()
{
    float size = 1.0f;

    vec2 offset;
    switch(gl_VertexID)
    {
    case 0:
        //Bottom-left
        mapping = vec2(0.0f, 0.0f);
        offset = vec2(-size, -size);
        break;
    case 1:
        //Top-left
        mapping = vec2(0.0f, 1.0f);
        offset = vec2(-size, size);
        break;
    case 2:
        //Bottom-right
        mapping = vec2(1.0, 0.0);
        offset = vec2(size, -size);
        break;
    case 3:
        //Top-right
        mapping = vec2(1.0, 1.0);
        offset = vec2(size, size);
        break;
    }

     gl_Position = vec4(offset, 0.0f, 1.0f);
}

The mapping variable tells the fragmentshader what the texture coordinates are.

Isn't there an easiest way without having a EBO array?

Duplicate your vertices & use glDrawArrays() .

You can use DrawArray to plot the indices.

Something like this:

Vertex2D* vertex = (Vertex2D*) vbo->lock();
        vertex[0].x = x[0]; vertex[0].y = y[0]; vertex[0].u = u[0]; vertex[0].v = v[0]; vertex[0].color = color;
        vertex[1].x = x[0]; vertex[1].y = y[1]; vertex[1].u = u[0]; vertex[1].v = v[1]; vertex[1].color = color;
        vertex[2].x = x[1]; vertex[2].y = y[1]; vertex[2].u = u[1]; vertex[2].v = v[1]; vertex[2].color = color;
        vertex[3].x = x[1]; vertex[3].y = y[0]; vertex[3].u = u[1]; vertex[3].v = v[0]; vertex[3].color = color;
vbo->unlock();

shader->bind();
vbo->bind();
vao->bind();
tex->bind();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
tex->unbind();
vao->unbind();
vbo->unbind();
shader->unbind();

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