Setting indices to VBO: Can't seem to make it work

Hi!

So I’m trying to make a simple square using two GL_TRIANGLES using four vertices and can’t seem to make it work. This is what I’m ending up with:

Code:
.h

ofVbo vbo;
ofShader shader;

.cpp

void ofApp::draw(){
    
    ofVec3f v0(0.5f,  0.5f, 0.0f);
    ofVec3f v1(0.5f, -0.5f, 0.0f);
    ofVec3f v2(-0.5f, -0.5f, 0.0f);
    ofVec3f v3( -0.5f,  0.5f, 0.0f);
    
    vector<ofVec3f> vertices;
    
    vertices.push_back(v0);
    vertices.push_back(v1);
    vertices.push_back(v2);
    vertices.push_back(v3);
    
    for(int i = 0; i<vertices.size(); i++){
        vertices[i].x *= ofGetWidth()/2;
        vertices[i].y *= ofGetHeight()/2;
    }
    
    const ofIndexType indices[] = {2, 3, 1, 0, 1, 2};
    
    vbo.setVertexData(&vertices[0], int(vertices.size()), GL_STATIC_DRAW);
    vbo.setIndexData(&indices[0], 6, GL_STATIC_DRAW);

    ofPushMatrix();
    ofTranslate(ofGetWidth()/2, ofGetHeight()/2);
    
    shader.begin();
    vbo.draw(GL_TRIANGLES, 0, 6);
    shader.end();
    
    ofPopMatrix();
}

What am I doing wrong?

Can you try replacing GL_TRIANGLES with GL_TRIANGLE_STRIP?

Still doesn’t do what I’m trying to do

Vertices are labelled for troubleshooting. According to the indices, the triangles should be (0, 1, 2) and (0, 2, 3) but whatever I do, it’s drawing (0, 1, 2), (1, 2, 3).

Looking at your vertices, they seem to be incorrect to draw a square. The following vertices should work:
(0.5, 0.5)
(0.5, -0.5)
(-0.5, 0.5)
(-0.5, -0.5)

In a triangle strip, the last two vertices are used to generate the triangle.

More info on it here: https://en.wikipedia.org/wiki/Triangle_strip

That worked! Thanks a lot!

Any idea why I couldn’t do it as two separate triangles, though? (which still doesn’t seem to work)

EDIT: Got it working! Hadn’t changed the indices after changing the vertex coordinates. Thanks again @ilmenite!

Oh well. It seems to work, but if I don’t fill it, I’m noticing that it’s three triangles instead of two… that’s not entirely correct, is it?

Using

    vbo.draw(GL_TRIANGLE_STRIP, 0, 4);

seems to solve…

    ofVec3f v0(-0.5f,  0.5f, 0.0f);
    ofVec3f v1(0.5f, 0.5f, 0.0f);
    ofVec3f v2(0.5f, -0.5f, 0.0f);
    ofVec3f v3(-0.5f,  -0.5f, 0.0f);
    
    vector&lt;ofVec3f&gt; vertices;
    
    vertices.push_back(v0);
    vertices.push_back(v1);
    vertices.push_back(v2);
    vertices.push_back(v3);
    
    for(int i = 0; i&lt;vertices.size(); i++){
        vertices[i].x *= ofGetWidth()/2;
        vertices[i].y *= ofGetHeight()/2;
    }
    
    const ofIndexType indices[] = {0, 1, 2, 2, 3, 0};

should work with GL_TRIANGLES

No luck. :cry:

oh yeah you need to call drawElements if you are using indices

1 Like

Yes! Finally it’s drawing how it should. Thanks!

I’m just getting started in GL and VBOs… this stuff is messy.

Oh, I missed the indices part. My bad.